Skip to content

Commit 9b58d36

Browse files
authored
Merge pull request #85 from buffrr/sync-checks
Clean up sync checks, remove mainnet alpha, and fix testnet sync
2 parents b2aed62 + 5fbed07 commit 9b58d36

File tree

5 files changed

+76
-27
lines changed

5 files changed

+76
-27
lines changed

client/src/bin/spaced.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,8 @@ impl Composer {
129129
}
130130

131131
async fn run(&mut self) -> anyhow::Result<()> {
132-
let spaced = Args::configure().await?;
132+
let shutdown_receiver = self.shutdown.subscribe();
133+
let spaced = Args::configure(shutdown_receiver).await?;
133134
self.setup_rpc_services(&spaced).await;
134135
self.setup_sync_service(spaced).await;
135136

client/src/config.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,6 @@ pub struct Args {
8888
#[serde(rename_all = "lowercase")]
8989
pub enum ExtendedNetwork {
9090
Mainnet,
91-
MainnetAlpha,
9291
Testnet,
9392
Testnet4,
9493
Signet,
@@ -98,7 +97,7 @@ pub enum ExtendedNetwork {
9897
impl ExtendedNetwork {
9998
pub fn fallback_network(&self) -> Network {
10099
match self {
101-
ExtendedNetwork::Mainnet | ExtendedNetwork::MainnetAlpha => Network::Bitcoin,
100+
ExtendedNetwork::Mainnet => Network::Bitcoin,
102101
ExtendedNetwork::Testnet => Network::Testnet,
103102
ExtendedNetwork::Signet => Network::Signet,
104103
ExtendedNetwork::Regtest => Network::Regtest,
@@ -110,7 +109,7 @@ impl ExtendedNetwork {
110109
impl Args {
111110
/// Configures spaced node by processing command line arguments
112111
/// and configuration files
113-
pub async fn configure() -> anyhow::Result<Spaced> {
112+
pub async fn configure(shutdown: tokio::sync::broadcast::Receiver<()>) -> anyhow::Result<Spaced> {
114113
let mut args = Args::merge_args_config(None);
115114
let default_dirs = get_default_node_dirs();
116115

@@ -170,7 +169,7 @@ impl Args {
170169
!args.bitcoin_rpc_light
171170
);
172171

173-
let genesis = Spaced::genesis(&rpc, args.chain).await?;
172+
let genesis = Spaced::genesis(&rpc, args.chain, shutdown).await?;
174173

175174
fs::create_dir_all(data_dir.clone())?;
176175

@@ -282,7 +281,7 @@ pub fn safe_exit(code: i32) -> ! {
282281

283282
pub fn default_bitcoin_rpc_url(network: &ExtendedNetwork) -> &'static str {
284283
match network {
285-
ExtendedNetwork::Mainnet | ExtendedNetwork::MainnetAlpha => "http://127.0.0.1:8332",
284+
ExtendedNetwork::Mainnet => "http://127.0.0.1:8332",
286285
ExtendedNetwork::Testnet4 => "http://127.0.0.1:48332",
287286
ExtendedNetwork::Signet => "http://127.0.0.1:38332",
288287
ExtendedNetwork::Testnet => "http://127.0.0.1:18332",
@@ -380,7 +379,6 @@ impl Display for ExtendedNetwork {
380379
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381380
let str = match self {
382381
ExtendedNetwork::Mainnet => "mainnet".to_string(),
383-
ExtendedNetwork::MainnetAlpha => "mainnet-alpha".to_string(),
384382
ExtendedNetwork::Testnet => "testnet".to_string(),
385383
ExtendedNetwork::Testnet4 => "testnet4".to_string(),
386384
ExtendedNetwork::Signet => "signet".to_string(),
@@ -393,7 +391,6 @@ impl Display for ExtendedNetwork {
393391
pub fn default_spaces_rpc_port(chain: &ExtendedNetwork) -> u16 {
394392
match chain {
395393
ExtendedNetwork::Mainnet => 7225,
396-
ExtendedNetwork::MainnetAlpha => 7225,
397394
ExtendedNetwork::Testnet4 => 7224,
398395
ExtendedNetwork::Testnet => 7223,
399396
ExtendedNetwork::Signet => 7221,

client/src/source.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -896,15 +896,22 @@ impl BlockSource for BitcoinBlockSource {
896896
#[serde(rename = "bestblockhash")]
897897
pub best_block_hash: BlockHash,
898898
}
899-
let info: Info = self
899+
let mut info: Info = self
900900
.rpc
901901
.send_json_blocking(&self.client, &self.rpc.get_blockchain_info())?;
902902

903+
// TODO: update this check once testnet4 is part of the [Network] type.
904+
// use network names from bitcoin core
905+
// https://github.com/bitcoin/bitcoin/blob/master/src/util/chaintype.cpp
903906
let expected_chain = match expected_chain {
904907
Network::Bitcoin => "main",
905908
Network::Regtest => "regtest",
909+
Network::Signet => "signet",
906910
_ => "test"
907911
};
912+
if info.chain.starts_with("test") {
913+
info.chain = "test".to_string()
914+
}
908915
if info.chain != expected_chain {
909916
warn!("Invalid chain from connected rpc node - expected {}, got {}", expected_chain, info.chain);
910917
return Ok(None);

client/src/sync.rs

+62-13
Original file line numberDiff line numberDiff line change
@@ -257,34 +257,83 @@ impl Spaced {
257257
pub async fn genesis(
258258
rpc: &BitcoinRpc,
259259
network: ExtendedNetwork,
260+
mut shutdown: tokio::sync::broadcast::Receiver<()>
260261
) -> anyhow::Result<ChainAnchor> {
261262
let mut anchor = match network {
262263
ExtendedNetwork::Testnet => ChainAnchor::TESTNET(),
263264
ExtendedNetwork::Testnet4 => ChainAnchor::TESTNET4(),
264265
ExtendedNetwork::Regtest => ChainAnchor::REGTEST(),
265266
ExtendedNetwork::Mainnet => ChainAnchor::MAINNET(),
266-
ExtendedNetwork::MainnetAlpha => ChainAnchor::MAINNET_ALPHA(),
267267
_ => panic!("unsupported network"),
268268
};
269269

270-
if anchor.hash == BlockHash::all_zeros() {
271-
let client = reqwest::Client::new();
272270

273-
anchor.hash = match rpc
274-
.send_json(&client, &rpc.get_block_hash(anchor.height))
275-
.await
276-
{
277-
Ok(hash) => hash,
278-
Err(e) => {
279-
return Err(anyhow!(
280-
"Could not retrieve activation block at height {}: {}",
281-
anchor.height,
282-
e
271+
272+
// Wait for the RPC node to be ready
273+
let mut attempts = 0;
274+
let mut last_error = BitcoinRpcError::Other("Unknown error".to_string());
275+
loop {
276+
if shutdown.try_recv().is_ok() {
277+
return Err(anyhow!("Fetching activation height terminated: shutdown requested"))
278+
}
279+
if attempts > 5 {
280+
return Err(anyhow!(
281+
"Could not retrieve activation height: {}",
282+
last_error
283283
));
284+
}
285+
286+
let rpc_task = rpc.clone();
287+
let net_task = network.fallback_network();
288+
let best_chain = tokio::task::spawn_blocking(move || {
289+
let source = BitcoinBlockSource::new(rpc_task);
290+
source.get_best_chain(Some(anchor.height), net_task)
291+
}).await.expect("join");
292+
293+
match best_chain {
294+
Ok(Some(tip)) => {
295+
info!("Connect to RPC node (tip: {})", tip.height);
296+
if anchor.hash != BlockHash::all_zeros() {
297+
break;
298+
}
299+
300+
// Pull the activation block hash
301+
let client = reqwest::Client::new();
302+
anchor.hash = match rpc
303+
.send_json(&client, &rpc.get_block_hash(anchor.height))
304+
.await
305+
{
306+
Ok(hash) => hash,
307+
Err(e) => {
308+
warn!("Fetching height {}:{}, retrying in 1s ...", anchor.height, e);
309+
last_error = e;
310+
match &last_error {
311+
BitcoinRpcError::Rpc(_) => {}
312+
_ => attempts += 1,
313+
}
314+
continue;
315+
}
316+
};
317+
318+
break;
319+
}
320+
Ok(None) => {
321+
warn!("Connected RPC node is still syncing, waiting 5s ...");
322+
tokio::time::sleep(Duration::from_secs(5)).await;
323+
}
324+
Err(e) => {
325+
warn!("Error fetching blockchain info: {}, retrying in 1s ...", e);
326+
last_error = e;
327+
tokio::time::sleep(Duration::from_secs(1)).await;
328+
match &last_error {
329+
BitcoinRpcError::Rpc(_) => {}
330+
_ => attempts += 1,
331+
}
284332
}
285333
}
286334
}
287335

336+
288337
Ok(anchor)
289338
}
290339
}

protocol/src/constants.rs

-5
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,6 @@ impl ChainAnchor {
6464
height: 871_222,
6565
};
6666

67-
pub const MAINNET_ALPHA: fn() -> Self = || ChainAnchor {
68-
hash: BlockHash::all_zeros(),
69-
height: 870_000,
70-
};
71-
7267
// Testnet4 activation block
7368
pub const TESTNET4: fn() -> Self = || Self {
7469
hash: BlockHash::all_zeros(),

0 commit comments

Comments
 (0)