@@ -327,7 +327,22 @@ func (w *Wallet) activeData(dbtx walletdb.ReadTx) ([]btcutil.Address, []wtxmgr.C
327327// finished. The birthday block can be passed in, if set, to ensure we can
328328// properly detect if it gets rolled back.
329329func (w * Wallet ) syncWithChain (birthdayStamp * waddrmgr.BlockStamp ) error {
330- // To start, if we've yet to find our birthday stamp, we'll do so now.
330+ chainClient , err := w .requireChainClient ()
331+ if err != nil {
332+ return err
333+ }
334+
335+ // We'll wait until the backend is synced to ensure we get the latest
336+ // MaxReorgDepth blocks to store. We don't do this for development
337+ // environments as we can't guarantee a lively chain.
338+ if ! w .isDevEnv () {
339+ log .Debug ("Waiting for chain backend to sync to tip" )
340+ if err := w .waitUntilBackendSynced (chainClient ); err != nil {
341+ return err
342+ }
343+ log .Debug ("Chain backend synced to tip!" )
344+ }
345+
331346 if birthdayStamp == nil {
332347 var err error
333348 birthdayStamp , err = w .syncToBirthday ()
@@ -357,11 +372,6 @@ func (w *Wallet) syncWithChain(birthdayStamp *waddrmgr.BlockStamp) error {
357372 // before catching up with the rescan.
358373 rollback := false
359374 rollbackStamp := w .Manager .SyncedTo ()
360- chainClient , err := w .requireChainClient ()
361- if err != nil {
362- return err
363- }
364-
365375 err = walletdb .Update (w .db , func (tx walletdb.ReadWriteTx ) error {
366376 addrmgrNs := tx .ReadWriteBucket (waddrmgrNamespaceKey )
367377 txmgrNs := tx .ReadWriteBucket (wtxmgrNamespaceKey )
@@ -467,6 +477,26 @@ func (w *Wallet) isDevEnv() bool {
467477 return true
468478}
469479
480+ // waitUntilBackendSynced blocks until the chain backend considers itself
481+ // "current".
482+ func (w * Wallet ) waitUntilBackendSynced (chainClient chain.Interface ) error {
483+ // We'll poll every second to determine if our chain considers itself
484+ // "current".
485+ t := time .NewTicker (time .Second )
486+ defer t .Stop ()
487+
488+ for {
489+ select {
490+ case <- t .C :
491+ if chainClient .IsCurrent () {
492+ return nil
493+ }
494+ case <- w .quitChan ():
495+ return ErrWalletShuttingDown
496+ }
497+ }
498+ }
499+
470500// scanChain is a helper method that scans the chain from the starting height
471501// until the tip of the chain. The onBlock callback can be used to perform
472502// certain operations for every block that we process as we scan the chain.
0 commit comments