b641ebb053167b01c6f397c1ef40d0decd98ad61
[ldk-sample] / src / disk.rs
1 use crate::cli;
2 use bitcoin::secp256k1::key::PublicKey;
3 use bitcoin::BlockHash;
4 use chrono::Utc;
5 use lightning::routing::network_graph::NetworkGraph;
6 use lightning::util::logger::{Logger, Record};
7 use lightning::util::ser::{Readable, Writeable, Writer};
8 use std::collections::HashMap;
9 use std::fs;
10 use std::fs::File;
11 use std::io::{BufRead, BufReader, BufWriter};
12 use std::net::SocketAddr;
13 use std::path::Path;
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                         // Note that a "real" lightning node almost certainly does *not* want subsecond
31                         // precision for message-receipt information as it makes log entries a target for
32                         // deanonymization attacks. For testing, however, its quite useful.
33                         Utc::now().format("%Y-%m-%d %H:%M:%S%.3f"),
34                         record.level.to_string(),
35                         record.module_path,
36                         record.line,
37                         raw_log
38                 );
39                 let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
40                 fs::OpenOptions::new()
41                         .create(true)
42                         .append(true)
43                         .open(logs_file_path)
44                         .unwrap()
45                         .write_all(log.as_bytes())
46                         .unwrap();
47         }
48 }
49 pub(crate) fn persist_channel_peer(path: &Path, peer_info: &str) -> std::io::Result<()> {
50         let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?;
51         file.write_all(format!("{}\n", peer_info).as_bytes())
52 }
53
54 pub(crate) fn read_channel_peer_data(
55         path: &Path,
56 ) -> Result<HashMap<PublicKey, SocketAddr>, std::io::Error> {
57         let mut peer_data = HashMap::new();
58         if !Path::new(&path).exists() {
59                 return Ok(HashMap::new());
60         }
61         let file = File::open(path)?;
62         let reader = BufReader::new(file);
63         for line in reader.lines() {
64                 match cli::parse_peer_info(line.unwrap()) {
65                         Ok((pubkey, socket_addr)) => {
66                                 peer_data.insert(pubkey, socket_addr);
67                         }
68                         Err(e) => return Err(e),
69                 }
70         }
71         Ok(peer_data)
72 }
73
74 pub(crate) fn persist_network(path: &Path, network_graph: &NetworkGraph) -> std::io::Result<()> {
75         let mut tmp_path = path.to_path_buf().into_os_string();
76         tmp_path.push(".tmp");
77         let file = fs::OpenOptions::new().write(true).create(true).open(&tmp_path)?;
78         let write_res = network_graph.write(&mut BufWriter::new(file));
79         if let Err(e) = write_res.and_then(|_| fs::rename(&tmp_path, path)) {
80                 let _ = fs::remove_file(&tmp_path);
81                 Err(e)
82         } else {
83                 Ok(())
84         }
85 }
86
87 pub(crate) fn read_network(path: &Path, genesis_hash: BlockHash) -> NetworkGraph {
88         if let Ok(file) = File::open(path) {
89                 if let Ok(graph) = NetworkGraph::read(&mut BufReader::new(file)) {
90                         return graph;
91                 }
92         }
93         NetworkGraph::new(genesis_hash)
94 }