@@ -3,7 +3,7 @@ use std::{collections::BTreeMap, str::FromStr, time::Duration};
3
3
use anyhow:: anyhow;
4
4
use clap:: ValueEnum ;
5
5
use futures:: { stream:: FuturesUnordered , StreamExt } ;
6
- use log:: info;
6
+ use log:: { info, warn } ;
7
7
use protocol:: {
8
8
bitcoin:: Txid ,
9
9
constants:: ChainAnchor ,
@@ -28,7 +28,8 @@ use wallet::{
28
28
} ,
29
29
DoubleUtxo , SpacesWallet , WalletInfo ,
30
30
} ;
31
-
31
+ use wallet:: bdk_wallet:: chain:: BlockId ;
32
+ use wallet:: bdk_wallet:: chain:: local_chain:: CheckPoint ;
32
33
use crate :: {
33
34
config:: ExtendedNetwork ,
34
35
node:: BlockSource ,
@@ -324,19 +325,37 @@ impl RpcWallet {
324
325
}
325
326
}
326
327
BlockEvent :: Error ( e) if matches ! ( e, BlockFetchError :: BlockMismatch ) => {
327
- let local_chain = wallet. coins . local_chain ( ) ;
328
- let restore_point = local_chain
329
- . iter_checkpoints ( )
330
- . find_map ( |x| {
331
- if wallet_tip. height - x. height ( ) > 12 {
332
- Some ( x. clone ( ) )
333
- } else {
334
- None
335
- }
336
- } )
337
- . unwrap_or (
338
- local_chain. iter_checkpoints ( ) . last ( ) . expect ( "a checkpoint" ) ,
339
- ) ;
328
+ let mut checkpoint_in_chain = None ;
329
+ let best_chain = source. get_best_chain ( ) ?;
330
+ for cp in wallet. coins . local_chain ( ) . iter_checkpoints ( ) {
331
+ if cp. height ( ) > best_chain. height {
332
+ continue ;
333
+ }
334
+
335
+ let hash = source. get_block_hash ( cp. height ( ) ) ?;
336
+ if cp. height ( ) != 0 && hash == cp. hash ( ) {
337
+ checkpoint_in_chain = Some ( cp) ;
338
+ break ;
339
+ }
340
+ }
341
+
342
+ let restore_point = match checkpoint_in_chain {
343
+ None => {
344
+ // We couldn't find a restore point
345
+ warn ! ( "Rebuilding wallet `{}`" , wallet. config. name) ;
346
+ let birthday = wallet. config . start_block ;
347
+ let hash = source. get_block_hash ( birthday) ?;
348
+ let cp = CheckPoint :: new ( BlockId {
349
+ height : birthday,
350
+ hash,
351
+ } ) ;
352
+ wallet = wallet. rebuild ( ) ?;
353
+ wallet. coins . insert_checkpoint ( cp. block_id ( ) ) ?;
354
+ wallet. spaces . insert_checkpoint ( cp. block_id ( ) ) ?;
355
+ cp
356
+ }
357
+ Some ( cp) => cp
358
+ } ;
340
359
341
360
wallet_tip. height = restore_point. block_id ( ) . height ;
342
361
wallet_tip. hash = restore_point. block_id ( ) . hash ;
0 commit comments