diff --git a/ethereum/src/consensus.rs b/ethereum/src/consensus.rs index c953f713..fe81f3f4 100644 --- a/ethereum/src/consensus.rs +++ b/ethereum/src/consensus.rs @@ -43,7 +43,7 @@ pub struct ConsensusClient, DB: Database> { pub finalized_block_recv: Option>>>, pub checkpoint_recv: watch::Receiver>, genesis_time: u64, - db: DB, + db: Arc, config: Arc, phantom: PhantomData<(S, R)>, } @@ -80,11 +80,6 @@ impl, DB: Database> Consensus } fn shutdown(&self) -> Result<()> { - let checkpoint = self.checkpoint_recv.borrow(); - if let Some(checkpoint) = checkpoint.as_ref() { - self.db.save_checkpoint(*checkpoint)?; - } - Ok(()) } } @@ -98,7 +93,7 @@ impl, DB: Database> ConsensusClient, DB: Database> ConsensusClient, DB: Database> ConsensusClient( + mut checkpoint_recv: watch::Receiver>, + db: Arc, + initial_checkpoint: B256, +) { + #[cfg(not(target_arch = "wasm32"))] + let run = tokio::spawn; + + #[cfg(target_arch = "wasm32")] + let run = wasm_bindgen_futures::spawn_local; + + run(async move { + let mut last_saved_checkpoint = initial_checkpoint; + loop { + let new_checkpoint = *checkpoint_recv.borrow_and_update(); + if let Some(new_checkpoint) = new_checkpoint.as_ref() { + if *new_checkpoint != last_saved_checkpoint { + // There is a more recent checkpoint to save + if db.save_checkpoint(*new_checkpoint).is_err() { + warn!(target: "helios::consensus", "failed to save checkpoint"); + } else { + info!(target: "helios::consensus", "saved checkpoint to DB: 0x{}", hex::encode(*new_checkpoint)); + last_saved_checkpoint = *new_checkpoint; + } + } + } + if checkpoint_recv.changed().await.is_err() { + break; + } + } + }); +} + async fn sync_fallback>( inner: &mut Inner, fallback: &str,