From b65c19e559e2fec511f40a4d5481bcf6a35c311c Mon Sep 17 00:00:00 2001 From: Bitflash Date: Sat, 1 Aug 2026 14:48:27 -0300 Subject: wallet: walk the chain for coins a key owns but the wallet never saw (#88) A transaction only entered the wallet when its block arrived over the network, so a key added afterwards was invisible: coins on the chain, private key in wallet.dat, balance zero. /importwallet has always ended that way -- it writes the keys and the money never shows up, which looks exactly like a failed import. ScanForWalletTransactions walks the main chain and hands every transaction that IsMine() to AddToWalletIfMine, the same two primitives the live path uses. Wired into /importwallet, and offered as /rescan. It is also the half that any recovery-phrase feature has to stand on: deriving keys from twelve words is easy, and without this a restore restores nothing. --- src/main.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index b027cef..68ae44c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -305,6 +305,55 @@ bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock) return true; } +int ScanForWalletTransactions(CBlockIndex* pindexStart) +{ + // Walk the chain looking for transactions that belong to keys this wallet + // holds now, whatever it held when those blocks arrived. + // + // Nothing in this tree could do that. A key added after the fact -- from + // /importwallet, or from a backup restored onto a node that had since + // moved on -- was simply invisible: the coins were on the chain, the + // private key was in wallet.dat, and the balance did not show them, + // because a transaction only ever entered the wallet at the moment its + // block arrived over the network. + // + // Bitcoin grew the same function for the same reason. It is also what any + // recovery-phrase feature has to stand on: deriving the keys is the easy + // half, and without this the other half does not exist. + int nFound = 0; + int nScanned = 0; + CBlockIndex* pindex = pindexStart; + CRITICAL_BLOCK(cs_main) + { + while (pindex) + { + CBlock block; + if (block.ReadFromDisk(pindex, true)) + { + foreach(CTransaction& tx, block.vtx) + { + // Ask before handing it over: AddToWalletIfMine returns + // true for a transaction that is none of our business, so + // its return value cannot be counted. + if (tx.IsMine()) + { + if (AddToWalletIfMine(tx, &block)) + nFound++; + } + } + } + nScanned++; + if ((nScanned % 500) == 0) + printf("ScanForWalletTransactions() : %d blocks scanned, %d transaction(s) found\n", + nScanned, nFound); + pindex = pindex->pnext; + } + } + printf("ScanForWalletTransactions() : %d block(s) scanned, %d transaction(s) added or updated\n", + nScanned, nFound); + return nFound; +} + bool EraseFromWallet(uint256 hash) { CRITICAL_BLOCK(cs_mapWallet) -- cgit v1.2.3