X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fdisk.rs;h=b641ebb053167b01c6f397c1ef40d0decd98ad61;hb=1030ef91aa47667ff244e087e8f25c24581e5f19;hp=cd4ea909ef160b658ca241c110d1521c02e9e7e7;hpb=25a4f605443ed2bc2bb9548f5679a86fc76d0333;p=ldk-sample diff --git a/src/disk.rs b/src/disk.rs index cd4ea90..b641ebb 100644 --- a/src/disk.rs +++ b/src/disk.rs @@ -1,105 +1,94 @@ -use bitcoin::{BlockHash, Txid}; -use bitcoin::hashes::hex::FromHex; -use bitcoin::secp256k1::key::PublicKey; use crate::cli; -use lightning::chain::channelmonitor::ChannelMonitor; -use lightning::chain::keysinterface::{InMemorySigner, KeysManager}; -use lightning::chain::transaction::OutPoint; +use bitcoin::secp256k1::key::PublicKey; +use bitcoin::BlockHash; +use chrono::Utc; +use lightning::routing::network_graph::NetworkGraph; use lightning::util::logger::{Logger, Record}; -use lightning::util::ser::{ReadableArgs, Writer}; +use lightning::util::ser::{Readable, Writeable, Writer}; use std::collections::HashMap; use std::fs; use std::fs::File; -// use std::io::{BufRead, BufReader, Cursor, Write}; -use std::io::{BufRead, BufReader, Cursor}; +use std::io::{BufRead, BufReader, BufWriter}; use std::net::SocketAddr; use std::path::Path; -use std::sync::Arc; -use time::OffsetDateTime; -pub(crate) struct FilesystemLogger{ - data_dir: String +pub(crate) struct FilesystemLogger { + data_dir: String, } impl FilesystemLogger { - pub(crate) fn new(data_dir: String) -> Self { - let logs_path = format!("{}/logs", data_dir); - fs::create_dir_all(logs_path.clone()).unwrap(); - Self { - data_dir: logs_path - } - } + pub(crate) fn new(data_dir: String) -> Self { + let logs_path = format!("{}/logs", data_dir); + fs::create_dir_all(logs_path.clone()).unwrap(); + Self { data_dir: logs_path } + } } impl Logger for FilesystemLogger { - fn log(&self, record: &Record) { - let raw_log = record.args.to_string(); - let log = format!("{} {:<5} [{}:{}] {}\n", OffsetDateTime::now_utc().format("%F %T"), - record.level.to_string(), record.module_path, record.line, raw_log); - let logs_file_path = format!("{}/logs.txt", self.data_dir.clone()); - fs::OpenOptions::new().create(true).append(true).open(logs_file_path).unwrap() - .write_all(log.as_bytes()).unwrap(); - } + fn log(&self, record: &Record) { + let raw_log = record.args.to_string(); + let log = format!( + "{} {:<5} [{}:{}] {}\n", + // Note that a "real" lightning node almost certainly does *not* want subsecond + // precision for message-receipt information as it makes log entries a target for + // deanonymization attacks. For testing, however, its quite useful. + Utc::now().format("%Y-%m-%d %H:%M:%S%.3f"), + record.level.to_string(), + record.module_path, + record.line, + raw_log + ); + let logs_file_path = format!("{}/logs.txt", self.data_dir.clone()); + fs::OpenOptions::new() + .create(true) + .append(true) + .open(logs_file_path) + .unwrap() + .write_all(log.as_bytes()) + .unwrap(); + } } pub(crate) fn persist_channel_peer(path: &Path, peer_info: &str) -> std::io::Result<()> { - let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?; - file.write_all(format!("{}\n", peer_info).as_bytes()) + let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?; + file.write_all(format!("{}\n", peer_info).as_bytes()) } -pub(crate) fn read_channel_peer_data(path: &Path) -> Result, std::io::Error> { - let mut peer_data = HashMap::new(); - if !Path::new(&path).exists() { - return Ok(HashMap::new()) - } - let file = File::open(path)?; - let reader = BufReader::new(file); - for line in reader.lines() { - match cli::parse_peer_info(line.unwrap()) { - Ok((pubkey, socket_addr)) => { - peer_data.insert(pubkey, socket_addr); - }, - Err(e) => return Err(e) - } - } - Ok(peer_data) +pub(crate) fn read_channel_peer_data( + path: &Path, +) -> Result, std::io::Error> { + let mut peer_data = HashMap::new(); + if !Path::new(&path).exists() { + return Ok(HashMap::new()); + } + let file = File::open(path)?; + let reader = BufReader::new(file); + for line in reader.lines() { + match cli::parse_peer_info(line.unwrap()) { + Ok((pubkey, socket_addr)) => { + peer_data.insert(pubkey, socket_addr); + } + Err(e) => return Err(e), + } + } + 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_channelmonitors(path: String, keys_manager: Arc) -> - Result)>, std::io::Error> -{ - if !Path::new(&path).exists() { - return Ok(HashMap::new()) - } - let mut outpoint_to_channelmonitor = HashMap::new(); - for file_option in fs::read_dir(path).unwrap() { - let file = file_option.unwrap(); - let owned_file_name = file.file_name(); - let filename = owned_file_name.to_str(); - if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 { - return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid ChannelMonitor file name")); - } - - let txid = Txid::from_hex(filename.unwrap().split_at(64).0); - if txid.is_err() { - return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid tx ID in filename")); - } - - let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse(); - if index.is_err() { - return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid tx index in filename")); - } - - let contents = fs::read(&file.path())?; - - if let Ok((blockhash, channel_monitor)) = - <(BlockHash, ChannelMonitor)>::read(&mut Cursor::new(&contents), - &*keys_manager) - { - outpoint_to_channelmonitor.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, - (blockhash, channel_monitor)); - } else { - return Err(std::io::Error::new(std::io::ErrorKind::Other, - "Failed to deserialize ChannelMonitor")); - } - } - Ok(outpoint_to_channelmonitor) +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) }