Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix shutdown save peers utreexo #280

Merged
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 @@ -575,7 +575,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 @@ -618,6 +618,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