Skip to content

Commit cebc1ab

Browse files
Godzilla-ossstark-3kmojoX911
authored
[BUG] Fix rescan during sync (#676)
* sync wallet after funding tx * sync wallet during hashlock recovery * fix maker logs * update test assertion and sync after privkeyhandover * another assertion fix * [BUG] Sync bug & Fix offer maxsize calculation - modified: ignored return value of rescan_blockchain - check rescan status using get_wallet_info and exit accordingly - updates last_synced_height after rescan completes - log wallet's birth height and last_synced_height - ADDS info log at sync site for maker - Changes: `refresh_offer_maxsize_cache` calculation from spendable to max(swap, regular) - Changes: `fn check_swap_liquidity` to use `refresh_offer_maxsize_cache` insted of `sync_and_save` - Udates: `fn check_swap_liquidity_taproot` to use `refresh_offer_maxsize_cache` - Remove `sync_and_save` from update_fidelity_bond_conf_details - Adds sync_and_save to test --------- Co-authored-by: Rishabh <rishkwal@gmail.com> Co-authored-by: mojoX911 <mojojojo48@protonmail.com>
1 parent f8b6163 commit cebc1ab

File tree

10 files changed

+68
-44
lines changed

10 files changed

+68
-44
lines changed

src/maker/api.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ impl Maker {
340340
}
341341
config.write_to_file(&data_dir.join("config.toml"))?;
342342

343+
log::info!("Sync at:----Maker init----");
343344
wallet.sync_and_save()?;
344345

345346
let network_port = config.network_port;

src/maker/api2.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -336,9 +336,8 @@ impl Maker {
336336

337337
config.write_to_file(&data_dir.join("config.toml"))?;
338338

339-
log::info!("Initializing wallet sync");
339+
log::info!("Sync at:----Maker init----");
340340
wallet.sync_and_save()?;
341-
log::info!("Completed wallet sync");
342341

343342
let network_port = config.network_port;
344343

@@ -491,6 +490,7 @@ impl Maker {
491490
let mut wallet = self.wallet.write()?;
492491

493492
// Sync wallet to get latest UTXO state
493+
log::info!("Sync at:----verify_and_process_senders_contract----");
494494
wallet.sync_and_save()?;
495495

496496
let balance = wallet.get_balances()?;

src/maker/handlers.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@ impl Maker {
303303
.get(funding_output_index as usize)
304304
.expect("funding output expected at this index");
305305

306+
log::info!("Sync at:----handle_proof_of_funding----");
306307
self.wallet.write()?.sync_and_save()?;
307308

308309
let receiver_contract_tx = create_receivers_contract_tx(
@@ -706,6 +707,7 @@ impl Maker {
706707
}
707708
}
708709

710+
log::info!("Sync at:----handle_private_key_handover----");
709711
self.wallet.write()?.sync_and_save()?;
710712

711713
log::info!("Successfully Completed Coinswap");
@@ -725,6 +727,7 @@ impl Maker {
725727
swept_txids
726728
);
727729
}
730+
log::info!("Sync at:----sweep_after_successful_coinswap----");
728731
self.wallet.write()?.sync_and_save()?;
729732
// For tests, terminate the maker at this stage.
730733
#[cfg(feature = "integration-test")]

src/maker/rpc/server.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ fn handle_request<M: MakerRpc>(maker: &Arc<M>, socket: &mut TcpStream) -> Result
109109

110110
let txid = maker.wallet().read()?.send_tx(&tx)?;
111111

112+
log::info!("Sync at:----handle_request----");
112113
maker.wallet().write()?.sync_and_save()?;
113114

114115
RpcMsgResp::SendToAddressResp(txid.to_string())

src/maker/server.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,7 @@ fn setup_fidelity_bond(maker: &Maker, maker_address: &str) -> Result<FidelityPro
305305
while !maker.shutdown.load(Relaxed) {
306306
sleep_multiplier += 1;
307307
// sync the wallet
308+
log::info!("Sync at:----setup_fidelity_bond----");
308309
maker.get_wallet().write()?.sync_and_save()?;
309310

310311
let fidelity_result = maker.get_wallet().write()?.create_fidelity(
@@ -358,6 +359,7 @@ fn setup_fidelity_bond(maker: &Maker, maker_address: &str) -> Result<FidelityPro
358359
*proof = Some(highest_proof);
359360

360361
// sync and save the wallet data to disk
362+
log::info!(" Sync at end:----setup_fidelity_bond----");
361363
maker.get_wallet().write()?.sync_and_save()?;
362364
break;
363365
}
@@ -381,6 +383,7 @@ fn check_swap_liquidity(maker: &Maker) -> Result<(), MakerError> {
381383
.write()?
382384
.get_next_external_address(AddressType::P2WPKH)?;
383385
while !maker.shutdown.load(Relaxed) {
386+
log::info!("Sync at:----check_swap_liquidity----");
384387
maker.get_wallet().write()?.sync_and_save()?;
385388
let offer_max_size = maker.get_wallet().read()?.store.offer_maxsize;
386389

@@ -662,10 +665,8 @@ pub fn start_maker_server(maker: Arc<Maker>) -> Result<(), MakerError> {
662665
log::info!("[{network_port}] Maker is shutting down.");
663666
maker.thread_pool.join_all_threads()?;
664667

665-
log::info!("Shutdown wallet sync initiated.");
668+
log::info!("sync at:----Shutdown wallet----");
666669
maker.get_wallet().write()?.sync_and_save()?;
667-
log::info!("Shutdown wallet syncing completed.");
668-
log::info!("Wallet file saved to disk.");
669670
log::info!("Maker Server is shut down successfully.");
670671
Ok(())
671672
}

src/maker/server2.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@ fn setup_fidelity_bond_taproot(
318318
while !maker.shutdown.load(Relaxed) {
319319
sleep_multiplier += 1;
320320
// sync the wallet
321+
log::info!("Sync at:----setup_fidelity_bond----");
321322
maker.wallet().write()?.sync_and_save()?;
322323

323324
let fidelity_result = maker.wallet().write()?.create_fidelity(
@@ -384,6 +385,7 @@ fn setup_fidelity_bond_taproot(
384385
};
385386

386387
// sync and save the wallet data to disk
388+
log::info!("Sync at end:----setup_fidelity_bond----");
387389
maker.wallet().write()?.sync_and_save()?;
388390

389391
// Store the fidelity proof in maker
@@ -401,6 +403,10 @@ fn setup_fidelity_bond_taproot(
401403

402404
/// Checks swap liquidity for taproot swaps
403405
fn check_swap_liquidity_taproot(maker: &Maker) -> Result<(), MakerError> {
406+
{
407+
let mut wallet = maker.wallet().write()?;
408+
wallet.refresh_offer_maxsize_cache()?;
409+
}
404410
let wallet_read = maker.wallet().read()?;
405411
let balances = wallet_read.get_balances()?;
406412

@@ -797,6 +803,8 @@ pub fn start_maker_server_taproot(maker: Arc<Maker>) -> Result<(), MakerError> {
797803
// Join all threads
798804
maker.thread_pool.join_all_threads()?;
799805

806+
log::info!("sync at:----Taproot server shutdown----");
807+
maker.wallet().write()?.sync_and_save()?;
800808
log::info!(
801809
"[{}] Taproot maker server stopped",
802810
maker.config.network_port

src/wallet/api.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//! In the future, takers might adopt alternative synchronization methods, such as lightweight wallet solutions.
55
66
use std::{
7-
convert::TryFrom, fmt::Display, path::PathBuf, str::FromStr, thread, thread::sleep,
7+
cmp::max, convert::TryFrom, fmt::Display, path::PathBuf, str::FromStr, thread, thread::sleep,
88
time::Duration,
99
};
1010

@@ -292,6 +292,16 @@ impl Wallet {
292292
Some(wallet_birthday),
293293
&store_enc_material,
294294
)?;
295+
let last_synced_height_val = match store.last_synced_height {
296+
Some(height) => height.to_string(),
297+
None => "None".to_string(),
298+
};
299+
300+
log::info!(
301+
"Wallet birth_height = {}, wallet last_sync_height = {}",
302+
wallet_birthday,
303+
last_synced_height_val
304+
);
295305

296306
Ok(Self {
297307
rpc,
@@ -1270,8 +1280,8 @@ impl Wallet {
12701280

12711281
/// Refreshes the offer maximum size cache based on the current wallet's unspent transaction outputs (UTXOs).
12721282
pub(crate) fn refresh_offer_maxsize_cache(&mut self) -> Result<(), WalletError> {
1273-
let balance = self.get_balances()?.spendable;
1274-
self.store.offer_maxsize = balance.to_sat();
1283+
let Balances { swap, regular, .. } = self.get_balances()?;
1284+
self.store.offer_maxsize = max(swap, regular).to_sat();
12751285
Ok(())
12761286
}
12771287

src/wallet/fidelity.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,8 +395,6 @@ impl Wallet {
395395
bond.cert_expiry = Some(cert_expiry);
396396
bond.conf_height = Some(conf_height);
397397

398-
self.sync_and_save()?;
399-
400398
Ok(())
401399
}
402400

src/wallet/rpc.rs

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
//!
33
use std::{convert::TryFrom, thread};
44

5-
use bitcoind::bitcoincore_rpc::{json::ListUnspentResultEntry, Auth, Client, RpcApi};
5+
use bitcoind::bitcoincore_rpc::{
6+
json::{ListUnspentResultEntry, ScanningDetails},
7+
Auth, Client, RpcApi,
8+
};
69
use serde_json::{json, Value};
710

811
use crate::{utill::HEART_BEAT_INTERVAL, wallet::api::KeychainKind};
@@ -70,16 +73,10 @@ impl Wallet {
7073
/// This method first synchronizes the wallet with the Bitcoin Core node,
7174
/// then persists the wallet state in the disk.
7275
pub fn sync_and_save(&mut self) -> Result<(), WalletError> {
73-
log::info!(
74-
"Initializing wallet sync and save for {:?}",
75-
&self.store.file_name
76-
);
76+
log::info!("Sync Started for {:?}", &self.store.file_name);
7777
self.sync_no_fail();
7878
self.save_to_disk()?;
79-
log::info!(
80-
"Completed wallet sync and save for {:?}",
81-
&self.store.file_name
82-
);
79+
log::info!("Synced & Saved {:?}", &self.store.file_name);
8380
Ok(())
8481
}
8582

@@ -130,40 +127,43 @@ impl Wallet {
130127
return Ok(());
131128
}
132129

133-
log::debug!("Importing Wallet spks/descriptors");
134-
135130
self.import_descriptors(&descriptors_to_import, None)?;
136131

137-
// Now run the scan
138-
log::debug!("Initializing TxOut scan. This may take a while.");
139-
140132
// Sometimes in test multiple wallet scans can occur at same time, resulting in error.
141-
// Just retry after 3 sec.
142-
loop {
143-
let last_synced_height = self
144-
.store
145-
.last_synced_height
146-
.unwrap_or(0)
147-
.max(self.store.wallet_birthday.unwrap_or(0));
148-
let node_synced = self.rpc.get_block_count()?;
149-
log::debug!("Re-scanning Blockchain from:{last_synced_height} to:{node_synced}");
150-
match self.rpc.rescan_blockchain(
151-
Some(last_synced_height as usize),
152-
Some(node_synced as usize),
153-
) {
154-
Ok(_) => {
155-
self.store.last_synced_height = Some(node_synced);
156-
break;
157-
}
133+
let last_synced_height = self
134+
.store
135+
.last_synced_height
136+
.unwrap_or(0)
137+
.max(self.store.wallet_birthday.unwrap_or(0));
138+
let node_synced = self.rpc.get_block_count()?;
139+
log::info!("Re-scanning Blockchain from:{last_synced_height} to:{node_synced}");
140+
141+
let _ = self.rpc.rescan_blockchain(
142+
Some(last_synced_height as usize),
143+
Some(node_synced as usize),
144+
);
158145

159-
Err(e) => {
160-
log::warn!("Sync Error, Retrying: {e}");
146+
// Returns when the scanning is completed
147+
loop {
148+
let wallet_info = self.rpc.get_wallet_info()?;
149+
match wallet_info.scanning {
150+
Some(ScanningDetails::Scanning { duration, .. }) => {
151+
// Todo: Show scan progress
152+
log::info!("Scanning for {}s", duration);
161153
thread::sleep(HEART_BEAT_INTERVAL);
162154
continue;
163155
}
156+
Some(ScanningDetails::NotScanning(_)) => {
157+
log::info!("Scanning completed");
158+
break;
159+
}
160+
None => {
161+
log::info!("No scan is in progress or Scanning completed");
162+
break;
163+
}
164164
}
165165
}
166-
166+
self.store.last_synced_height = Some(node_synced);
167167
self.update_utxo_cache(self.get_all_utxo_from_rpc()?);
168168

169169
let max_external_index = self.find_hd_next_index(KeychainKind::External)?;
@@ -177,6 +177,7 @@ impl Wallet {
177177
fn sync_no_fail(&mut self) {
178178
while let Err(e) = self.sync() {
179179
log::error!("Blockchain sync failed. Retrying. | {e:?}");
180+
thread::sleep(HEART_BEAT_INTERVAL);
180181
}
181182
}
182183

tests/fidelity.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ fn test_fidelity() {
161161
log::info!("📊 Verifying balances with both fidelity bonds");
162162
// Verify balances
163163
{
164+
maker.get_wallet().write().unwrap().sync_and_save().unwrap();
164165
let wallet_read = maker.get_wallet().read().unwrap();
165166

166167
let balances = wallet_read.get_balances().unwrap();

0 commit comments

Comments
 (0)