X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fdisk.rs;h=2c1834a6f0b7ac92caec7c712a659dd25786c718;hb=e87a9e18f6739988b93b6bc38c1ae178c0bdaeb8;hp=827cb7e9e79326f6a3b8ae5022748267c07bf72a;hpb=6199433ab8f13e4f78b12e13a683eb33c999114b;p=ldk-sample diff --git a/src/disk.rs b/src/disk.rs index 827cb7e..2c1834a 100644 --- a/src/disk.rs +++ b/src/disk.rs @@ -1,11 +1,13 @@ use crate::cli; use bitcoin::secp256k1::key::PublicKey; +use bitcoin::BlockHash; +use lightning::routing::network_graph::NetworkGraph; use lightning::util::logger::{Logger, Record}; -use lightning::util::ser::Writer; +use lightning::util::ser::{Readable, Writeable, Writer}; use std::collections::HashMap; use std::fs; use std::fs::File; -use std::io::{BufRead, BufReader}; +use std::io::{BufRead, BufReader, BufWriter}; use std::net::SocketAddr; use std::path::Path; use time::OffsetDateTime; @@ -65,3 +67,25 @@ pub(crate) fn read_channel_peer_data( } Ok(peer_data) } + +pub(crate) fn persist_network(path: &Path, network_graph: &NetworkGraph) -> std::io::Result<()> { + let mut tmp_path = path.to_path_buf().into_os_string(); + tmp_path.push(".tmp"); + let file = fs::OpenOptions::new().write(true).create(true).open(&tmp_path)?; + let write_res = network_graph.write(&mut BufWriter::new(file)); + if let Err(e) = write_res.and_then(|_| fs::rename(&tmp_path, path)) { + let _ = fs::remove_file(&tmp_path); + Err(e) + } else { + Ok(()) + } +} + +pub(crate) fn read_network(path: &Path, genesis_hash: BlockHash) -> NetworkGraph { + if let Ok(file) = File::open(path) { + if let Ok(graph) = NetworkGraph::read(&mut BufReader::new(file)) { + return graph; + } + } + NetworkGraph::new(genesis_hash) +}