diff --git a/chronik/chronik-bridge/src/ffi.rs b/chronik/chronik-bridge/src/ffi.rs --- a/chronik/chronik-bridge/src/ffi.rs +++ b/chronik/chronik-bridge/src/ffi.rs @@ -242,5 +242,9 @@ /// Calls `AbortNode` from shutdown.h to gracefully shut down the node /// when an unrecoverable error occured. fn abort_node(msg: &str, user_msg: &str); + + /// Returns true if a shutdown is requested, false otherwise. + /// See `ShutdownRequested` in `shutdown.h`. + fn shutdown_requested() -> bool; } } diff --git a/chronik/chronik-cpp/chronik_bridge.h b/chronik/chronik-cpp/chronik_bridge.h --- a/chronik/chronik-cpp/chronik_bridge.h +++ b/chronik/chronik-cpp/chronik_bridge.h @@ -85,6 +85,8 @@ void abort_node(const rust::Str msg, const rust::Str user_msg); +bool shutdown_requested(); + } // namespace chronik_bridge #endif // BITCOIN_CHRONIK_CPP_CHRONIK_BRIDGE_H diff --git a/chronik/chronik-cpp/chronik_bridge.cpp b/chronik/chronik-cpp/chronik_bridge.cpp --- a/chronik/chronik-cpp/chronik_bridge.cpp +++ b/chronik/chronik-cpp/chronik_bridge.cpp @@ -304,4 +304,8 @@ AbortNode(std::string(msg), Untranslated(std::string(user_msg))); } +bool shutdown_requested() { + return ShutdownRequested(); +} + } // namespace chronik_bridge diff --git a/chronik/chronik-indexer/src/indexer.rs b/chronik/chronik-indexer/src/indexer.rs --- a/chronik/chronik-indexer/src/indexer.rs +++ b/chronik/chronik-indexer/src/indexer.rs @@ -202,6 +202,10 @@ }; let tip_height = node_tip_info.height; for height in fork_height + 1..=tip_height { + if ffi::shutdown_requested() { + log!("Stopped re-sync adding blocks\n"); + return Ok(()); + } let block_index = ffi::get_block_ancestor(node_tip_index, height)?; let ffi_block = bridge.load_block(block_index)?; let ffi_block = expect_unique_ptr("load_block", &ffi_block); @@ -245,6 +249,11 @@ ); log!("Reverting Chronik blocks {revert_height} to {indexer_height}.\n"); for height in (revert_height..indexer_height).rev() { + if ffi::shutdown_requested() { + log!("Stopped re-sync rewinding blocks\n"); + // return MAX here so we don't add any blocks + return Ok(BlockHeight::MAX); + } let db_block = BlockReader::new(&self.db)? .by_height(height)? .ok_or(BlocksBelowMissing { diff --git a/chronik/chronik-lib/src/bridge.rs b/chronik/chronik-lib/src/bridge.rs --- a/chronik/chronik-lib/src/bridge.rs +++ b/chronik/chronik-lib/src/bridge.rs @@ -72,6 +72,10 @@ fn_compress_script: compress_script, })?; indexer.resync_indexer(bridge_ref)?; + if chronik_bridge::ffi::shutdown_requested() { + // Don't setup Chronik if the user requested shutdown during resync + return Ok(()); + } let indexer = Arc::new(RwLock::new(indexer)); let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all()