chain: improve reorg-during-rescan handling for bitcoind

This commit is contained in:
Alex 2018-03-09 20:37:17 -07:00 committed by Olaoluwa Osuntokun
parent 321c2fac2b
commit 6b6ed89d87

View file

@ -828,47 +828,55 @@ func (c *BitcoindClient) rescan(hash *chainhash.Hash) error {
} }
} }
if block.Header.PrevBlock.String() != lastHeader.Hash { for block.Header.PrevBlock.String() != lastHeader.Hash {
// We've been reorganized, maybe. We now walk backwards // If we're in this for loop, it looks like we've been
// to a known block. If we go back past the passed // reorganized. We now walk backwards to the common
// block, we return an error. The initialization logic // ancestor between the best chain and the known chain.
// of the wallet should prevent that from happening. //
for j := i - 1; j > firstHeader.Height; j-- { // First, we signal a disconnected block to rewind the
hash, err = c.GetBlockHash(int64(j)) // rescan state.
c.onBlockDisconnected(lastHash, lastHeader.Height,
time.Unix(lastHeader.Time, 0))
// Next, we get the previous block of the best chain.
hash, err = c.GetBlockHash(int64(i - 1))
if err != nil { if err != nil {
return err return err
} }
// If we've found a matching hash, we can move
// forward from there.
if hash.String() == lastHeader.Hash {
i = j + 1
block, err = c.GetBlock(hash) block, err = c.GetBlock(hash)
if err != nil { if err != nil {
return err return err
} }
break
}
// Rewind the rescan state. // Then, we get the previous header for the known chain.
c.onBlockDisconnected(lastHash, if headers.Back() != nil {
lastHeader.Height, // If it's already in the headers list, we can
time.Unix(lastHeader.Time, 0)) // just get it from there and remove the
// current hash).
headers.Remove(headers.Back()) headers.Remove(headers.Back())
lastHeader = headers.Back().Value.(*btcjson. if headers.Back() != nil {
lastHeader = headers.Back().
Value.(*btcjson.
GetBlockHeaderVerboseResult) GetBlockHeaderVerboseResult)
lastHash, err = chainhash.NewHashFromStr( lastHash, err = chainhash.
lastHeader.Hash) NewHashFromStr(lastHeader.Hash)
if err != nil { if err != nil {
return err return err
} }
} }
} else {
// Check again and make sure we're at the start of the // Otherwise, we get it from bitcoind.
// reorg. lastHash, err = chainhash.NewHashFromStr(
if block.Header.PrevBlock.String() != lastHeader.Hash { lastHeader.PreviousHash)
return errors.New("reorg during rescan went " + if err != nil {
"too far back") return err
}
lastHeader, err = c.GetBlockHeaderVerbose(
lastHash)
if err != nil {
return err
}
} }
} }