2 use bitcoin::secp256k1::key::PublicKey;
3 use bitcoin::BlockHash;
4 use lightning::routing::network_graph::NetworkGraph;
5 use lightning::util::logger::{Logger, Record};
6 use lightning::util::ser::{Readable, Writeable, Writer};
7 use std::collections::HashMap;
10 use std::io::{BufRead, BufReader, BufWriter};
11 use std::net::SocketAddr;
13 use time::OffsetDateTime;
15 pub(crate) struct FilesystemLogger {
18 impl FilesystemLogger {
19 pub(crate) fn new(data_dir: String) -> Self {
20 let logs_path = format!("{}/logs", data_dir);
21 fs::create_dir_all(logs_path.clone()).unwrap();
22 Self { data_dir: logs_path }
25 impl Logger for FilesystemLogger {
26 fn log(&self, record: &Record) {
27 let raw_log = record.args.to_string();
29 "{} {:<5} [{}:{}] {}\n",
30 OffsetDateTime::now_utc().format("%F %T"),
31 record.level.to_string(),
36 let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
37 fs::OpenOptions::new()
42 .write_all(log.as_bytes())
46 pub(crate) fn persist_channel_peer(path: &Path, peer_info: &str) -> std::io::Result<()> {
47 let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?;
48 file.write_all(format!("{}\n", peer_info).as_bytes())
51 pub(crate) fn read_channel_peer_data(
53 ) -> Result<HashMap<PublicKey, SocketAddr>, std::io::Error> {
54 let mut peer_data = HashMap::new();
55 if !Path::new(&path).exists() {
56 return Ok(HashMap::new());
58 let file = File::open(path)?;
59 let reader = BufReader::new(file);
60 for line in reader.lines() {
61 match cli::parse_peer_info(line.unwrap()) {
62 Ok((pubkey, socket_addr)) => {
63 peer_data.insert(pubkey, socket_addr);
65 Err(e) => return Err(e),
71 pub(crate) fn persist_network(path: &Path, network_graph: &NetworkGraph) -> std::io::Result<()> {
72 let mut tmp_path = path.to_path_buf().into_os_string();
73 tmp_path.push(".tmp");
74 let file = fs::OpenOptions::new().write(true).create(true).open(&tmp_path)?;
75 let write_res = network_graph.write(&mut BufWriter::new(file));
76 if let Err(e) = write_res.and_then(|_| fs::rename(&tmp_path, path)) {
77 let _ = fs::remove_file(&tmp_path);
84 pub(crate) fn read_network(path: &Path, genesis_hash: BlockHash) -> NetworkGraph {
85 if let Ok(file) = File::open(path) {
86 if let Ok(graph) = NetworkGraph::read(&mut BufReader::new(file)) {
90 NetworkGraph::new(genesis_hash)