From 3aeec96470cc681bf6bf50baa5ce1b533762c479 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 19 Sep 2018 17:39:43 -0400 Subject: [PATCH] Add module and all-pub-things docs and deny missing docs --- src/chain/chaininterface.rs | 7 +++ src/chain/mod.rs | 3 + src/chain/transaction.rs | 3 + src/lib.rs | 11 ++++ src/ln/channelmanager.rs | 11 ++++ src/ln/channelmonitor.rs | 23 ++++++++ src/ln/mod.rs | 9 +++ src/ln/msgs.rs | 114 +++++++++++++++++++++++++++++++++--- src/ln/peer_handler.rs | 17 ++++++ src/ln/router.rs | 13 ++++ src/util/errors.rs | 19 +++++- src/util/events.rs | 17 ++++++ src/util/logger.rs | 9 ++- src/util/mod.rs | 2 + src/util/ser.rs | 3 + 15 files changed, 248 insertions(+), 13 deletions(-) diff --git a/src/chain/chaininterface.rs b/src/chain/chaininterface.rs index 6f6362284..c6b3b1b62 100644 --- a/src/chain/chaininterface.rs +++ b/src/chain/chaininterface.rs @@ -1,3 +1,7 @@ +//! Traits and utility impls which allow other parts of rust-lightning to interact with the +//! blockchain - receiving notifications of new blocks and block disconnections and allowing +//! rust-lightning to request that you monitor the chain for certain outpoints/transactions. + use bitcoin::blockdata::block::{Block, BlockHeader}; use bitcoin::blockdata::transaction::Transaction; use bitcoin::blockdata::script::Script; @@ -38,6 +42,8 @@ pub trait ChainWatchInterface: Sync + Send { /// Indicates that a listener needs to see all transactions. fn watch_all_txn(&self); + /// Register the given listener to receive events. Only a weak pointer is provided and the + /// registration should be freed once that pointer expires. fn register_listener(&self, listener: Weak); //TODO: unregister @@ -229,6 +235,7 @@ impl ChainWatchInterface for ChainWatchInterfaceUtil { } impl ChainWatchInterfaceUtil { + /// Creates a new ChainWatchInterfaceUtil for the given network pub fn new(network: Network, logger: Arc) -> ChainWatchInterfaceUtil { ChainWatchInterfaceUtil { network: network, diff --git a/src/chain/mod.rs b/src/chain/mod.rs index 54b13eaa1..2919e08bf 100644 --- a/src/chain/mod.rs +++ b/src/chain/mod.rs @@ -1,2 +1,5 @@ +//! Module provides structs and traits which allow other parts of rust-lightning to interact with +//! the blockchain. + pub mod chaininterface; pub mod transaction; diff --git a/src/chain/transaction.rs b/src/chain/transaction.rs index 227afa0de..73e08ea22 100644 --- a/src/chain/transaction.rs +++ b/src/chain/transaction.rs @@ -1,3 +1,5 @@ +//! Contains simple structs describing parts of transactions on the chain. + use bitcoin::util::hash::Sha256dHash; use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint; @@ -27,6 +29,7 @@ impl OutPoint { res } + /// Converts this OutPoint into the OutPoint field as used by rust-bitcoin pub fn into_bitcoin_outpoint(self) -> BitcoinOutPoint { BitcoinOutPoint { txid: self.txid, diff --git a/src/lib.rs b/src/lib.rs index 1fa7b21e0..bd71b15f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,16 @@ #![crate_name = "lightning"] +//! Rust-Lightning, not Rusty's Lightning! +//! +//! A full-featured but also flexible lightning implementation, in library form. This allows the +//! user (you) to decide how they wish to use it instead of being a fully self-contained daemon. +//! This means there is no built-in threading/execution environment and its up to the user to +//! figure out how best to make networking happen/timers fire/things get written to disk/keys get +//! generated/etc. This makes it a good candidate for tight integration into an existing wallet +//! instead of having a rather-separate lightning appendage to a wallet. + +#![cfg_attr(not(feature = "fuzztarget"), deny(missing_docs))] + extern crate bitcoin; extern crate crypto; extern crate rand; diff --git a/src/ln/channelmanager.rs b/src/ln/channelmanager.rs index d6246166b..9b3f7713c 100644 --- a/src/ln/channelmanager.rs +++ b/src/ln/channelmanager.rs @@ -1,3 +1,11 @@ +//! The top-level channel management and payment tracking stuff lives here. +//! The ChannelManager is the main chunk of logic implementing the lightning protocol and is +//! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those +//! upon reconnect to the relevant peer(s). +//! It does not manage routing logic (see ln::router for that) nor does it manage constructing +//! on-chain transactions (it only monitors the chain to watch for any force-closes that might +//! imply it needs to fail HTLCs/payments/channels it manages). + use bitcoin::blockdata::block::BlockHeader; use bitcoin::blockdata::transaction::Transaction; use bitcoin::blockdata::constants::genesis_block; @@ -258,6 +266,7 @@ struct OnionKeys { mu: [u8; 32], } +/// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels pub struct ChannelDetails { /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes, /// thereafter this is the txid of the funding transaction xor the funding transaction output). @@ -267,7 +276,9 @@ pub struct ChannelDetails { /// The position of the funding transaction in the chain. None if the funding transaction has /// not yet been confirmed and the channel fully opened. pub short_channel_id: Option, + /// The node_id of our counterparty pub remote_network_id: PublicKey, + /// The value, in satoshis, of this channel as appears in the funding output pub channel_value_satoshis: u64, /// The user_id passed in to create_channel, or 0 if the channel was inbound. pub user_id: u64, diff --git a/src/ln/channelmonitor.rs b/src/ln/channelmonitor.rs index cd38c9c1a..f3eed0fe1 100644 --- a/src/ln/channelmonitor.rs +++ b/src/ln/channelmonitor.rs @@ -1,3 +1,14 @@ +//! The logic to monitor for on-chain transactions and create the relevant claim responses lives +//! here. +//! ChannelMonitor objects are generated by ChannelManager in response to relevant +//! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can +//! be made in responding to certain messages, see ManyChannelMonitor for more. +//! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the +//! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date +//! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other +//! security-domain-separated system design, you should consider having multiple paths for +//! ChannelMonitors to get out of the HSM and onto monitoring devices. + use bitcoin::blockdata::block::BlockHeader; use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction}; use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint; @@ -24,6 +35,7 @@ use std::collections::HashMap; use std::sync::{Arc,Mutex}; use std::{hash,cmp}; +/// An error enum representing a failure to persist a channel monitor update. pub enum ChannelMonitorUpdateErr { /// Used to indicate a temporary failure (eg connection to a watchtower failed, but is expected /// to succeed at some point in the future). @@ -88,6 +100,8 @@ impl ChainListener for SimpleManyChannelMonit } impl SimpleManyChannelMonitor { + /// Creates a new object which can be used to monitor several channels given the chain + /// interface with which to register to receive notifications. pub fn new(chain_monitor: Arc, broadcaster: Arc) -> Arc> { let res = Arc::new(SimpleManyChannelMonitor { monitors: Mutex::new(HashMap::new()), @@ -99,6 +113,7 @@ impl SimpleManyChannelMonitor res } + /// Adds or udpates the monitor which monitors the channel referred to by the given key. pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> { let mut monitors = self.monitors.lock().unwrap(); match monitors.get_mut(&key) { @@ -162,6 +177,10 @@ struct LocalSignedTx { const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; +/// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates +/// on-chain transactions to ensure no loss of funds occurs. +/// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date +/// information and are actively monitoring the chain. pub struct ChannelMonitor { funding_txo: Option<(OutPoint, Script)>, commitment_transaction_number_obscure_factor: u64, @@ -438,6 +457,9 @@ impl ChannelMonitor { self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone()); } + /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor. + /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the + /// chain for new blocks/transactions. pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> { if self.funding_txo.is_some() { // We should be able to compare the entire funding_txo, but in fuzztarget its trivially @@ -499,6 +521,7 @@ impl ChannelMonitor { self.funding_txo = None; } + /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for. pub fn get_funding_txo(&self) -> Option { match self.funding_txo { Some((outpoint, _)) => Some(outpoint), diff --git a/src/ln/mod.rs b/src/ln/mod.rs index fe4eeed8e..0f3b74544 100644 --- a/src/ln/mod.rs +++ b/src/ln/mod.rs @@ -1,3 +1,12 @@ +//! High level lightning structs and impls live here. +//! You probably want to create a channelmanager::ChannelManager, and a router::Router first. +//! Then, you probably want to pass them both on to a peer_handler::PeerManager and use that to +//! create/manage connections and call get_and_clear_pending_events after each action, handling +//! them appropriately. +//! When you want to open/close a channel or send a payment, call into your ChannelManager and when +//! you want to learn things about the network topology (eg get a route for sending a payment), +//! call into your Router. + pub mod channelmanager; pub mod channelmonitor; pub mod msgs; diff --git a/src/ln/msgs.rs b/src/ln/msgs.rs index c43a5dc9c..5dd3165bf 100644 --- a/src/ln/msgs.rs +++ b/src/ln/msgs.rs @@ -1,3 +1,18 @@ +//! Wire messages, traits representing wire message handlers, and a few error types live here. +//! For a normal node you probably don't need to use anything here, however, if you wish to split a +//! node into an internet-facing route/message socket handling daemon and a separate daemon (or +//! server entirely) which handles only channel-related messages you may wish to implement +//! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across +//! daemons/servers. +//! Note that if you go with such an architecture (instead of passing raw socket events to a +//! non-internet-facing system) you trust the frontend internet-facing system to not lie about the +//! source node_id of the mssage, however this does allow you to significantly reduce bandwidth +//! between the systems as routing messages can represent a significant chunk of bandwidth usage +//! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids +//! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send +//! raw socket events into your non-internet-facing system and then send routing events back to +//! track the network on the less-secure system. + use secp256k1::key::PublicKey; use secp256k1::{Secp256k1, Signature}; use secp256k1; @@ -12,6 +27,7 @@ use std::result::Result; use util::{byte_utils, events}; use util::ser::{Readable, Writeable, Writer}; +/// An error in decoding a message or struct. #[derive(Debug)] pub enum DecodeError { /// Unknown realm byte in an OnionHopData packet @@ -130,25 +146,30 @@ impl GlobalFeatures { } } +/// An init message to be sent or received from a peer pub struct Init { pub(crate) global_features: GlobalFeatures, pub(crate) local_features: LocalFeatures, } +/// An error message to be sent or received from a peer pub struct ErrorMessage { pub(crate) channel_id: [u8; 32], pub(crate) data: String, } +/// A ping message to be sent or received from a peer pub struct Ping { pub(crate) ponglen: u16, pub(crate) byteslen: u16, } +/// A pong message to be sent or received from a peer pub struct Pong { pub(crate) byteslen: u16, } +/// An open_channel message to be sent or received from a peer pub struct OpenChannel { pub(crate) chain_hash: Sha256dHash, pub(crate) temporary_channel_id: [u8; 32], @@ -171,6 +192,7 @@ pub struct OpenChannel { pub(crate) shutdown_scriptpubkey: Option