X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fmsgs.rs;h=43005ad1d65370095f70e28823fc53ef2b95386f;hb=07db23d102738d1e84e3d2cb36101cef92e1761d;hp=ea1953eb83cffee3c5a74f48acccb99142289d2b;hpb=f8b06ec82c491efee2595bfcf95a68b027567d70;p=rust-lightning diff --git a/lightning/src/ln/msgs.rs b/lightning/src/ln/msgs.rs index ea1953eb..43005ad1 100644 --- a/lightning/src/ln/msgs.rs +++ b/lightning/src/ln/msgs.rs @@ -15,21 +15,25 @@ //! 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::Signature; -use secp256k1; -use bitcoin_hashes::sha256d::Hash as Sha256dHash; +use bitcoin::secp256k1::key::PublicKey; +use bitcoin::secp256k1::Signature; +use bitcoin::secp256k1; use bitcoin::blockdata::script::Script; +use bitcoin::hash_types::{Txid, BlockHash}; + +use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; -use std::error::Error; use std::{cmp, fmt}; use std::io::Read; use std::result::Result; use util::events; -use util::ser::{Readable, Writeable, Writer}; +use util::ser::{Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt}; + +use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret}; -use ln::channelmanager::{PaymentPreimage, PaymentHash}; +/// 21 million * 10^8 * 1000 +pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000; /// An error in decoding a message or struct. #[derive(Debug)] @@ -37,117 +41,26 @@ pub enum DecodeError { /// A version byte specified something we don't know how to handle. /// Includes unknown realm byte in an OnionHopData packet UnknownVersion, - /// Unknown feature mandating we fail to parse message + /// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type) UnknownRequiredFeature, /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0 - /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc + /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was + /// syntactically incorrect, etc InvalidValue, /// Buffer too short ShortRead, - /// node_announcement included more than one address of a given type! - ExtraAddressesPerType, /// A length descriptor in the packet didn't describe the later data correctly BadLengthDescriptor, /// Error from std::io Io(::std::io::Error), } -/// Tracks localfeatures which are only in init messages -#[derive(Clone, PartialEq)] -pub struct LocalFeatures { - flags: Vec, -} - -impl LocalFeatures { - /// Create a blank LocalFeatures flags (visibility extended for fuzz tests) - #[cfg(not(feature = "fuzztarget"))] - pub(crate) fn new() -> LocalFeatures { - LocalFeatures { - flags: vec![2 | 1 << 5], - } - } - #[cfg(feature = "fuzztarget")] - pub fn new() -> LocalFeatures { - LocalFeatures { - flags: vec![2 | 1 << 5], - } - } - - pub(crate) fn supports_data_loss_protect(&self) -> bool { - self.flags.len() > 0 && (self.flags[0] & 3) != 0 - } - pub(crate) fn initial_routing_sync(&self) -> bool { - self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0 - } - pub(crate) fn set_initial_routing_sync(&mut self) { - if self.flags.len() == 0 { - self.flags.resize(1, 1 << 3); - } else { - self.flags[0] |= 1 << 3; - } - } - - pub(crate) fn supports_upfront_shutdown_script(&self) -> bool { - self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0 - } - #[cfg(test)] - pub(crate) fn unset_upfront_shutdown_script(&mut self) { - self.flags[0] ^= 1 << 5; - } - - pub(crate) fn requires_unknown_bits(&self) -> bool { - self.flags.iter().enumerate().any(|(idx, &byte)| { - ( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 ) - }) - } - - pub(crate) fn supports_unknown_bits(&self) -> bool { - self.flags.iter().enumerate().any(|(idx, &byte)| { - ( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 ) - }) - } -} - -/// Tracks globalfeatures which are in init messages and routing announcements -#[derive(Clone, PartialEq, Debug)] -pub struct GlobalFeatures { - #[cfg(not(test))] - flags: Vec, - // Used to test encoding of diverse msgs - #[cfg(test)] - pub flags: Vec -} - -impl GlobalFeatures { - pub(crate) fn new() -> GlobalFeatures { - GlobalFeatures { - flags: Vec::new(), - } - } - - pub(crate) fn requires_unknown_bits(&self) -> bool { - for &byte in self.flags.iter() { - if (byte & 0x55) != 0 { - return true; - } - } - return false; - } - - pub(crate) fn supports_unknown_bits(&self) -> bool { - for &byte in self.flags.iter() { - if byte != 0 { - return true; - } - } - return false; - } -} - /// An init message to be sent or received from a peer pub struct Init { - pub(crate) global_features: GlobalFeatures, - pub(crate) local_features: LocalFeatures, + #[cfg(not(feature = "fuzztarget"))] + pub(crate) features: InitFeatures, + #[cfg(feature = "fuzztarget")] + pub features: InitFeatures, } /// An error message to be sent or received from a peer @@ -171,7 +84,7 @@ pub struct Pong { /// An open_channel message to be sent or received from a peer #[derive(Clone)] pub struct OpenChannel { - pub(crate) chain_hash: Sha256dHash, + pub(crate) chain_hash: BlockHash, pub(crate) temporary_channel_id: [u8; 32], pub(crate) funding_satoshis: u64, pub(crate) push_msat: u64, @@ -184,7 +97,7 @@ pub struct OpenChannel { pub(crate) max_accepted_htlcs: u16, pub(crate) funding_pubkey: PublicKey, pub(crate) revocation_basepoint: PublicKey, - pub(crate) payment_basepoint: PublicKey, + pub(crate) payment_point: PublicKey, pub(crate) delayed_payment_basepoint: PublicKey, pub(crate) htlc_basepoint: PublicKey, pub(crate) first_per_commitment_point: PublicKey, @@ -205,7 +118,7 @@ pub struct AcceptChannel { pub(crate) max_accepted_htlcs: u16, pub(crate) funding_pubkey: PublicKey, pub(crate) revocation_basepoint: PublicKey, - pub(crate) payment_basepoint: PublicKey, + pub(crate) payment_point: PublicKey, pub(crate) delayed_payment_basepoint: PublicKey, pub(crate) htlc_basepoint: PublicKey, pub(crate) first_per_commitment_point: PublicKey, @@ -216,7 +129,7 @@ pub struct AcceptChannel { #[derive(Clone)] pub struct FundingCreated { pub(crate) temporary_channel_id: [u8; 32], - pub(crate) funding_txid: Sha256dHash, + pub(crate) funding_txid: Txid, pub(crate) funding_output_index: u16, pub(crate) signature: Signature, } @@ -230,9 +143,10 @@ pub struct FundingSigned { /// A funding_locked message to be sent or received from a peer #[derive(Clone, PartialEq)] +#[allow(missing_docs)] pub struct FundingLocked { - pub(crate) channel_id: [u8; 32], - pub(crate) next_per_commitment_point: PublicKey, + pub channel_id: [u8; 32], + pub next_per_commitment_point: PublicKey, } /// A shutdown message to be sent or received from a peer @@ -390,6 +304,9 @@ impl NetAddress { &NetAddress::OnionV3 { .. } => { 37 }, } } + + /// The maximum length of any address descriptor, not including the 1-byte type + pub(crate) const MAX_LEN: u16 = 37; } impl Writeable for NetAddress { @@ -422,9 +339,9 @@ impl Writeable for NetAddress { } } -impl Readable for Result { - fn read(reader: &mut R) -> Result, DecodeError> { - let byte = >::read(reader)?; +impl Readable for Result { + fn read(reader: &mut R) -> Result, DecodeError> { + let byte = ::read(reader)?; match byte { 1 => { Ok(Ok(NetAddress::IPv4 { @@ -461,7 +378,7 @@ impl Readable for Result { /// The unsigned part of a node_announcement #[derive(PartialEq, Clone, Debug)] pub struct UnsignedNodeAnnouncement { - pub(crate) features: GlobalFeatures, + pub(crate) features: NodeFeatures, pub(crate) timestamp: u32, /// The node_id this announcement originated from (don't rebroadcast the node_announcement back /// to this node). @@ -485,8 +402,8 @@ pub struct NodeAnnouncement { /// The unsigned part of a channel_announcement #[derive(PartialEq, Clone, Debug)] pub struct UnsignedChannelAnnouncement { - pub(crate) features: GlobalFeatures, - pub(crate) chain_hash: Sha256dHash, + pub(crate) features: ChannelFeatures, + pub(crate) chain_hash: BlockHash, pub(crate) short_channel_id: u64, /// One of the two node_ids which are endpoints of this channel pub node_id_1: PublicKey, @@ -508,7 +425,7 @@ pub struct ChannelAnnouncement { #[derive(PartialEq, Clone, Debug)] pub(crate) struct UnsignedChannelUpdate { - pub(crate) chain_hash: Sha256dHash, + pub(crate) chain_hash: BlockHash, pub(crate) short_channel_id: u64, pub(crate) timestamp: u32, pub(crate) flags: u16, @@ -616,9 +533,9 @@ pub enum OptionalField { pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync { //Channel init: /// Handle an incoming open_channel message from the given peer. - fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &OpenChannel); + fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel); /// Handle an incoming accept_channel message from the given peer. - fn handle_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &AcceptChannel); + fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel); /// Handle an incoming funding_created message from the given peer. fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated); /// Handle an incoming funding_signed message from the given peer. @@ -661,7 +578,7 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn 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); + fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init); /// Handle an incoming channel_reestablish message from the given peer. fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish); @@ -685,30 +602,49 @@ pub trait RoutingMessageHandler : Send + Sync { fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate); /// Gets a subset of the channel announcements and updates required to dump our routing table /// to a remote node, starting at the short_channel_id indicated by starting_point and - /// including batch_amount entries. - fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>; + /// including the batch_amount entries immediately higher in numerical value than starting_point. + fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option, Option)>; /// Gets a subset of the node announcements required to dump our routing table to a remote node, - /// starting at the node *after* the provided publickey and including batch_amount entries. + /// starting at the node *after* the provided publickey and including batch_amount entries + /// immediately higher (as defined by ::cmp) than starting_point. /// If None is provided for starting_point, we start at the first node. fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec; -} - -pub(crate) struct OnionRealm0HopData { - pub(crate) short_channel_id: u64, - pub(crate) amt_to_forward: u64, - pub(crate) outgoing_cltv_value: u32, - // 12 bytes of 0-padding + /// Returns whether a full sync should be requested from a peer. + fn should_request_full_sync(&self, node_id: &PublicKey) -> bool; } mod fuzzy_internal_msgs { + use ln::channelmanager::PaymentSecret; + // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize // them from untrusted input): + #[derive(Clone)] + pub(crate) struct FinalOnionHopData { + pub(crate) payment_secret: PaymentSecret, + /// The total value, in msat, of the payment as received by the ultimate recipient. + /// Message serialization may panic if this value is more than 21 million Bitcoin. + pub(crate) total_msat: u64, + } + + pub(crate) enum OnionHopDataFormat { + Legacy { // aka Realm-0 + short_channel_id: u64, + }, + NonFinalNode { + short_channel_id: u64, + }, + FinalNode { + payment_data: Option, + }, + } - use super::OnionRealm0HopData; pub struct OnionHopData { - pub(crate) realm: u8, - pub(crate) data: OnionRealm0HopData, - pub(crate) hmac: [u8; 32], + pub(crate) format: OnionHopDataFormat, + /// The value, in msat, of the payment after this hop's fee is deducted. + /// Message serialization may panic if this value is more than 21 million Bitcoin. + pub(crate) amt_to_forward: u64, + pub(crate) outgoing_cltv_value: u32, + // 12 bytes of 0-padding for Legacy format } pub struct DecodedOnionErrorPacket { @@ -751,22 +687,16 @@ pub(crate) struct OnionErrorPacket { pub(crate) data: Vec, } -impl Error for DecodeError { - fn description(&self) -> &str { - match *self { - DecodeError::UnknownVersion => "Unknown realm byte in Onion packet", - DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode", - DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as", - DecodeError::ShortRead => "Packet extended beyond the provided bytes", - DecodeError::ExtraAddressesPerType => "More than one address of a single type", - DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly", - DecodeError::Io(ref e) => e.description(), - } - } -} impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(self.description()) + match *self { + DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"), + DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"), + DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"), + DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"), + DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"), + DecodeError::Io(ref e) => e.fmt(f), + } } } @@ -799,9 +729,9 @@ impl Writeable for OptionalField