Fix race condition after reorg #29

Merged
roylee17 merged 2 commits from roylee/fix-race-condition-after-reorg into master 2022-09-13 20:40:06 +02:00
2 changed files with 18 additions and 1 deletions

View file

@ -245,7 +245,7 @@ func (w *Wallet) disconnectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta)
if err != nil { if err != nil {
return err return err
} }
b.Hash = *hash bs.Hash = *hash
client := w.ChainClient() client := w.ChainClient()
header, err := client.GetBlockHeader(hash) header, err := client.GetBlockHeader(hash)

View file

@ -430,6 +430,23 @@ func (w *Wallet) syncWithChain(birthdayStamp *waddrmgr.BlockStamp) error {
// before catching up with the rescan. // before catching up with the rescan.
rollback := false rollback := false
rollbackStamp := w.Manager.SyncedTo() rollbackStamp := w.Manager.SyncedTo()
// Handle corner cases where the chain has reorged to a lower height
// than the wallet had synced to. This could happen if the chain has
// reorged to a shorter chain with difficulty greater than the current.
// Most of the time, it's only temporary since the chain will grow
// past the previous height anyway. In regtest, however, it burdens
// the testing setup without this check.
bestBlockHash, bestBlockHeight, err := chainClient.GetBestBlock()
if err != nil {
return err
}
if rollbackStamp.Height > bestBlockHeight {
rollbackStamp.Hash = *bestBlockHash
rollbackStamp.Height = bestBlockHeight
rollback = true
}
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error { err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey) addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadWriteBucket(wtxmgrNamespaceKey) txmgrNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)