]> git.bitcoin.ninja Git - ldk-sample/blob - src/disk.rs
Correct logging on forwarded HTLCs
[ldk-sample] / src / disk.rs
1 use crate::{cli, NetworkGraph};
2 use bitcoin::secp256k1::PublicKey;
3 use bitcoin::BlockHash;
4 use chrono::Utc;
5 use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
6 use lightning::util::logger::{Logger, Record};
7 use lightning::util::ser::{ReadableArgs, Writer};
8 use std::collections::HashMap;
9 use std::fs;
10 use std::fs::File;
11 use std::io::{BufRead, BufReader};
12 use std::net::SocketAddr;
13 use std::path::Path;
14 use std::sync::Arc;
15
16 pub(crate) struct FilesystemLogger {
17         data_dir: String,
18 }
19 impl FilesystemLogger {
20         pub(crate) fn new(data_dir: String) -> Self {
21                 let logs_path = format!("{}/logs", data_dir);
22                 fs::create_dir_all(logs_path.clone()).unwrap();
23                 Self { data_dir: logs_path }
24         }
25 }
26 impl Logger for FilesystemLogger {
27         fn log(&self, record: &Record) {
28                 let raw_log = record.args.to_string();
29                 let log = format!(
30                         "{} {:<5} [{}:{}] {}\n",
31                         // Note that a "real" lightning node almost certainly does *not* want subsecond
32                         // precision for message-receipt information as it makes log entries a target for
33                         // deanonymization attacks. For testing, however, its quite useful.
34                         Utc::now().format("%Y-%m-%d %H:%M:%S%.3f"),
35                         record.level.to_string(),
36                         record.module_path,
37                         record.line,
38                         raw_log
39                 );
40                 let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
41                 fs::OpenOptions::new()
42                         .create(true)
43                         .append(true)
44                         .open(logs_file_path)
45                         .unwrap()
46                         .write_all(log.as_bytes())
47                         .unwrap();
48         }
49 }
50 pub(crate) fn persist_channel_peer(path: &Path, peer_info: &str) -> std::io::Result<()> {
51         let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?;
52         file.write_all(format!("{}\n", peer_info).as_bytes())
53 }
54
55 pub(crate) fn read_channel_peer_data(
56         path: &Path,
57 ) -> Result<HashMap<PublicKey, SocketAddr>, std::io::Error> {
58         let mut peer_data = HashMap::new();
59         if !Path::new(&path).exists() {
60                 return Ok(HashMap::new());
61         }
62         let file = File::open(path)?;
63         let reader = BufReader::new(file);
64         for line in reader.lines() {
65                 match cli::parse_peer_info(line.unwrap()) {
66                         Ok((pubkey, socket_addr)) => {
67                                 peer_data.insert(pubkey, socket_addr);
68                         }
69                         Err(e) => return Err(e),
70                 }
71         }
72         Ok(peer_data)
73 }
74
75 pub(crate) fn read_network(
76         path: &Path, genesis_hash: BlockHash, logger: Arc<FilesystemLogger>,
77 ) -> NetworkGraph {
78         if let Ok(file) = File::open(path) {
79                 if let Ok(graph) = NetworkGraph::read(&mut BufReader::new(file), logger.clone()) {
80                         return graph;
81                 }
82         }
83         NetworkGraph::new(genesis_hash, logger)
84 }
85
86 pub(crate) fn read_scorer(
87         path: &Path, graph: Arc<NetworkGraph>, logger: Arc<FilesystemLogger>,
88 ) -> ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>> {
89         let params = ProbabilisticScoringParameters::default();
90         if let Ok(file) = File::open(path) {
91                 let args = (params.clone(), Arc::clone(&graph), Arc::clone(&logger));
92                 if let Ok(scorer) = ProbabilisticScorer::read(&mut BufReader::new(file), args) {
93                         return scorer;
94                 }
95         }
96         ProbabilisticScorer::new(params, graph, logger)
97 }