Skip to content

Commit

Permalink
Fix shutdown save peers utreexo (#280)
Browse files Browse the repository at this point in the history
Added code to save good utreexo peers to a anchors.json file
  • Loading branch information
lucad70 authored Nov 29, 2024
1 parent 259a40e commit 8ede062
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
14 changes: 14 additions & 0 deletions crates/floresta-wire/src/p2p_wire/address_man.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,20 @@ impl AddressMan {
Ok(())
}

/// Dumps the connected utreexo peers to a file on dir `datadir/anchors.json` in json format `
/// inputs are the directory to save the file and the list of ids of the connected utreexo peers
pub fn dump_utreexo_peers(&self, datadir: &str, peers_id: &[usize]) -> std::io::Result<()> {
let addresses: Vec<DiskLocalAddress> = peers_id
.iter()
.filter_map(|id| Some(self.addresses.get(id)?.to_owned().into()))
.collect();
let addresses: Result<String, serde_json::Error> = serde_json::to_string(&addresses);
if let Ok(addresses) = addresses {
std::fs::write(datadir.to_owned() + "/anchors.json", addresses)?;
}
Ok(())
}

fn get_address_by_service(&self, service: ServiceFlags) -> Option<(usize, LocalAddress)> {
let peers = self.good_peers_by_service.get(&service)?;
if peers.is_empty() {
Expand Down
19 changes: 18 additions & 1 deletion crates/floresta-wire/src/p2p_wire/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ where
for peer in self.peer_ids.iter() {
try_and_log!(self.send_to_peer(*peer, NodeRequest::Shutdown).await);
}

try_and_log!(self.save_utreexo_peers());
try_and_log!(self.save_peers());
try_and_log!(self.chain.flush());
}
Expand Down Expand Up @@ -752,6 +752,23 @@ where
.map_err(WireError::Io)
}

/// Saves the utreexo peers to disk so we can reconnect with them later
pub(crate) fn save_utreexo_peers(&self) -> Result<(), WireError> {
let peers: &Vec<u32> = self
.peer_by_service
.get(&service_flags::UTREEXO.into())
.ok_or(WireError::NoPeersAvailable)?;
let peers_usize: Vec<usize> = peers.iter().map(|&peer| peer as usize).collect();
if peers_usize.is_empty() {
warn!("No connected utreexo peers to save to disk");
return Ok(());
}
info!("Saving utreexo peers to disk");
self.address_man
.dump_utreexo_peers(&self.datadir, &peers_usize)
.map_err(WireError::Io)
}

pub(crate) async fn maybe_open_connection(&mut self) -> Result<(), WireError> {
// If the user passes in a `--connect` cli argument, we only connect with
// that particular peer.
Expand Down

0 comments on commit 8ede062

Please sign in to comment.