2c1834a6f0b7ac92caec7c712a659dd25786c718
[ldk-sample] / src / disk.rs
1 use crate::cli;
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;
8 use std::fs;
9 use std::fs::File;
10 use std::io::{BufRead, BufReader, BufWriter};
11 use std::net::SocketAddr;
12 use std::path::Path;
13 use time::OffsetDateTime;
14
15 pub(crate) struct FilesystemLogger {
16         data_dir: String,
17 }
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 }
23         }
24 }
25 impl Logger for FilesystemLogger {
26         fn log(&self, record: &Record) {
27                 let raw_log = record.args.to_string();
28                 let log = format!(
29                         "{} {:<5} [{}:{}] {}\n",
30                         OffsetDateTime::now_utc().format("%F %T"),
31                         record.level.to_string(),
32                         record.module_path,
33                         record.line,
34                         raw_log
35                 );
36                 let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
37                 fs::OpenOptions::new()
38                         .create(true)
39                         .append(true)
40                         .open(logs_file_path)
41                         .unwrap()
42                         .write_all(log.as_bytes())
43                         .unwrap();
44         }
45 }
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())
49 }
50
51 pub(crate) fn read_channel_peer_data(
52         path: &Path,
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());
57         }
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);
64                         }
65                         Err(e) => return Err(e),
66                 }
67         }
68         Ok(peer_data)
69 }
70
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);
78                 Err(e)
79         } else {
80                 Ok(())
81         }
82 }
83
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)) {
87                         return graph;
88                 }
89         }
90         NetworkGraph::new(genesis_hash)
91 }