diff --git a/src/bip32.cpp b/src/bip32.cpp index 6423974..6ba946a 100644 --- a/src/bip32.cpp +++ b/src/bip32.cpp @@ -114,6 +114,43 @@ static bool HmacSha512(const unsigned char* key, int keyLen, len == 64; } +static bool PrivateKeyToCompressedPubKey(const std::vector& privateKey, + unsigned char out[33], + std::string& errorOut) +{ + if (!IsValidPrivateKey(privateKey)) + { + errorOut = "private key is invalid"; + return false; + } + + BIGNUM* bn = BN_bin2bn(&privateKey[0], 32, NULL); + BN_CTX* ctx = BN_CTX_new(); + EC_GROUP* group = EC_GROUP_new_by_curve_name(NID_secp256k1); + EC_POINT* pub = group ? EC_POINT_new(group) : NULL; + + bool ok = false; + if (bn && ctx && group && pub && + EC_POINT_mul(group, pub, bn, NULL, NULL, ctx)) + { + size_t n = EC_POINT_point2oct(group, pub, POINT_CONVERSION_COMPRESSED, + out, 33, ctx); + ok = n == 33; + } + + BN_free(bn); + BN_CTX_free(ctx); + EC_POINT_free(pub); + EC_GROUP_free(group); + + if (!ok) + { + errorOut = "could not serialize parent public key"; + return false; + } + return true; +} + bool BIP39EntropyToMnemonic(const std::vector& entropy, std::string& mnemonicOut, std::string& errorOut) @@ -284,10 +321,10 @@ bool BIP32MasterFromSeed(const std::vector& seed, return true; } -bool BIP32DeriveHardenedChild(const BIP32PrivateNode& parent, - unsigned int childIndex, - BIP32PrivateNode& childOut, - std::string& errorOut) +bool BIP32DeriveChild(const BIP32PrivateNode& parent, + unsigned int childNumber, + BIP32PrivateNode& childOut, + std::string& errorOut) { childOut.privateKey.clear(); childOut.chainCode.clear(); @@ -297,20 +334,21 @@ bool BIP32DeriveHardenedChild(const BIP32PrivateNode& parent, errorOut = "parent private key or chain code is invalid"; return false; } - if (childIndex >= 0x80000000U) + unsigned char data[37]; + if (childNumber & BIP32_HARDENED) { - errorOut = "child index must be non-hardened; hardening is applied here"; - return false; + data[0] = 0x00; + memcpy(data + 1, &parent.privateKey[0], 32); } - - const unsigned int hardened = childIndex | 0x80000000U; - unsigned char data[37]; - data[0] = 0x00; - memcpy(data + 1, &parent.privateKey[0], 32); - data[33] = (unsigned char)((hardened >> 24) & 0xff); - data[34] = (unsigned char)((hardened >> 16) & 0xff); - data[35] = (unsigned char)((hardened >> 8) & 0xff); - data[36] = (unsigned char)(hardened & 0xff); + else + { + if (!PrivateKeyToCompressedPubKey(parent.privateKey, data, errorOut)) + return false; + } + data[33] = (unsigned char)((childNumber >> 24) & 0xff); + data[34] = (unsigned char)((childNumber >> 16) & 0xff); + data[35] = (unsigned char)((childNumber >> 8) & 0xff); + data[36] = (unsigned char)(childNumber & 0xff); unsigned char I[64]; if (!HmacSha512(&parent.chainCode[0], 32, data, sizeof(data), I)) @@ -363,4 +401,43 @@ bool BIP32DeriveHardenedChild(const BIP32PrivateNode& parent, return true; } +bool BIP32DerivePath(const BIP32PrivateNode& root, + const std::vector& path, + BIP32PrivateNode& nodeOut, + std::string& errorOut) +{ + nodeOut.privateKey.clear(); + nodeOut.chainCode.clear(); + errorOut.clear(); + if (!IsValidPrivateKey(root.privateKey) || root.chainCode.size() != 32) + { + errorOut = "root private key or chain code is invalid"; + return false; + } + + BIP32PrivateNode cur = root; + for (size_t i = 0; i < path.size(); i++) + { + BIP32PrivateNode next; + if (!BIP32DeriveChild(cur, path[i], next, errorOut)) + return false; + cur = next; + } + nodeOut = cur; + return true; +} + +bool BIP32DeriveHardenedChild(const BIP32PrivateNode& parent, + unsigned int childIndex, + BIP32PrivateNode& childOut, + std::string& errorOut) +{ + if (childIndex >= BIP32_HARDENED) + { + errorOut = "child index must be non-hardened; hardening is applied here"; + return false; + } + return BIP32DeriveChild(parent, childIndex | BIP32_HARDENED, childOut, errorOut); +} + } // namespace bitflash diff --git a/src/bip32.h b/src/bip32.h index a029444..e9862d5 100644 --- a/src/bip32.h +++ b/src/bip32.h @@ -5,7 +5,7 @@ // // This module is deliberately independent from wallet.dat and GUI code. It is // the auditable foundation: mnemonic generation/validation, seed derivation, -// and hardened private child derivation over secp256k1. +// and private child derivation over secp256k1. #ifndef BITFLASH_BIP32_H #define BITFLASH_BIP32_H @@ -16,6 +16,8 @@ namespace bitflash { +static const unsigned int BIP32_HARDENED = 0x80000000U; + struct BIP32PrivateNode { std::vector privateKey; // 32-byte scalar @@ -43,6 +45,16 @@ bool BIP32MasterFromSeed(const std::vector& seed, BIP32PrivateNode& nodeOut, std::string& errorOut); +bool BIP32DeriveChild(const BIP32PrivateNode& parent, + unsigned int childNumber, + BIP32PrivateNode& childOut, + std::string& errorOut); + +bool BIP32DerivePath(const BIP32PrivateNode& root, + const std::vector& path, + BIP32PrivateNode& nodeOut, + std::string& errorOut); + bool BIP32DeriveHardenedChild(const BIP32PrivateNode& parent, unsigned int childIndex, BIP32PrivateNode& childOut, diff --git a/src/db.cpp b/src/db.cpp index 294920b..b7e7b91 100644 --- a/src/db.cpp +++ b/src/db.cpp @@ -554,6 +554,7 @@ bool CWalletDB::LoadWallet(vector& vchDefaultKeyRet) // Whether wallet.dat actually carried a mining mode, as opposed to just the // ancient fGenerateBitcoins flag. See the reconciliation further down. bool fHaveStoredMineMode = false; + bool fHaveStoredHDCoinType = false; vchDefaultKeyRet.clear(); // Satoshi's "todo: shouldn't we catch exceptions" sat here since 2009, and @@ -651,6 +652,23 @@ bool CWalletDB::LoadWallet(vector& vchDefaultKeyRet) { ssValue >> nHDNext; } + else if (strType == "hdschema") + { + ssValue >> nHDKeySchema; + } + else if (strType == "hdcointype") + { + ssValue >> nHDCoinType; + fHaveStoredHDCoinType = true; + } + else if (strType == "hdreceivenext") + { + ssValue >> nHDReceiveNext; + } + else if (strType == "hdchangenext") + { + ssValue >> nHDChangeNext; + } else if (strType == "pool") { int64 nIndex; @@ -707,6 +725,38 @@ bool CWalletDB::LoadWallet(vector& vchDefaultKeyRet) return false; } + if (HaveHDSeed()) + { + if (nHDKeySchema == HD_SCHEMA_NONE) + { + nHDKeySchema = HD_SCHEMA_LEGACY; + printf("LoadWallet: deterministic seed has no schema metadata; " + "treating it as legacy m/index'\n"); + } + else if (nHDKeySchema != HD_SCHEMA_LEGACY && + nHDKeySchema != HD_SCHEMA_BIP44) + { + printf("LoadWallet: deterministic wallet schema %d (%s) is not " + "supported by this build\n", + nHDKeySchema, HDKeySchemaName(nHDKeySchema).c_str()); + return false; + } + if (!fHaveStoredHDCoinType) + { + nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + printf("LoadWallet: deterministic seed has no BIP44 coin type metadata; " + "using provisional Bitflash coin type %u\n", nHDCoinType); + } + } + else + { + nHDKeySchema = HD_SCHEMA_NONE; + nHDNext = 0; + nHDReceiveNext = 0; + nHDChangeNext = 0; + nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + } + // fGenerateBitcoins and nMineMode only mean anything together, and a // wallet.dat can easily hold one without the other: Bitcoin 0.1.0 already // wrote fGenerateBitcoins when mining was toggled, years before this fork diff --git a/src/db.h b/src/db.h index 01b8583..90238bf 100644 --- a/src/db.h +++ b/src/db.h @@ -392,8 +392,11 @@ class CWalletDB : public CDB // twelve words are the user's to write down, and keeping a copy of them in // the file they are meant to protect defeats the point of having them. // - // "hdnext" is the next child index to derive, so the sequence a restore - // reproduces is the same one this wallet handed out. + // "hdschema" identifies the derivation layout. Wallets created before the + // field existed are inferred as HD_SCHEMA_LEGACY when a seed is present. + // "hdnext" is that legacy layout's next child index. The receive/change + // counters and coin type are reserved for the BIP44 layout that uses + // separate chains. bool ReadHDMaster(vector& vchMasterRet, vector& vchChainCodeRet) { vchMasterRet.clear(); @@ -413,6 +416,26 @@ class CWalletDB : public CDB return Write(string("hdnext"), nNext); } + bool WriteHDSchema(int nSchema) + { + return Write(string("hdschema"), nSchema); + } + + bool WriteHDCoinType(unsigned int nCoinType) + { + return Write(string("hdcointype"), nCoinType); + } + + bool WriteHDReceiveNext(unsigned int nNext) + { + return Write(string("hdreceivenext"), nNext); + } + + bool WriteHDChangeNext(unsigned int nNext) + { + return Write(string("hdchangenext"), nNext); + } + // Keys generated ahead of time and not yet handed out. The private key of // each is already stored under its own "key" record by AddKey; a "pool" // record only says that this one is still unspoken for. diff --git a/src/gui.cpp b/src/gui.cpp index 2335bf9..8f1d204 100644 --- a/src/gui.cpp +++ b/src/gui.cpp @@ -1247,6 +1247,11 @@ static void DrawWalletSafetyDialog() ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.25f, 1.0f), "No recovery phrase. Only a file backup can rebuild this wallet."); + if (g_recoveryAudit.fHaveSeed) + { + ImGui::Text("Derivation schema: %s", HDKeySchemaName(g_recoveryAudit.nSchema).c_str()); + ImGui::Text("BIP44 coin type: %u (provisional BITFLASH)", g_recoveryAudit.nCoinType); + } ImGui::Text("Phrase-backed spendable balance: %s BTF", FmtMoney(g_recoveryAudit.nRecoverableCredit).c_str()); ImGui::Text("Wallet.dat-only spendable balance: %s BTF", diff --git a/src/main.cpp b/src/main.cpp index 75647ba..efece6c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -181,7 +181,7 @@ static bool AddKeyIfMissing(const CKey& key) return AddKey(key); } -static bool DeriveNextHDWalletKey(vector& vchPubKeyRet, string& strErrorRet) +static bool DeriveNextHDReceiveKey(vector& vchPubKeyRet, string& strErrorRet) { vchPubKeyRet.clear(); CRITICAL_BLOCK(cs_keyPool) @@ -193,7 +193,12 @@ static bool DeriveNextHDWalletKey(vector& vchPubKeyRet, string& s } CKey key; - if (!DeriveHDKey(nHDNext, key, strErrorRet)) + unsigned int nIndex = 0; + if (nHDKeySchema == HD_SCHEMA_BIP44) + nIndex = nHDReceiveNext; + else + nIndex = nHDNext; + if (!DeriveHDKey(nIndex, key, strErrorRet)) return false; if (!AddKeyIfMissing(key)) { @@ -201,14 +206,77 @@ static bool DeriveNextHDWalletKey(vector& vchPubKeyRet, string& s return false; } - unsigned int nNext = nHDNext + 1; - if (!CWalletDB().WriteHDNext(nNext)) + unsigned int nNext = nIndex + 1; + if (nHDKeySchema == HD_SCHEMA_BIP44) + { + if (!CWalletDB().WriteHDReceiveNext(nNext)) + { + strErrorRet = "could not advance the receive derivation counter"; + return false; + } + nHDReceiveNext = nNext; + } + else + { + if (!CWalletDB().WriteHDNext(nNext)) + { + strErrorRet = "could not advance the derivation counter"; + return false; + } + nHDNext = nNext; + } + + vchPubKeyRet = key.GetPubKey(); + } + return true; +} + +static bool DeriveNextHDChangeKey(vector& vchPubKeyRet, string& strErrorRet) +{ + vchPubKeyRet.clear(); + CRITICAL_BLOCK(cs_keyPool) + { + if (!HaveHDSeed()) { - strErrorRet = "could not advance the derivation counter"; + strErrorRet = "no seed"; return false; } - nHDNext = nNext; + CKey key; + if (nHDKeySchema == HD_SCHEMA_BIP44) + { + if (!DeriveHDChangeKey(nHDChangeNext, key, strErrorRet)) + return false; + if (!AddKeyIfMissing(key)) + { + strErrorRet = "could not write the derived change key to wallet.dat"; + return false; + } + unsigned int nNext = nHDChangeNext + 1; + if (!CWalletDB().WriteHDChangeNext(nNext)) + { + strErrorRet = "could not advance the change derivation counter"; + return false; + } + nHDChangeNext = nNext; + } + else + { + if (!DeriveHDKey(nHDNext, key, strErrorRet)) + return false; + if (!AddKeyIfMissing(key)) + { + strErrorRet = "could not write the derived change key to wallet.dat"; + return false; + } + unsigned int nNext = nHDNext + 1; + if (!CWalletDB().WriteHDNext(nNext)) + { + strErrorRet = "could not advance the derivation counter"; + return false; + } + nHDNext = nNext; + } vchPubKeyRet = key.GetPubKey(); } return true; @@ -229,6 +297,40 @@ map > mapKeyPool; vector vchHDMaster; vector vchHDChainCode; unsigned int nHDNext = 0; +int nHDKeySchema = HD_SCHEMA_NONE; +unsigned int nHDReceiveNext = 0; +unsigned int nHDChangeNext = 0; +unsigned int nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + +string HDKeySchemaName(int nSchema) +{ + if (nSchema == HD_SCHEMA_LEGACY) + return "legacy-hd"; + if (nSchema == HD_SCHEMA_BIP44) + return "bip44"; + return "none"; +} + +std::vector HDLegacyPath(unsigned int nIndex) +{ + std::vector path; + path.push_back(nIndex | bitflash::BIP32_HARDENED); + return path; +} + +std::vector HDBIP44Path(unsigned int nCoinType, + unsigned int nAccount, + unsigned int nChain, + unsigned int nIndex) +{ + std::vector path; + path.push_back(HD_BIP44_PURPOSE | bitflash::BIP32_HARDENED); + path.push_back(nCoinType | bitflash::BIP32_HARDENED); + path.push_back(nAccount | bitflash::BIP32_HARDENED); + path.push_back(nChain); + path.push_back(nIndex); + return path; +} static bool ClearKeyPoolRecords(string& strErrorRet) { @@ -254,13 +356,59 @@ bool DeriveHDKey(unsigned int nIndex, CKey& keyRet, string& strErrorRet) strErrorRet = "no seed"; return false; } + if (nIndex >= bitflash::BIP32_HARDENED) + { + strErrorRet = "child index must be non-hardened; hardening is applied here"; + return false; + } + + bitflash::BIP32PrivateNode parent; + parent.privateKey = vchHDMaster; + parent.chainCode = vchHDChainCode; + + bitflash::BIP32PrivateNode child; + std::vector path = nHDKeySchema == HD_SCHEMA_BIP44 + ? HDBIP44Path(nHDCoinType, HD_BIP44_ACCOUNT, HD_BIP44_CHAIN_RECEIVE, nIndex) + : HDLegacyPath(nIndex); + if (!bitflash::BIP32DerivePath(parent, path, child, strErrorRet)) + return false; + + if (!keyRet.SetSecret(child.privateKey)) + { + strErrorRet = "derived scalar is not a usable key"; + return false; + } + return true; +} + +bool DeriveHDChangeKey(unsigned int nIndex, CKey& keyRet, string& strErrorRet) +{ + if (!HaveHDSeed()) + { + strErrorRet = "no seed"; + return false; + } + if (nIndex >= bitflash::BIP32_HARDENED) + { + strErrorRet = "child index must be non-hardened; hardening is applied here"; + return false; + } + + if (nHDKeySchema != HD_SCHEMA_BIP44) + return DeriveHDKey(nIndex, keyRet, strErrorRet); bitflash::BIP32PrivateNode parent; parent.privateKey = vchHDMaster; parent.chainCode = vchHDChainCode; bitflash::BIP32PrivateNode child; - if (!bitflash::BIP32DeriveHardenedChild(parent, nIndex, child, strErrorRet)) + if (!bitflash::BIP32DerivePath(parent, + HDBIP44Path(nHDCoinType, + HD_BIP44_ACCOUNT, + HD_BIP44_CHAIN_CHANGE, + nIndex), + child, + strErrorRet)) return false; if (!keyRet.SetSecret(child.privateKey)) @@ -307,20 +455,28 @@ bool SetHDSeedFromMnemonic(const string& strMnemonic, string& strErrorRet) return false; if (!CWalletDB().WriteHDMaster(master.privateKey, master.chainCode) || - !CWalletDB().WriteHDNext(1)) + !CWalletDB().WriteHDSchema(HD_SCHEMA_BIP44) || + !CWalletDB().WriteHDCoinType(HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL) || + !CWalletDB().WriteHDNext(0) || + !CWalletDB().WriteHDReceiveNext(1) || + !CWalletDB().WriteHDChangeNext(0)) { - strErrorRet = "could not write the seed to wallet.dat"; + strErrorRet = "could not write the seed metadata to wallet.dat"; return false; } vchHDMaster = master.privateKey; vchHDChainCode = master.chainCode; + nHDKeySchema = HD_SCHEMA_BIP44; + nHDReceiveNext = 1; + nHDChangeNext = 0; + nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; // Index 0 is spoken for before it is derived, so a failure below cannot // leave the pool free to hand it out as an ordinary key. The cost of // the counter being ahead of the derivation is one unused index; the // cost of the reverse is the default address and a pool key sharing a // derivation path. - nHDNext = 1; + nHDNext = 0; // Remember which address stops being the default, so it can be named // for what it is. Two entries reading "Your Address" -- one covered by @@ -372,15 +528,18 @@ void TopUpKeyPool() // without a seed uses anyway. It will not come back from the // phrase, and that is better than a node that cannot mine. string strError; - if (DeriveHDKey(nHDNext, key, strError)) + vector vchPubKey; + if (DeriveNextHDReceiveKey(vchPubKey, strError)) { - nHDNext++; - CWalletDB().WriteHDNext(nHDNext); + if (!CWalletDB().WritePool(nIndex, vchPubKey)) + return; + mapKeyPool[nIndex] = vchPubKey; + continue; } else { - printf("TopUpKeyPool() : derivation at index %u failed (%s), " - "falling back to a random key\n", nHDNext, strError.c_str()); + printf("TopUpKeyPool() : receive derivation failed (%s), " + "falling back to a random key\n", strError.c_str()); key.MakeNewKey(); } } @@ -3668,11 +3827,20 @@ WalletRecoveryAudit GetWalletRecoveryAudit() CRITICAL_BLOCK(cs_keyPool) { audit.fHaveSeed = HaveHDSeed(); + audit.nSchema = nHDKeySchema; audit.nDerivedKnown = nHDNext; + audit.nReceiveNext = nHDReceiveNext; + audit.nChangeNext = nHDChangeNext; + audit.nCoinType = nHDCoinType; + if (nHDKeySchema == HD_SCHEMA_BIP44) + audit.nDerivedKnown = nHDReceiveNext + nHDChangeNext + nHDNext; if (audit.fHaveSeed) { string strError; - for (unsigned int i = 0; i < nHDNext; i++) + unsigned int nReceiveDepth = nHDKeySchema == HD_SCHEMA_BIP44 + ? nHDReceiveNext + : nHDNext; + for (unsigned int i = 0; i < nReceiveDepth; i++) { CKey key; if (!DeriveHDKey(i, key, strError)) @@ -3684,6 +3852,36 @@ WalletRecoveryAudit GetWalletRecoveryAudit() } setDerivedPubKeys.insert(key.GetPubKey()); } + if (nHDKeySchema == HD_SCHEMA_BIP44) + { + int nSavedSchema = nHDKeySchema; + for (unsigned int i = 0; i < nHDChangeNext; i++) + { + CKey key; + if (!DeriveHDChangeKey(i, key, strError)) + { + audit.fDeriveComplete = false; + audit.strDeriveError = strprintf("change derivation failed at index %u: %s", + i, strError.c_str()); + break; + } + setDerivedPubKeys.insert(key.GetPubKey()); + } + nHDKeySchema = HD_SCHEMA_LEGACY; + for (unsigned int i = 0; i < nHDNext; i++) + { + CKey key; + if (!DeriveHDKey(i, key, strError)) + { + audit.fDeriveComplete = false; + audit.strDeriveError = strprintf("legacy compatibility derivation failed at index %u: %s", + i, strError.c_str()); + break; + } + setDerivedPubKeys.insert(key.GetPubKey()); + } + nHDKeySchema = nSavedSchema; + } } } @@ -3926,7 +4124,7 @@ bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, in if (HaveHDSeed()) { string strError; - if (!DeriveNextHDWalletKey(vchPubKey, strError)) + if (!DeriveNextHDChangeKey(vchPubKey, strError)) { printf("CreateTransaction() : could not derive a phrase-backed change key: %s\n", strError.c_str()); diff --git a/src/main.h b/src/main.h index 4886f55..cca2cad 100644 --- a/src/main.h +++ b/src/main.h @@ -147,21 +147,45 @@ extern map > mapKeyPool; // --- Deterministic wallet (BIP32) ----------------------------------------- // -// When a seed is present the key pool is derived from it -- m/0'/n, hardened, -// n increasing -- instead of being made of random keys. That is what lets a -// recovery phrase bring a wallet back: the same twelve words reproduce the same -// keys in the same order. +// When a seed is present today, the key pool is derived from it by the legacy +// Bitflash path -- m/index', hardened, index increasing -- instead of being +// made of random keys. That is what lets a recovery phrase bring a wallet back: +// the same twelve words reproduce the same keys in the same order. // -// A wallet without a seed keeps working exactly as before. Nothing here -// migrates an existing wallet on its own: the seed is created only when the -// user asks for a phrase and confirms they have written it down, because a -// phrase generated silently is a backup nobody has. +// BIP44 uses a different path family and separate receive/change counters. +// The schema fields below let new wallets opt into that without making old +// m/index' coins disappear. +// +// A wallet without a seed keeps working exactly as before. Existing seeded +// wallets keep their recorded schema. A new phrase uses BIP44, but it is still +// created only when the user asks for a phrase and confirms they have written +// it down, because a phrase generated silently is a backup nobody has. // // Empty until a seed exists. extern vector vchHDMaster; // 32-byte master private key (IL) extern vector vchHDChainCode; // 32 bytes (IR) extern unsigned int nHDNext; // next child index to derive +static const int HD_SCHEMA_NONE = 0; +static const int HD_SCHEMA_LEGACY = 1; // m/index' +static const int HD_SCHEMA_BIP44 = 2; // m/44'/coin_type'/account'/change/index +static const unsigned int HD_BIP44_PURPOSE = 44; +static const unsigned int HD_BIP44_ACCOUNT = 0; +static const unsigned int HD_BIP44_CHAIN_RECEIVE = 0; +static const unsigned int HD_BIP44_CHAIN_CHANGE = 1; +// Provisional until Bitflash has an official SLIP-0044 assignment. +// Proposed registry row: 4346950 | BITFLASH | Bitflash. +static const unsigned int HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL = 4346950; +extern int nHDKeySchema; +extern unsigned int nHDReceiveNext; // BIP44 external chain +extern unsigned int nHDChangeNext; // BIP44 internal chain +extern unsigned int nHDCoinType; // BIP44 coin_type' inline bool HaveHDSeed() { return vchHDMaster.size() == 32 && vchHDChainCode.size() == 32; } +string HDKeySchemaName(int nSchema); +std::vector HDLegacyPath(unsigned int nIndex); +std::vector HDBIP44Path(unsigned int nCoinType, + unsigned int nAccount, + unsigned int nChain, + unsigned int nIndex); // Install a seed derived from a mnemonic, replacing any existing one. The // default receiving key is derived immediately, so the next visible address is @@ -169,9 +193,12 @@ inline bool HaveHDSeed() { return vchHDMaster.size() == 32 && vchHDChainCode.siz // wallet untouched if the phrase is not valid. bool SetHDSeedFromMnemonic(const string& strMnemonic, string& strErrorRet); -// Derive the child at nIndex and return it as a key. Used by the key pool and -// by restore, which needs to run ahead of the pool. +// Derive the receiving child at nIndex for the wallet's active schema and +// return it as a key. Legacy seeded wallets use m/index'. BIP44 wallets use +// m/44'/coin_type'/0'/0/index. Used by the key pool and restore, which needs +// to run ahead of the pool. bool DeriveHDKey(unsigned int nIndex, CKey& keyRet, string& strErrorRet); +bool DeriveHDChangeKey(unsigned int nIndex, CKey& keyRet, string& strErrorRet); // Fill the pool back up to KEYPOOL_SIZE. Every key it creates is written to // wallet.dat before it is offered to anybody. @@ -221,7 +248,11 @@ struct WalletRecoveryAudit { bool fHaveSeed; bool fDeriveComplete; + int nSchema; unsigned int nDerivedKnown; + unsigned int nReceiveNext; + unsigned int nChangeNext; + unsigned int nCoinType; int nRecoverableTx; int nLegacyTx; int nRecoverableImmatureTx; @@ -236,7 +267,11 @@ struct WalletRecoveryAudit { fHaveSeed = false; fDeriveComplete = true; + nSchema = HD_SCHEMA_NONE; nDerivedKnown = 0; + nReceiveNext = 0; + nChangeNext = 0; + nCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; nRecoverableTx = 0; nLegacyTx = 0; nRecoverableImmatureTx = 0; diff --git a/src/selftest.cpp b/src/selftest.cpp index df55bcd..aee2951 100644 --- a/src/selftest.cpp +++ b/src/selftest.cpp @@ -6,7 +6,9 @@ // and against a temporary data directory. #include "headers_core.h" +#include "bip32.h" #include "selftest.h" +#include "walletcmd.h" // Test results go to the terminal, not to debug.log. // @@ -342,18 +344,68 @@ static int RunWalletHDSelfTest() nFail += Check(SetHDSeedFromMnemonic(strPhraseA, strError), "a valid phrase installs a seed") ? 0 : 1; nFail += Check(HaveHDSeed(), "the wallet reports having a seed") ? 0 : 1; + nFail += Check(nHDKeySchema == HD_SCHEMA_BIP44, + "a new recovery phrase records the BIP44 HD schema") ? 0 : 1; + nFail += Check(nHDCoinType == HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + "a new recovery phrase records the provisional BIP44 coin type") ? 0 : 1; + nFail += Check(nHDReceiveNext == 1 && nHDChangeNext == 0, + "BIP44 receive/change counters reserve the default receive key") ? 0 : 1; + std::vector vBIP44Path = HDBIP44Path(HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + HD_BIP44_ACCOUNT, + HD_BIP44_CHAIN_RECEIVE, + 0); + nFail += Check(vBIP44Path.size() == 5 && + vBIP44Path[0] == (HD_BIP44_PURPOSE | bitflash::BIP32_HARDENED) && + vBIP44Path[1] == (HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL | bitflash::BIP32_HARDENED) && + vBIP44Path[2] == (HD_BIP44_ACCOUNT | bitflash::BIP32_HARDENED) && + vBIP44Path[3] == HD_BIP44_CHAIN_RECEIVE && + vBIP44Path[4] == 0, + "the BIP44 helper builds m/44'/coin_type'/account'/change/index") ? 0 : 1; int nPoolAfterSeed = 0; CRITICAL_BLOCK(cs_keyPool) nPoolAfterSeed = (int)mapKeyPool.size(); nFail += Check(nPoolAfterSeed == 0, "installing a phrase clears the old random key pool") ? 0 : 1; - nFail += Check(nHDNext == 1, - "installing a phrase reserves one derived default key") ? 0 : 1; + nFail += Check(nHDNext == 0, + "installing a BIP44 phrase leaves the legacy counter unused") ? 0 : 1; CKey keyFirstDerived; if (!DeriveHDKey(0, keyFirstDerived, strError)) throw std::runtime_error("default derivation failed: " + strError); + bitflash::BIP32PrivateNode hdParent; + hdParent.privateKey = vchHDMaster; + hdParent.chainCode = vchHDChainCode; + bitflash::BIP32PrivateNode hdBIP44ReceiveChild; + if (!bitflash::BIP32DerivePath(hdParent, + HDBIP44Path(HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + HD_BIP44_ACCOUNT, + HD_BIP44_CHAIN_RECEIVE, + 0), + hdBIP44ReceiveChild, + strError)) + throw std::runtime_error("BIP44 receive path derivation failed: " + strError); + CKey keyBIP44ReceivePath; + if (!keyBIP44ReceivePath.SetSecret(hdBIP44ReceiveChild.privateKey)) + throw std::runtime_error("BIP44 receive path produced an unusable key"); + nFail += Check(keyBIP44ReceivePath.GetPubKey() == keyFirstDerived.GetPubKey(), + "the default HD key path is m/44'/coin_type'/0'/0/0") ? 0 : 1; + + bitflash::BIP32PrivateNode hdLegacyChild; + int nSchemaForLegacyCheck = nHDKeySchema; + nHDKeySchema = HD_SCHEMA_LEGACY; + CKey keyLegacyDerived; + if (!DeriveHDKey(0, keyLegacyDerived, strError)) + throw std::runtime_error("legacy derivation failed: " + strError); + nHDKeySchema = nSchemaForLegacyCheck; + if (!bitflash::BIP32DerivePath(hdParent, HDLegacyPath(0), hdLegacyChild, strError)) + throw std::runtime_error("legacy path derivation failed: " + strError); + CKey keyLegacyPath; + if (!keyLegacyPath.SetSecret(hdLegacyChild.privateKey)) + throw std::runtime_error("legacy path produced an unusable key"); + nFail += Check(keyLegacyPath.GetPubKey() == keyLegacyDerived.GetPubKey(), + "the legacy HD key path remains m/index'") ? 0 : 1; + std::vector vchDefaultKey; bool fDefaultRead = CWalletDB("r").ReadDefaultKey(vchDefaultKey); nFail += Check(fDefaultRead && vchDefaultKey == keyFirstDerived.GetPubKey(), @@ -370,10 +422,16 @@ static int RunWalletHDSelfTest() "the pre-seed address is kept, named apart from the new one") ? 0 : 1; std::vector vchBefore = vchHDMaster; + int nSchemaBefore = nHDKeySchema; + unsigned int nCoinTypeBefore = nHDCoinType; nFail += Check(!SetHDSeedFromMnemonic("not a mnemonic at all", strError), "an invalid phrase is refused") ? 0 : 1; nFail += Check(vchHDMaster == vchBefore, "a refused phrase leaves the existing seed alone") ? 0 : 1; + nFail += Check(nHDKeySchema == nSchemaBefore, + "a refused phrase leaves the derivation schema alone") ? 0 : 1; + nFail += Check(nHDCoinType == nCoinTypeBefore, + "a refused phrase leaves the BIP44 coin type alone") ? 0 : 1; // The property the whole feature exists for: the same words give back // the same keys, in the same order. @@ -416,18 +474,26 @@ static int RunWalletHDSelfTest() // With a seed installed the pool must be derived from it, and the // counter must move exactly once per key. SetHDSeedFromMnemonic(strPhraseA, strError); - unsigned int nNextBefore = nHDNext; + unsigned int nReceiveNextBefore = nHDReceiveNext; TopUpKeyPool(); int nPool = 0; CRITICAL_BLOCK(cs_keyPool) nPool = (int)mapKeyPool.size(); nFail += Check(nPool == KEYPOOL_SIZE, "the derived pool fills") ? 0 : 1; - nFail += Check(nHDNext == nNextBefore + (unsigned int)KEYPOOL_SIZE, - "the derivation counter advances once per pooled key") ? 0 : 1; + nFail += Check(nHDReceiveNext == nReceiveNextBefore + (unsigned int)KEYPOOL_SIZE, + "the BIP44 receive counter advances once per pooled key") ? 0 : 1; + nFail += Check(nHDChangeNext == 0, + "filling the receive pool leaves the BIP44 change counter alone") ? 0 : 1; + nFail += Check(!RestoreScanReachedDepth(HD_SCHEMA_BIP44, 600, 400, 600, 600), + "BIP44 restore depth is not satisfied by receive plus legacy alone") ? 0 : 1; + nFail += Check(RestoreScanReachedDepth(HD_SCHEMA_BIP44, 600, 600, 600, 600), + "BIP44 restore depth is satisfied on each branch") ? 0 : 1; + nFail += Check(RestoreScanReachedDepth(HD_SCHEMA_LEGACY, 0, 0, 600, 600), + "legacy restore depth still follows the legacy counter") ? 0 : 1; std::set derived; - for (unsigned int i = nNextBefore; i < nHDNext; i++) + for (unsigned int i = nReceiveNextBefore; i < nHDReceiveNext; i++) { CKey key; if (!DeriveHDKey(i, key, strError)) @@ -456,11 +522,32 @@ static int RunWalletHDSelfTest() CKey keyAuditDerived; if (!DeriveHDKey(0, keyAuditDerived, strError)) throw std::runtime_error("audit derivation failed: " + strError); + CKey keyAuditChange; + if (!DeriveHDChangeKey(0, keyAuditChange, strError)) + throw std::runtime_error("audit change derivation failed: " + strError); + nFail += Check(keyAuditChange.GetPubKey() != keyAuditDerived.GetPubKey(), + "BIP44 receive and change chains derive different keys") ? 0 : 1; + if (!AddKey(keyAuditChange)) + throw std::runtime_error("could not store the audit change key"); + nHDChangeNext = 1; + int nSchemaForLegacyAudit = nHDKeySchema; + nHDKeySchema = HD_SCHEMA_LEGACY; + CKey keyAuditLegacyHD; + if (!DeriveHDKey(0, keyAuditLegacyHD, strError)) + throw std::runtime_error("audit legacy compatibility derivation failed: " + strError); + nHDKeySchema = nSchemaForLegacyAudit; + if (!AddKey(keyAuditLegacyHD)) + throw std::runtime_error("could not store the audit legacy compatibility key"); + nHDNext = 1; CWalletTx wtxLegacy; wtxLegacy.vout.push_back(CTxOut(5 * COIN, CScript() << vchPreSeedKey << OP_CHECKSIG)); CWalletTx wtxDerived; wtxDerived.vout.push_back(CTxOut(7 * COIN, CScript() << keyAuditDerived.GetPubKey() << OP_CHECKSIG)); + CWalletTx wtxChange; + wtxChange.vout.push_back(CTxOut(13 * COIN, CScript() << keyAuditChange.GetPubKey() << OP_CHECKSIG)); + CWalletTx wtxLegacyHD; + wtxLegacyHD.vout.push_back(CTxOut(17 * COIN, CScript() << keyAuditLegacyHD.GetPubKey() << OP_CHECKSIG)); CWalletTx wtxImmatureLegacy; wtxImmatureLegacy.vin.push_back(CTxIn()); wtxImmatureLegacy.vout.push_back(CTxOut(11 * COIN, CScript() << vchPreSeedKey << OP_CHECKSIG)); @@ -470,17 +557,25 @@ static int RunWalletHDSelfTest() mapWallet.clear(); mapWallet[wtxLegacy.GetHash()] = wtxLegacy; mapWallet[wtxDerived.GetHash()] = wtxDerived; + mapWallet[wtxChange.GetHash()] = wtxChange; + mapWallet[wtxLegacyHD.GetHash()] = wtxLegacyHD; mapWallet[wtxImmatureLegacy.GetHash()] = wtxImmatureLegacy; } WalletRecoveryAudit audit = GetWalletRecoveryAudit(); nFail += Check(audit.fHaveSeed, "the recovery audit reports the phrase") ? 0 : 1; + nFail += Check(audit.nSchema == HD_SCHEMA_BIP44, + "the recovery audit reports the derivation schema") ? 0 : 1; + nFail += Check(audit.nCoinType == HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + "the recovery audit reports the BIP44 coin type") ? 0 : 1; + nFail += Check(audit.nReceiveNext == nHDReceiveNext && audit.nChangeNext == 1, + "the recovery audit reports receive/change counters") ? 0 : 1; nFail += Check(audit.nLegacyCredit == 5 * COIN, "the recovery audit finds wallet.dat-only balance") ? 0 : 1; - nFail += Check(audit.nRecoverableCredit == 7 * COIN, - "the recovery audit finds phrase-backed balance") ? 0 : 1; - nFail += Check(audit.nLegacyTx == 1 && audit.nRecoverableTx == 1, - "the recovery audit counts legacy and phrase-backed transactions") ? 0 : 1; + nFail += Check(audit.nRecoverableCredit == 37 * COIN, + "the recovery audit finds BIP44 and legacy-HD phrase balance") ? 0 : 1; + nFail += Check(audit.nLegacyTx == 1 && audit.nRecoverableTx == 3, + "the recovery audit counts wallet.dat-only and phrase-backed transactions") ? 0 : 1; nFail += Check(audit.nLegacyImmatureCredit == 11 * COIN, "the recovery audit finds wallet.dat-only immature mining rewards") ? 0 : 1; nFail += Check(audit.nLegacyImmatureTx == 1, diff --git a/src/test_bip32.cpp b/src/test_bip32.cpp index 610a651..6c11510 100644 --- a/src/test_bip32.cpp +++ b/src/test_bip32.cpp @@ -5,6 +5,8 @@ #include "bip32.h" +#include + #include #include #include @@ -57,6 +59,76 @@ static std::string ToHex(const std::vector& v) return out; } +static bool DecodeBase58Check(const std::string& str, std::vector& out) +{ + static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + out.clear(); + + std::vector b256(str.size() * 733 / 1000 + 1); + for (char c : str) + { + const char* p = strchr(pszBase58, c); + if (!p) + return false; + int carry = (int)(p - pszBase58); + for (std::vector::reverse_iterator it = b256.rbegin(); + it != b256.rend(); ++it) + { + carry += 58 * (*it); + *it = (unsigned char)(carry & 0xff); + carry >>= 8; + } + if (carry != 0) + return false; + } + + size_t zeros = 0; + while (zeros < str.size() && str[zeros] == '1') + zeros++; + std::vector::iterator it = b256.begin(); + while (it != b256.end() && *it == 0) + ++it; + + std::vector full; + full.assign(zeros, 0); + while (it != b256.end()) + full.push_back(*it++); + if (full.size() < 4) + return false; + + std::vector payload(full.begin(), full.end() - 4); + unsigned char h1[SHA256_DIGEST_LENGTH]; + unsigned char h2[SHA256_DIGEST_LENGTH]; + SHA256(&payload[0], payload.size(), h1); + SHA256(h1, sizeof(h1), h2); + if (memcmp(h2, &full[full.size() - 4], 4) != 0) + return false; + + out = payload; + return true; +} + +static bool DecodeXPrvNode(const std::string& xprv, BIP32PrivateNode& nodeOut) +{ + nodeOut.privateKey.clear(); + nodeOut.chainCode.clear(); + + std::vector payload; + if (!DecodeBase58Check(xprv, payload)) + return false; + if (payload.size() != 78) + return false; + if (payload[0] != 0x04 || payload[1] != 0x88 || + payload[2] != 0xad || payload[3] != 0xe4) + return false; + if (payload[45] != 0x00) + return false; + + nodeOut.chainCode.assign(payload.begin() + 13, payload.begin() + 45); + nodeOut.privateKey.assign(payload.begin() + 46, payload.end()); + return true; +} + int main() { std::string err; @@ -124,6 +196,53 @@ int main() "pre-hardened index rejected"); } + printf("bip32_paths\n"); + { + std::vector seed = FromHex("000102030405060708090a0b0c0d0e0f"); + BIP32PrivateNode master; + CHECK(BIP32MasterFromSeed(seed, master, err), "path test master derives"); + + struct PathVector + { + const char* name; + std::vector path; + const char* xprv; + }; + + std::vector vectors; + vectors.push_back({"m", + {}, + "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"}); + vectors.push_back({"m/0'", + {0 | BIP32_HARDENED}, + "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7"}); + vectors.push_back({"m/0'/1", + {0 | BIP32_HARDENED, 1}, + "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs"}); + vectors.push_back({"m/0'/1/2'", + {0 | BIP32_HARDENED, 1, 2 | BIP32_HARDENED}, + "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM"}); + vectors.push_back({"m/0'/1/2'/2", + {0 | BIP32_HARDENED, 1, 2 | BIP32_HARDENED, 2}, + "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334"}); + vectors.push_back({"m/0'/1/2'/2/1000000000", + {0 | BIP32_HARDENED, 1, 2 | BIP32_HARDENED, 2, 1000000000}, + "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76"}); + + for (const PathVector& v : vectors) + { + BIP32PrivateNode actual; + BIP32PrivateNode expected; + std::string label = std::string("derives ") + v.name; + CHECK(BIP32DerivePath(master, v.path, actual, err), label.c_str()); + label = std::string("decodes vector ") + v.name; + CHECK(DecodeXPrvNode(v.xprv, expected), label.c_str()); + label = std::string("matches vector ") + v.name; + CHECK(actual.privateKey == expected.privateKey && + actual.chainCode == expected.chainCode, label.c_str()); + } + } + printf("\n%s (%d failures)\n", g_fail == 0 ? "ALL TESTS PASSED" : "TESTS FAILED", g_fail); return g_fail == 0 ? 0 : 1; diff --git a/src/walletcmd.cpp b/src/walletcmd.cpp index 41b4ed2..b449df9 100644 --- a/src/walletcmd.cpp +++ b/src/walletcmd.cpp @@ -25,16 +25,34 @@ // would restore a wallet that looks empty. static const int RESTORE_BATCH = 100; static const int RESTORE_MAX = 10000; -// The wallet may have a full unused key pool in front of a change address -// created while spending pre-phrase coins. Looking only one empty batch ahead -// can stop just before that change output. -static const int RESTORE_MIN_SCAN = KEYPOOL_SIZE + RESTORE_BATCH; - // Quiet batches required before giving up. Three, because the wallet's own // bookkeeping can leave a gap of two hundred used-nothing indices between one // used address and the next -- see the note at the stop condition. One was not // enough and cost a real balance in testing. static const int RESTORE_QUIET_BATCHES = 3; +// The wallet may have restored once, scanned a few quiet batches, and then +// spent after that. Change starts from wherever that restore stopped, so the +// next real change output can be just beyond the old quiet window. The default +// restore has to look far enough for that ordinary "restore, then spend, then +// restore again" path; explicit -restoredepth can still go deeper. +static const int RESTORE_MIN_SCAN = + KEYPOOL_SIZE + (RESTORE_QUIET_BATCHES + 1) * RESTORE_BATCH; + +bool RestoreScanReachedDepth(int nSchema, + unsigned int nReceiveNext, + unsigned int nChangeNext, + unsigned int nLegacyNext, + int nStopDepth) +{ + if (nStopDepth <= 0) + return true; + unsigned int nDepth = (unsigned int)nStopDepth; + if (nSchema == HD_SCHEMA_BIP44) + return nReceiveNext >= nDepth && + nChangeNext >= nDepth && + nLegacyNext >= nDepth; + return nLegacyNext >= nDepth; +} int CmdNewPhrase() { @@ -114,7 +132,9 @@ bool RestoreFromPhrase(const std::string& strMnemonic, // Derive forward in batches, scanning after each, until a whole batch turns // up nothing. Every derived key is written to the wallet before the scan, // because the scan asks the wallet what belongs to it. - int nTotalDerived = (int)nHDNext; + int nTotalDerived = nHDKeySchema == HD_SCHEMA_BIP44 + ? (int)(nHDReceiveNext + nHDChangeNext) + : (int)nHDNext; int nStopDepth = max(nMinDepth, RESTORE_MIN_SCAN); int nQuietBatches = 0; while (nTotalDerived < RESTORE_MAX) @@ -131,17 +151,61 @@ bool RestoreFromPhrase(const std::string& strMnemonic, nWalletBefore = mapWallet.size(); std::string strDeriveError; - for (int i = 0; i < RESTORE_BATCH; i++) + if (nHDKeySchema == HD_SCHEMA_BIP44) + { + for (int i = 0; i < RESTORE_BATCH; i++) + { + CKey key; + if (!DeriveHDKey(nHDReceiveNext, key, strDeriveError)) + break; + if (!AddKey(key)) + break; + nHDReceiveNext++; + nTotalDerived++; + } + CWalletDB().WriteHDReceiveNext(nHDReceiveNext); + + for (int i = 0; i < RESTORE_BATCH; i++) + { + CKey key; + if (!DeriveHDChangeKey(nHDChangeNext, key, strDeriveError)) + break; + if (!AddKey(key)) + break; + nHDChangeNext++; + nTotalDerived++; + } + CWalletDB().WriteHDChangeNext(nHDChangeNext); + + int nSavedSchema = nHDKeySchema; + nHDKeySchema = HD_SCHEMA_LEGACY; + for (int i = 0; i < RESTORE_BATCH; i++) + { + CKey key; + if (!DeriveHDKey(nHDNext, key, strDeriveError)) + break; + if (!AddKey(key)) + break; + nHDNext++; + nTotalDerived++; + } + nHDKeySchema = nSavedSchema; + CWalletDB().WriteHDNext(nHDNext); + } + else { - CKey key; - if (!DeriveHDKey(nHDNext, key, strDeriveError)) - break; - if (!AddKey(key)) - break; - nHDNext++; - nTotalDerived++; + for (int i = 0; i < RESTORE_BATCH; i++) + { + CKey key; + if (!DeriveHDKey(nHDNext, key, strDeriveError)) + break; + if (!AddKey(key)) + break; + nHDNext++; + nTotalDerived++; + } + CWalletDB().WriteHDNext(nHDNext); } - CWalletDB().WriteHDNext(nHDNext); ScanForWalletTransactions(pindexGenesisBlock); @@ -157,11 +221,11 @@ bool RestoreFromPhrase(const std::string& strMnemonic, } // Stopping needs more than one quiet batch, because this wallet digs - // gaps in its own derivation. A restore leaves nHDNext at the depth it - // scanned, the key pool then derives KEYPOOL_SIZE more, and change - // takes the index after that -- so the address used *after* a restore - // can sit two hundred indices past the last one used before it, with - // nothing in between. + // gaps in its own derivation. A restore leaves the receive counter at + // the depth it scanned, the key pool then derives KEYPOOL_SIZE more, + // and a later spend can use change after that -- so the address used + // *after* a restore can sit two hundred indices past the last one used + // before it, with nothing in between. // // Measured, on a real wallet with real coin: restore, spend once, and // the coins land at indices 201 and 302. Restoring again with the old @@ -171,7 +235,12 @@ bool RestoreFromPhrase(const std::string& strMnemonic, nQuietBatches++; else nQuietBatches = 0; - if (nQuietBatches >= RESTORE_QUIET_BATCHES && nTotalDerived >= nStopDepth) + if (nQuietBatches >= RESTORE_QUIET_BATCHES && + RestoreScanReachedDepth(nHDKeySchema, + nHDReceiveNext, + nHDChangeNext, + nHDNext, + nStopDepth)) break; } @@ -283,7 +352,13 @@ int CmdRecoveryAudit() printf("Wallet recovery audit\n"); printf(" recovery phrase: %s\n", audit.fHaveSeed ? "present" : "not installed"); if (audit.fHaveSeed) + { + printf(" derivation schema: %s\n", HDKeySchemaName(audit.nSchema).c_str()); + printf(" BIP44 coin type: %u (provisional BITFLASH)\n", audit.nCoinType); printf(" derived keys known to this wallet: %u\n", audit.nDerivedKnown); + printf(" receive/change counters: %u/%u\n", + audit.nReceiveNext, audit.nChangeNext); + } if (!audit.fDeriveComplete) printf(" derivation warning: %s\n", audit.strDeriveError.c_str()); printf(" total spendable balance: %s BTF\n", FormatMoney(nTotal).c_str()); diff --git a/src/walletcmd.h b/src/walletcmd.h index 69874e4..32d3eef 100644 --- a/src/walletcmd.h +++ b/src/walletcmd.h @@ -32,6 +32,15 @@ bool RestoreFromPhrase(const std::string& strMnemonic, int& nRecoveredRet, int& nDerivedRet); +// Restore scans stop only after the requested depth is reached. BIP44 has more +// than one branch, so the depth has to be satisfied per branch, not by summing +// receive + change + compatibility keys. +bool RestoreScanReachedDepth(int nSchema, + unsigned int nReceiveNext, + unsigned int nChangeNext, + unsigned int nLegacyNext, + int nStopDepth); + // Take the next address from the key pool and print it. With a recovery phrase // installed the address is derived, so the phrase can bring back whatever is // paid to it.