Add module and all-pub-things docs and deny missing docs 2018-09-docs-docs-docs
authorMatt Corallo <git@bluematt.me>
Wed, 19 Sep 2018 21:39:43 +0000 (17:39 -0400)
committerMatt Corallo <git@bluematt.me>
Thu, 20 Sep 2018 03:07:02 +0000 (23:07 -0400)
15 files changed:
src/chain/chaininterface.rs
src/chain/mod.rs
src/chain/transaction.rs
src/lib.rs
src/ln/channelmanager.rs
src/ln/channelmonitor.rs
src/ln/mod.rs
src/ln/msgs.rs
src/ln/peer_handler.rs
src/ln/router.rs
src/util/errors.rs
src/util/events.rs
src/util/logger.rs
src/util/mod.rs
src/util/ser.rs

index 6f6362284072958115e97d5fe585d4e93e96e2ec..c6b3b1b629d0cd11051215c27c01a2f66237205d 100644 (file)
@@ -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<ChainListener>);
        //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<Logger>) -> ChainWatchInterfaceUtil {
                ChainWatchInterfaceUtil {
                        network: network,
index 54b13eaa1a7af1a9c9f8382ca44083e4752b8a80..2919e08bfb9699061da0cb44246b83e8443c76be 100644 (file)
@@ -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;
index 227afa0de68e35bf8a104ea913f6ce7e2c6b0db0..73e08ea22f41f4d32ac5a7804617e0e7219d0e1d 100644 (file)
@@ -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,
index 1fa7b21e06aaefbdc8b94c7a24bbfe71c55c392e..bd71b15f35c302827607590199ec4029888f84fe 100644 (file)
@@ -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;
index d6246166bb7c3ac9ddd6f2bc2aa6d1a094750230..9b3f7713ca403dbef3a180c05bb53f18681c46ee 100644 (file)
@@ -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<u64>,
+       /// 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,
index cd38c9c1a79b10dde58d07d5b878280d167cb23d..f3eed0fe16ac0ed9d7e4a59d67f8e82bf5330e8f 100644 (file)
@@ -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<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonit
 }
 
 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
+       /// 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<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
                let res = Arc::new(SimpleManyChannelMonitor {
                        monitors: Mutex::new(HashMap::new()),
@@ -99,6 +113,7 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key>
                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<OutPoint> {
                match self.funding_txo {
                        Some((outpoint, _)) => Some(outpoint),
index fe4eeed8e7d49d8e4742b7a03d1bc4e4021cf906..0f3b745443e378d5e53c77c26fc2f339a1693823 100644 (file)
@@ -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;
index c43a5dc9c4d4ff5c0b379d6cdc94f31c904bdc12..5dd3165bfc0977728f8c80b03ba9cfeff3ecdb9f 100644 (file)
@@ -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<Script>,
 }
 
+/// An accept_channel message to be sent or received from a peer
 pub struct AcceptChannel {
        pub(crate) temporary_channel_id: [u8; 32],
        pub(crate) dust_limit_satoshis: u64,
@@ -189,6 +211,7 @@ pub struct AcceptChannel {
        pub(crate) shutdown_scriptpubkey: Option<Script>,
 }
 
+/// A funding_created message to be sent or received from a peer
 pub struct FundingCreated {
        pub(crate) temporary_channel_id: [u8; 32],
        pub(crate) funding_txid: Sha256dHash,
@@ -196,27 +219,32 @@ pub struct FundingCreated {
        pub(crate) signature: Signature,
 }
 
+/// A funding_signed message to be sent or received from a peer
 pub struct FundingSigned {
        pub(crate) channel_id: [u8; 32],
        pub(crate) signature: Signature,
 }
 
+/// A funding_locked message to be sent or received from a peer
 pub struct FundingLocked {
        pub(crate) channel_id: [u8; 32],
        pub(crate) next_per_commitment_point: PublicKey,
 }
 
+/// A shutdown message to be sent or received from a peer
 pub struct Shutdown {
        pub(crate) channel_id: [u8; 32],
        pub(crate) scriptpubkey: Script,
 }
 
+/// A closing_signed message to be sent or received from a peer
 pub struct ClosingSigned {
        pub(crate) channel_id: [u8; 32],
        pub(crate) fee_satoshis: u64,
        pub(crate) signature: Signature,
 }
 
+/// An update_add_htlc message to be sent or received from a peer
 #[derive(Clone)]
 pub struct UpdateAddHTLC {
        pub(crate) channel_id: [u8; 32],
@@ -227,6 +255,7 @@ pub struct UpdateAddHTLC {
        pub(crate) onion_routing_packet: OnionPacket,
 }
 
+/// An update_fulfill_htlc message to be sent or received from a peer
 #[derive(Clone)]
 pub struct UpdateFulfillHTLC {
        pub(crate) channel_id: [u8; 32],
@@ -234,6 +263,7 @@ pub struct UpdateFulfillHTLC {
        pub(crate) payment_preimage: [u8; 32],
 }
 
+/// An update_fail_htlc message to be sent or received from a peer
 #[derive(Clone)]
 pub struct UpdateFailHTLC {
        pub(crate) channel_id: [u8; 32],
@@ -241,6 +271,7 @@ pub struct UpdateFailHTLC {
        pub(crate) reason: OnionErrorPacket,
 }
 
+/// An update_fail_malformed_htlc message to be sent or received from a peer
 #[derive(Clone)]
 pub struct UpdateFailMalformedHTLC {
        pub(crate) channel_id: [u8; 32],
@@ -249,6 +280,7 @@ pub struct UpdateFailMalformedHTLC {
        pub(crate) failure_code: u16,
 }
 
+/// A commitment_signed message to be sent or received from a peer
 #[derive(Clone)]
 pub struct CommitmentSigned {
        pub(crate) channel_id: [u8; 32],
@@ -256,12 +288,14 @@ pub struct CommitmentSigned {
        pub(crate) htlc_signatures: Vec<Signature>,
 }
 
+/// A revoke_and_ack message to be sent or received from a peer
 pub struct RevokeAndACK {
        pub(crate) channel_id: [u8; 32],
        pub(crate) per_commitment_secret: [u8; 32],
        pub(crate) next_per_commitment_point: PublicKey,
 }
 
+/// An update_fee message to be sent or received from a peer
 pub struct UpdateFee {
        pub(crate) channel_id: [u8; 32],
        pub(crate) feerate_per_kw: u32,
@@ -272,6 +306,7 @@ pub(crate) struct DataLossProtect {
        pub(crate) my_current_per_commitment_point: PublicKey,
 }
 
+/// A channel_reestablish message to be sent or received from a peer
 pub struct ChannelReestablish {
        pub(crate) channel_id: [u8; 32],
        pub(crate) next_local_commitment_number: u64,
@@ -279,6 +314,7 @@ pub struct ChannelReestablish {
        pub(crate) data_loss_protect: Option<DataLossProtect>,
 }
 
+/// An announcement_signatures message to be sent or received from a peer
 #[derive(Clone)]
 pub struct AnnouncementSignatures {
        pub(crate) channel_id: [u8; 32],
@@ -287,24 +323,41 @@ pub struct AnnouncementSignatures {
        pub(crate) bitcoin_signature: Signature,
 }
 
+/// An address which can be used to connect to a remote peer
 #[derive(Clone)]
 pub enum NetAddress {
+       /// An IPv4 address/port on which the peer is listenting.
        IPv4 {
+               /// The 4-byte IPv4 address
                addr: [u8; 4],
+               /// The port on which the node is listenting
                port: u16,
        },
+       /// An IPv6 address/port on which the peer is listenting.
        IPv6 {
+               /// The 16-byte IPv6 address
                addr: [u8; 16],
+               /// The port on which the node is listenting
                port: u16,
        },
+       /// An old-style Tor onion address/port on which the peer is listening.
        OnionV2 {
+               /// The bytes (usually encoded in base32 with ".onion" appended)
                addr: [u8; 10],
+               /// The port on which the node is listenting
                port: u16,
        },
+       /// A new-style Tor onion address/port on which the peer is listening.
+       /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
+       /// wrap as base32 and append ".onion".
        OnionV3 {
+               /// The ed25519 long-term public key of the peer
                ed25519_pubkey: [u8; 32],
+               /// The checksum of the pubkey and version, as included in the onion address
                checksum: u16,
+               /// The version byte, as defined by the Tor Onion v3 spec.
                version: u8,
+               /// The port on which the node is listenting
                port: u16,
        },
 }
@@ -319,34 +372,44 @@ impl NetAddress {
        }
 }
 
+// Only exposed as broadcast of node_announcement should be filtered by node_id
+/// The unsigned part of a node_announcement
 pub struct UnsignedNodeAnnouncement {
-       pub features: GlobalFeatures,
-       pub timestamp: u32,
-       pub node_id: PublicKey,
-       pub rgb: [u8; 3],
-       pub alias: [u8; 32],
+       pub(crate) features: GlobalFeatures,
+       pub(crate) timestamp: u32,
+       /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
+       /// to this node).
+       pub        node_id: PublicKey,
+       pub(crate) rgb: [u8; 3],
+       pub(crate) alias: [u8; 32],
        /// List of addresses on which this node is reachable. Note that you may only have up to one
        /// address of each type, if you have more, they may be silently discarded or we may panic!
        pub(crate) addresses: Vec<NetAddress>,
        pub(crate) excess_address_data: Vec<u8>,
        pub(crate) excess_data: Vec<u8>,
 }
+/// A node_announcement message to be sent or received from a peer
 pub struct NodeAnnouncement {
        pub(crate) signature: Signature,
        pub(crate) contents: UnsignedNodeAnnouncement,
 }
 
+// Only exposed as broadcast of channel_announcement should be filtered by node_id
+/// The unsigned part of a channel_announcement
 #[derive(PartialEq, Clone)]
 pub struct UnsignedChannelAnnouncement {
        pub(crate) features: GlobalFeatures,
        pub(crate) chain_hash: Sha256dHash,
        pub(crate) short_channel_id: u64,
+       /// One of the two node_ids which are endpoints of this channel
        pub        node_id_1: PublicKey,
+       /// The other of the two node_ids which are endpoints of this channel
        pub        node_id_2: PublicKey,
        pub(crate) bitcoin_key_1: PublicKey,
        pub(crate) bitcoin_key_2: PublicKey,
        pub(crate) excess_data: Vec<u8>,
 }
+/// A channel_announcement message to be sent or received from a peer
 #[derive(PartialEq, Clone)]
 pub struct ChannelAnnouncement {
        pub(crate) node_signature_1: Signature,
@@ -368,6 +431,7 @@ pub(crate) struct UnsignedChannelUpdate {
        pub(crate) fee_proportional_millionths: u32,
        pub(crate) excess_data: Vec<u8>,
 }
+/// A channel_update message to be sent or received from a peer
 #[derive(PartialEq, Clone)]
 pub struct ChannelUpdate {
        pub(crate) signature: Signature,
@@ -378,18 +442,23 @@ pub struct ChannelUpdate {
 pub enum ErrorAction {
        /// The peer took some action which made us think they were useless. Disconnect them.
        DisconnectPeer {
+               /// An error message which we should make an effort to send before we disconnect.
                msg: Option<ErrorMessage>
        },
        /// The peer did something harmless that we weren't able to process, just log and ignore
        IgnoreError,
        /// The peer did something incorrect. Tell them.
        SendErrorMessage {
+               /// The message to send.
                msg: ErrorMessage
        },
 }
 
+/// An Err type for failure to process messages.
 pub struct HandleError { //TODO: rename me
+       /// A human-readable message describing the error
        pub err: &'static str,
+       /// The action which should be taken against the offending peer.
        pub action: Option<ErrorAction>, //TODO: Make this required
 }
 
@@ -403,41 +472,63 @@ pub struct CommitmentUpdate {
        pub(crate) commitment_signed: CommitmentSigned,
 }
 
+/// The information we received from a peer along the route of a payment we originated. This is
+/// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
+/// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
 pub enum HTLCFailChannelUpdate {
+       /// We received an error which included a full ChannelUpdate message.
        ChannelUpdateMessage {
+               /// The unwrapped message we received
                msg: ChannelUpdate,
        },
+       /// We received an error which indicated only that a channel has been closed
        ChannelClosed {
+               /// The short_channel_id which has now closed.
                short_channel_id: u64,
        },
 }
 
 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
-/// paralell when they originate from different their_node_ids, however they MUST NOT be called in
-/// paralell when the two calls have the same their_node_id.
+/// parallel when they originate from different their_node_ids, however they MUST NOT be called in
+/// parallel when the two calls have the same their_node_id.
 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
        //Channel init:
+       /// Handle an incoming open_channel message from the given peer.
        fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
+       /// Handle an incoming accept_channel message from the given peer.
        fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
+       /// Handle an incoming funding_created message from the given peer.
        fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
+       /// Handle an incoming funding_signed message from the given peer.
        fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
+       /// Handle an incoming funding_locked message from the given peer.
        fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
 
        // Channl close:
+       /// Handle an incoming shutdown message from the given peer.
        fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
+       /// Handle an incoming closing_signed message from the given peer.
        fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
 
        // HTLC handling:
+       /// Handle an incoming update_add_htlc message from the given peer.
        fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
+       /// Handle an incoming update_fulfill_htlc message from the given peer.
        fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
+       /// Handle an incoming update_fail_htlc message from the given peer.
        fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
+       /// Handle an incoming update_fail_malformed_htlc message from the given peer.
        fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
+       /// Handle an incoming commitment_signed message from the given peer.
        fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
+       /// Handle an incoming revoke_and_ack message from the given peer.
        fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
 
+       /// Handle an incoming update_fee message from the given peer.
        fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
 
        // Channel-to-announce:
+       /// Handle an incoming announcement_signatures message from the given peer.
        fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
 
        // Connection loss/reestablish:
@@ -447,19 +538,28 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
        /// and any outstanding channels should be failed.
        fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
 
+       /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
        fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
+       /// Handle an incoming channel_reestablish message from the given peer.
        fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
 
        // Error:
+       /// Handle an incoming error message from the given peer.
        fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
 }
 
+/// A trait to describe an object which can receive routing messages.
 pub trait RoutingMessageHandler : Send + Sync {
+       /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
+       /// false or returning an Err otherwise.
        fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
        /// Handle a channel_announcement message, returning true if it should be forwarded on, false
        /// or returning an Err otherwise.
        fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
+       /// Handle an incoming channel_update message, returning true if it should be forwarded on,
+       /// false or returning an Err otherwise.
        fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
+       /// Handle some updates to the route graph that we learned due to an outbound failed payment.
        fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
 }
 
index 20faf2500b8ed40e911f018edba75b34828c28a4..6c2b4d798c4a002ac52c359c2fe2d5d067eefafd 100644 (file)
@@ -1,3 +1,10 @@
+//! Top level peer message handling and socket handling logic lives here.
+//! Instead of actually servicing sockets ourselves we require that you implement the
+//! SocketDescriptor interface and use that to receive actions which you should perform on the
+//! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
+//! call into the provided message handlers (probably a ChannelManager and Router) with messages
+//! they should handle, and encoding/sending response messages.
+
 use secp256k1::key::{SecretKey,PublicKey};
 
 use ln::msgs;
@@ -12,8 +19,13 @@ use std::sync::{Arc, Mutex};
 use std::sync::atomic::{AtomicUsize, Ordering};
 use std::{cmp,error,mem,hash,fmt};
 
+/// Provides references to trait impls which handle different types of messages.
 pub struct MessageHandler {
+       /// A message handler which handles messages specific to channels. Usually this is just a
+       /// ChannelManager object.
        pub chan_handler: Arc<msgs::ChannelMessageHandler>,
+       /// A message handler which handles messages updating our knowledge of the network channel
+       /// graph. Usually this is just a Router object.
        pub route_handler: Arc<msgs::RoutingMessageHandler>,
 }
 
@@ -51,6 +63,8 @@ pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
 /// no such disconnect_event must be generated and the socket be silently disconencted).
 pub struct PeerHandleError {
+       /// Used to indicate that we probably can't make any future connections to this peer, implying
+       /// we should go ahead and force-close any channels we have with it.
        no_connection_possible: bool,
 }
 impl fmt::Debug for PeerHandleError {
@@ -103,6 +117,8 @@ impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
        }
 }
 
+/// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
+/// events into messages which it passes on to its MessageHandlers.
 pub struct PeerManager<Descriptor: SocketDescriptor> {
        message_handler: MessageHandler,
        peers: Mutex<PeerHolder<Descriptor>>,
@@ -138,6 +154,7 @@ const INITIAL_SYNCS_TO_SEND: usize = 5;
 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
 /// PeerIds may repeat, but only after disconnect_event() has been called.
 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
+       /// Constructs a new PeerManager with the given message handlers and node_id secret key
        pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, logger: Arc<Logger>) -> PeerManager<Descriptor> {
                PeerManager {
                        message_handler: message_handler,
index d2d428a38bc70a27d3cfec4fc04c09bbc744947f..16f996df062047134248d43298aa77d2d6ee4ad1 100644 (file)
@@ -1,3 +1,7 @@
+//! The top-level routing/network map tracking logic lives here.
+//! You probably want to create a Router and use that as your RoutingMessageHandler and then
+//! interrogate it to get routes for your own payments.
+
 use secp256k1::key::PublicKey;
 use secp256k1::{Secp256k1,Message};
 use secp256k1;
@@ -22,6 +26,7 @@ use std;
 /// A hop in a route
 #[derive(Clone)]
 pub struct RouteHop {
+       /// The node_id of the node at this hop.
        pub pubkey: PublicKey,
        /// The channel that should be used from the previous hop to reach this node.
        pub short_channel_id: u64,
@@ -160,11 +165,18 @@ impl NetworkMap {
 
 /// A channel descriptor which provides a last-hop route to get_route
 pub struct RouteHint {
+       /// The node_id of the non-target end of the route
        pub src_node_id: PublicKey,
+       /// The short_channel_id of this channel
        pub short_channel_id: u64,
+       /// The static msat-denominated fee which must be paid to use this channel
        pub fee_base_msat: u32,
+       /// The dynamic proportional fee which must be paid to use this channel, denominated in
+       /// millionths of the value being forwarded to the next hop.
        pub fee_proportional_millionths: u32,
+       /// The difference in CLTV values between this node and the next node.
        pub cltv_expiry_delta: u16,
+       /// The minimum value, in msat, which must be relayed to the next hop.
        pub htlc_minimum_msat: u64,
 }
 
@@ -444,6 +456,7 @@ struct DummyDirectionalChannelInfo {
 }
 
 impl Router {
+       /// Creates a new router with the given node_id to be used as the source for get_route()
        pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
                let mut nodes = HashMap::new();
                nodes.insert(our_pubkey.clone(), NodeInfo {
index 23a349e3e850f9e6aed90dee6058f95a6d8587a5..f9c7f7111951fa8200c558c59dcdbdcbf13f480b 100644 (file)
@@ -1,3 +1,5 @@
+//! Error types live here.
+
 use std::fmt;
 
 /// Indicates an error on the client's part (usually some variant of attempting to use too-low or
@@ -5,14 +7,25 @@ use std::fmt;
 pub enum APIError {
        /// Indicates the API was wholly misused (see err for more). Cases where these can be returned
        /// are documented, but generally indicates some precondition of a function was violated.
-       APIMisuseError {err: &'static str},
+       APIMisuseError {
+               /// A human-readable error message
+               err: &'static str
+       },
        /// Due to a high feerate, we were unable to complete the request.
        /// For example, this may be returned if the feerate implies we cannot open a channel at the
        /// requested value, but opening a larger channel would succeed.
-       FeeRateTooHigh {err: String, feerate: u64},
+       FeeRateTooHigh {
+               /// A human-readable error message
+               err: String,
+               /// The feerate which was too high.
+               feerate: u64
+       },
 
        /// Invalid route or parameters (cltv_delta, fee, pubkey) was specified
-       RouteError {err: &'static str},
+       RouteError {
+               /// A human-readable error message
+               err: &'static str
+       },
 }
 
 impl fmt::Debug for APIError {
index 58eec665225659cdbb0cc2afebea8518dabfbbbf..a33644d06114967108aa61d10ad1984622e57315 100644 (file)
@@ -1,3 +1,16 @@
+//! Events are returned from various bits in the library which indicate some action must be taken
+//! by the client.
+//! Because we don't have a built-in runtime, its up to the client to call events at a time in the
+//! future, as well as generate and broadcast funding transactions handle payment preimages and a
+//! few other things.
+//!
+//! Note that many events are handled for you by PeerHandler, so in the common design of having a
+//! PeerManager which marshalls messages to ChannelManager and Router you only need to call
+//! process_events on the PeerHandler and then get_and_clear_pending_events and handle the events
+//! that bubble up to the surface. If, however, you do not have a PeerHandler managing a
+//! ChannelManager you need to handle all of the events which may be generated.
+//TODO: We need better separation of event types ^
+
 use ln::msgs;
 use chain::transaction::OutPoint;
 
@@ -7,6 +20,7 @@ use secp256k1::key::PublicKey;
 
 use std::time::Instant;
 
+/// An Event which you should probably take some action in response to.
 pub enum Event {
        // Events a user will probably have to handle
        /// Used to indicate that the client should generate a funding transaction with the given
@@ -137,6 +151,9 @@ pub enum Event {
        }
 }
 
+/// A trait indicating an object may generate events
 pub trait EventsProvider {
+       /// Gets the list of pending events which were generated by previous actions, clearing the list
+       /// in the process.
        fn get_and_clear_pending_events(&self) -> Vec<Event>;
 }
index 720bccf4140d8f7053c7e0e96b1015a2523716b2..b05ab10f3110b3446b4d8d0775b6f356d1314307 100644 (file)
@@ -7,9 +7,12 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-/// There is currently 2 ways to filter log messages. First one, by using compilation flag, e.g "max_level_off".
-/// The second one, client-side by implementing check against Record Level field, e.g TestLogger in test_utils.
-/// Each module may have its own Logger or share one.
+//! Log traits live here, which are called throughout the library to provide useful information for
+//! debugging purposes.
+//!
+//! There is currently 2 ways to filter log messages. First one, by using compilation features, e.g "max_level_off".
+//! The second one, client-side by implementing check against Record Level field.
+//! Each module may have its own Logger or share one.
 
 use std::cmp;
 use std::fmt;
index 2244f9b2fa44e1fb72c3fbf5c8feda1ce883dac0..b91b4f25d96fa116ea92b473e0b69c313b178919 100644 (file)
@@ -1,3 +1,5 @@
+//! Some utility modules live here. See individual sub-modules for more info.
+
 pub mod events;
 pub mod errors;
 pub mod ser;
index 18e558204963984ebef1f929883c1f7f852f14e3..8c713dfeebef297f6751d756e2966e83fa75b37f 100644 (file)
@@ -1,3 +1,6 @@
+//! A very simple serialization framework which is used to serialize/deserialize messages as well
+//! as ChannelsManagers and ChannelMonitors.
+
 use std::result::Result;
 use std::io::Read;
 use std::collections::HashMap;