Make field error of LightingError mandatory
[rust-lightning] / src / ln / msgs.rs
index f87e3722f999d239934241e8aa5ee046872d8fd8..277d96d168733e890be98391b6017aa7df138b50 100644 (file)
@@ -1,12 +1,14 @@
 //! 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
+//! source node_id of the message, 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
@@ -14,9 +16,9 @@
 //! track the network on the less-secure system.
 
 use secp256k1::key::PublicKey;
-use secp256k1::{Secp256k1, Signature};
+use secp256k1::Signature;
 use secp256k1;
-use bitcoin::util::hash::Sha256dHash;
+use bitcoin_hashes::sha256d::Hash as Sha256dHash;
 use bitcoin::blockdata::script::Script;
 
 use std::error::Error;
@@ -24,9 +26,11 @@ use std::{cmp, fmt};
 use std::io::Read;
 use std::result::Result;
 
-use util::{byte_utils, events};
+use util::events;
 use util::ser::{Readable, Writeable, Writer};
 
+use ln::channelmanager::{PaymentPreimage, PaymentHash};
+
 /// An error in decoding a message or struct.
 #[derive(Debug)]
 pub enum DecodeError {
@@ -43,7 +47,6 @@ pub enum DecodeError {
        /// 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
-       /// (currently only generated in node_announcement)
        BadLengthDescriptor,
        /// Error from std::io
        Io(::std::io::Error),
@@ -56,19 +59,23 @@ pub struct LocalFeatures {
 }
 
 impl LocalFeatures {
+       /// Create a blank LocalFeatures flags (visibility extended for fuzz tests)
+       #[cfg(not(feature = "fuzztarget"))]
        pub(crate) fn new() -> LocalFeatures {
                LocalFeatures {
-                       flags: Vec::new(),
+                       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 requires_data_loss_protect(&self) -> bool {
-               self.flags.len() > 0 && (self.flags[0] & 1) != 0
-       }
-
        pub(crate) fn initial_routing_sync(&self) -> bool {
                self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
        }
@@ -83,37 +90,32 @@ impl LocalFeatures {
        pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
                self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
        }
-       pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
-               self.flags.len() > 0 && (self.flags[0] & (1 << 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 {
-               for (idx, &byte) in self.flags.iter().enumerate() {
-                       if idx != 0 && (byte & 0x55) != 0 {
-                               return true;
-                       } else if idx == 0 && (byte & 0x14) != 0 {
-                               return true;
-                       }
-               }
-               return false;
+               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 {
-               for (idx, &byte) in self.flags.iter().enumerate() {
-                       if idx != 0 && byte != 0 {
-                               return true;
-                       } else if idx == 0 && (byte & 0xc4) != 0 {
-                               return true;
-                       }
-               }
-               return false;
+               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)]
+#[derive(Clone, PartialEq, Debug)]
 pub struct GlobalFeatures {
+       #[cfg(not(test))]
        flags: Vec<u8>,
+       // Used to test encoding of diverse msgs
+       #[cfg(test)]
+       pub flags: Vec<u8>
 }
 
 impl GlobalFeatures {
@@ -149,6 +151,7 @@ pub struct Init {
 }
 
 /// An error message to be sent or received from a peer
+#[derive(Clone)]
 pub struct ErrorMessage {
        pub(crate) channel_id: [u8; 32],
        pub(crate) data: String,
@@ -166,6 +169,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) temporary_channel_id: [u8; 32],
@@ -185,10 +189,11 @@ pub struct OpenChannel {
        pub(crate) htlc_basepoint: PublicKey,
        pub(crate) first_per_commitment_point: PublicKey,
        pub(crate) channel_flags: u8,
-       pub(crate) shutdown_scriptpubkey: Option<Script>,
+       pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
 }
 
 /// An accept_channel message to be sent or received from a peer
+#[derive(Clone)]
 pub struct AcceptChannel {
        pub(crate) temporary_channel_id: [u8; 32],
        pub(crate) dust_limit_satoshis: u64,
@@ -204,10 +209,11 @@ pub struct AcceptChannel {
        pub(crate) delayed_payment_basepoint: PublicKey,
        pub(crate) htlc_basepoint: PublicKey,
        pub(crate) first_per_commitment_point: PublicKey,
-       pub(crate) shutdown_scriptpubkey: Option<Script>,
+       pub(crate) shutdown_scriptpubkey: OptionalField<Script>
 }
 
 /// A funding_created message to be sent or received from a peer
+#[derive(Clone)]
 pub struct FundingCreated {
        pub(crate) temporary_channel_id: [u8; 32],
        pub(crate) funding_txid: Sha256dHash,
@@ -216,24 +222,28 @@ pub struct FundingCreated {
 }
 
 /// A funding_signed message to be sent or received from a peer
+#[derive(Clone)]
 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
+#[derive(Clone, PartialEq)]
 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
+#[derive(Clone, PartialEq)]
 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
+#[derive(Clone, PartialEq)]
 pub struct ClosingSigned {
        pub(crate) channel_id: [u8; 32],
        pub(crate) fee_satoshis: u64,
@@ -241,26 +251,26 @@ pub struct ClosingSigned {
 }
 
 /// An update_add_htlc message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, PartialEq)]
 pub struct UpdateAddHTLC {
        pub(crate) channel_id: [u8; 32],
        pub(crate) htlc_id: u64,
        pub(crate) amount_msat: u64,
-       pub(crate) payment_hash: [u8; 32],
+       pub(crate) payment_hash: PaymentHash,
        pub(crate) cltv_expiry: u32,
        pub(crate) onion_routing_packet: OnionPacket,
 }
 
 /// An update_fulfill_htlc message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, PartialEq)]
 pub struct UpdateFulfillHTLC {
        pub(crate) channel_id: [u8; 32],
        pub(crate) htlc_id: u64,
-       pub(crate) payment_preimage: [u8; 32],
+       pub(crate) payment_preimage: PaymentPreimage,
 }
 
 /// An update_fail_htlc message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, PartialEq)]
 pub struct UpdateFailHTLC {
        pub(crate) channel_id: [u8; 32],
        pub(crate) htlc_id: u64,
@@ -268,7 +278,7 @@ pub struct UpdateFailHTLC {
 }
 
 /// An update_fail_malformed_htlc message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, PartialEq)]
 pub struct UpdateFailMalformedHTLC {
        pub(crate) channel_id: [u8; 32],
        pub(crate) htlc_id: u64,
@@ -277,7 +287,7 @@ pub struct UpdateFailMalformedHTLC {
 }
 
 /// A commitment_signed message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(Clone, PartialEq)]
 pub struct CommitmentSigned {
        pub(crate) channel_id: [u8; 32],
        pub(crate) signature: Signature,
@@ -285,6 +295,7 @@ pub struct CommitmentSigned {
 }
 
 /// A revoke_and_ack message to be sent or received from a peer
+#[derive(Clone, PartialEq)]
 pub struct RevokeAndACK {
        pub(crate) channel_id: [u8; 32],
        pub(crate) per_commitment_secret: [u8; 32],
@@ -292,26 +303,29 @@ pub struct RevokeAndACK {
 }
 
 /// An update_fee message to be sent or received from a peer
+#[derive(PartialEq, Clone)]
 pub struct UpdateFee {
        pub(crate) channel_id: [u8; 32],
        pub(crate) feerate_per_kw: u32,
 }
 
+#[derive(PartialEq, Clone)]
 pub(crate) struct DataLossProtect {
        pub(crate) your_last_per_commitment_secret: [u8; 32],
        pub(crate) my_current_per_commitment_point: PublicKey,
 }
 
 /// A channel_reestablish message to be sent or received from a peer
+#[derive(PartialEq, Clone)]
 pub struct ChannelReestablish {
        pub(crate) channel_id: [u8; 32],
        pub(crate) next_local_commitment_number: u64,
        pub(crate) next_remote_commitment_number: u64,
-       pub(crate) data_loss_protect: Option<DataLossProtect>,
+       pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
 }
 
 /// An announcement_signatures message to be sent or received from a peer
-#[derive(Clone)]
+#[derive(PartialEq, Clone, Debug)]
 pub struct AnnouncementSignatures {
        pub(crate) channel_id: [u8; 32],
        pub(crate) short_channel_id: u64,
@@ -320,27 +334,27 @@ pub struct AnnouncementSignatures {
 }
 
 /// An address which can be used to connect to a remote peer
-#[derive(Clone)]
+#[derive(Clone, PartialEq, Debug)]
 pub enum NetAddress {
-       /// An IPv4 address/port on which the peer is listenting.
+       /// An IPv4 address/port on which the peer is listening.
        IPv4 {
                /// The 4-byte IPv4 address
                addr: [u8; 4],
-               /// The port on which the node is listenting
+               /// The port on which the node is listening
                port: u16,
        },
-       /// An IPv6 address/port on which the peer is listenting.
+       /// An IPv6 address/port on which the peer is listening.
        IPv6 {
                /// The 16-byte IPv6 address
                addr: [u8; 16],
-               /// The port on which the node is listenting
+               /// The port on which the node is listening
                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
+               /// The port on which the node is listening
                port: u16,
        },
        /// A new-style Tor onion address/port on which the peer is listening.
@@ -353,7 +367,7 @@ pub enum NetAddress {
                checksum: u16,
                /// The version byte, as defined by the Tor Onion v3 spec.
                version: u8,
-               /// The port on which the node is listenting
+               /// The port on which the node is listening
                port: u16,
        },
 }
@@ -366,10 +380,86 @@ impl NetAddress {
                        &NetAddress::OnionV3 {..} => { 4 },
                }
        }
+
+       /// Strict byte-length of address descriptor, 1-byte type not recorded
+       fn len(&self) -> u16 {
+               match self {
+                       &NetAddress::IPv4 { .. } => { 6 },
+                       &NetAddress::IPv6 { .. } => { 18 },
+                       &NetAddress::OnionV2 { .. } => { 12 },
+                       &NetAddress::OnionV3 { .. } => { 37 },
+               }
+       }
+}
+
+impl Writeable for NetAddress {
+       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+               match self {
+                       &NetAddress::IPv4 { ref addr, ref port } => {
+                               1u8.write(writer)?;
+                               addr.write(writer)?;
+                               port.write(writer)?;
+                       },
+                       &NetAddress::IPv6 { ref addr, ref port } => {
+                               2u8.write(writer)?;
+                               addr.write(writer)?;
+                               port.write(writer)?;
+                       },
+                       &NetAddress::OnionV2 { ref addr, ref port } => {
+                               3u8.write(writer)?;
+                               addr.write(writer)?;
+                               port.write(writer)?;
+                       },
+                       &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
+                               4u8.write(writer)?;
+                               ed25519_pubkey.write(writer)?;
+                               checksum.write(writer)?;
+                               version.write(writer)?;
+                               port.write(writer)?;
+                       }
+               }
+               Ok(())
+       }
+}
+
+impl<R: ::std::io::Read>  Readable<R> for Result<NetAddress, u8> {
+       fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
+               let byte = <u8 as Readable<R>>::read(reader)?;
+               match byte {
+                       1 => {
+                               Ok(Ok(NetAddress::IPv4 {
+                                       addr: Readable::read(reader)?,
+                                       port: Readable::read(reader)?,
+                               }))
+                       },
+                       2 => {
+                               Ok(Ok(NetAddress::IPv6 {
+                                       addr: Readable::read(reader)?,
+                                       port: Readable::read(reader)?,
+                               }))
+                       },
+                       3 => {
+                               Ok(Ok(NetAddress::OnionV2 {
+                                       addr: Readable::read(reader)?,
+                                       port: Readable::read(reader)?,
+                               }))
+                       },
+                       4 => {
+                               Ok(Ok(NetAddress::OnionV3 {
+                                       ed25519_pubkey: Readable::read(reader)?,
+                                       checksum: Readable::read(reader)?,
+                                       version: Readable::read(reader)?,
+                                       port: Readable::read(reader)?,
+                               }))
+                       },
+                       _ => return Ok(Err(byte)),
+               }
+       }
 }
 
 // Only exposed as broadcast of node_announcement should be filtered by node_id
 /// The unsigned part of a node_announcement
+#[derive(PartialEq, Clone, Debug)]
 pub struct UnsignedNodeAnnouncement {
        pub(crate) features: GlobalFeatures,
        pub(crate) timestamp: u32,
@@ -384,6 +474,7 @@ pub struct UnsignedNodeAnnouncement {
        pub(crate) excess_address_data: Vec<u8>,
        pub(crate) excess_data: Vec<u8>,
 }
+#[derive(PartialEq, Clone)]
 /// A node_announcement message to be sent or received from a peer
 pub struct NodeAnnouncement {
        pub(crate) signature: Signature,
@@ -392,7 +483,7 @@ pub struct NodeAnnouncement {
 
 // Only exposed as broadcast of channel_announcement should be filtered by node_id
 /// The unsigned part of a channel_announcement
-#[derive(PartialEq, Clone)]
+#[derive(PartialEq, Clone, Debug)]
 pub struct UnsignedChannelAnnouncement {
        pub(crate) features: GlobalFeatures,
        pub(crate) chain_hash: Sha256dHash,
@@ -406,7 +497,7 @@ pub struct UnsignedChannelAnnouncement {
        pub(crate) excess_data: Vec<u8>,
 }
 /// A channel_announcement message to be sent or received from a peer
-#[derive(PartialEq, Clone)]
+#[derive(PartialEq, Clone, Debug)]
 pub struct ChannelAnnouncement {
        pub(crate) node_signature_1: Signature,
        pub(crate) node_signature_2: Signature,
@@ -415,7 +506,7 @@ pub struct ChannelAnnouncement {
        pub(crate) contents: UnsignedChannelAnnouncement,
 }
 
-#[derive(PartialEq, Clone)]
+#[derive(PartialEq, Clone, Debug)]
 pub(crate) struct UnsignedChannelUpdate {
        pub(crate) chain_hash: Sha256dHash,
        pub(crate) short_channel_id: u64,
@@ -428,13 +519,14 @@ pub(crate) struct UnsignedChannelUpdate {
        pub(crate) excess_data: Vec<u8>,
 }
 /// A channel_update message to be sent or received from a peer
-#[derive(PartialEq, Clone)]
+#[derive(PartialEq, Clone, Debug)]
 pub struct ChannelUpdate {
        pub(crate) signature: Signature,
        pub(crate) contents: UnsignedChannelUpdate,
 }
 
-/// Used to put an error message in a HandleError
+/// Used to put an error message in a LightningError
+#[derive(Clone)]
 pub enum ErrorAction {
        /// The peer took some action which made us think they were useless. Disconnect them.
        DisconnectPeer {
@@ -451,26 +543,35 @@ pub enum ErrorAction {
 }
 
 /// An Err type for failure to process messages.
-pub struct HandleError { //TODO: rename me
+pub struct LightningError {
        /// 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
+       pub action: ErrorAction,
 }
 
 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
 /// transaction updates if they were pending.
+#[derive(PartialEq, Clone)]
 pub struct CommitmentUpdate {
-       pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
-       pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
-       pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
-       pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
-       pub(crate) commitment_signed: CommitmentSigned,
+       /// update_add_htlc messages which should be sent
+       pub update_add_htlcs: Vec<UpdateAddHTLC>,
+       /// update_fulfill_htlc messages which should be sent
+       pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
+       /// update_fail_htlc messages which should be sent
+       pub update_fail_htlcs: Vec<UpdateFailHTLC>,
+       /// update_fail_malformed_htlc messages which should be sent
+       pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
+       /// An update_fee message which should be sent
+       pub update_fee: Option<UpdateFee>,
+       /// Finally, the commitment_signed message which should be sent
+       pub 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.
+#[derive(Clone)]
 pub enum HTLCFailChannelUpdate {
        /// We received an error which included a full ChannelUpdate message.
        ChannelUpdateMessage {
@@ -481,51 +582,76 @@ pub enum HTLCFailChannelUpdate {
        ChannelClosed {
                /// The short_channel_id which has now closed.
                short_channel_id: u64,
+               /// when this true, this channel should be permanently removed from the
+               /// consideration. Otherwise, this channel can be restored as new channel_update is received
+               is_permanent: bool,
        },
+       /// We received an error which indicated only that a node has failed
+       NodeFailure {
+               /// The node_id that has failed.
+               node_id: PublicKey,
+               /// when this true, node should be permanently removed from the
+               /// consideration. Otherwise, the channels connected to this node can be
+               /// restored as new channel_update is received
+               is_permanent: bool,
+       }
 }
 
-/// A trait to describe an object which can receive channel messages. Messages MAY be called in
-/// 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 {
+/// Messages could have optional fields to use with extended features
+/// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
+/// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
+/// separate enum type for them.
+#[derive(Clone, PartialEq)]
+pub enum OptionalField<T> {
+       /// Optional field is included in message
+       Present(T),
+       /// Optional field is absent in message
+       Absent
+}
+
+/// A trait to describe an object which can receive channel messages.
+///
+/// Messages MAY be called in 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::MessageSendEventsProvider + 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>;
+       fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &OpenChannel) -> Result<(), LightningError>;
        /// Handle an incoming accept_channel message from the given peer.
-       fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
+       fn handle_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &AcceptChannel) -> Result<(), LightningError>;
        /// Handle an incoming funding_created message from the given peer.
-       fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
+       fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), LightningError>;
        /// Handle an incoming funding_signed message from the given peer.
-       fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
+       fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), LightningError>;
 
        // 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>;
+       fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), LightningError>;
 
        // 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>;
+       fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), LightningError>;
        /// 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>;
+       fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), LightningError>;
 
        /// Handle an incoming update_fee message from the given peer.
-       fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
+       fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), LightningError>;
 
        // 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>;
+       fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), LightningError>;
 
        // Connection loss/reestablish:
        /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
@@ -535,9 +661,9 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
        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>;
+       fn peer_connected(&self, their_node_id: &PublicKey);
        /// 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>;
+       fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), LightningError>;
 
        // Error:
        /// Handle an incoming error message from the given peer.
@@ -548,15 +674,23 @@ pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
 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>;
+       fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
        /// 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>;
+       fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
        /// 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>;
+       fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
        /// 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);
+       /// 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)>;
+       /// 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.
+       /// 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<NodeAnnouncement>;
 }
 
 pub(crate) struct OnionRealm0HopData {
@@ -576,7 +710,6 @@ mod fuzzy_internal_msgs {
                pub(crate) data: OnionRealm0HopData,
                pub(crate) hmac: [u8; 32],
        }
-       unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
 
        pub struct DecodedOnionErrorPacket {
                pub(crate) hmac: [u8; 32],
@@ -600,7 +733,18 @@ pub(crate) struct OnionPacket {
        pub(crate) hmac: [u8; 32],
 }
 
-#[derive(Clone)]
+impl PartialEq for OnionPacket {
+       fn eq(&self, other: &OnionPacket) -> bool {
+               for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
+                       if i != j { return false; }
+               }
+               self.version == other.version &&
+                       self.public_key == other.public_key &&
+                       self.hmac == other.hmac
+       }
+}
+
+#[derive(Clone, PartialEq)]
 pub(crate) struct OnionErrorPacket {
        // This really should be a constant size slice, but the spec lets these things be up to 128KB?
        // (TODO) We limit it in decode to much lower...
@@ -626,7 +770,7 @@ impl fmt::Display for DecodeError {
        }
 }
 
-impl fmt::Debug for HandleError {
+impl fmt::Debug for LightningError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str(self.err)
        }
@@ -642,8 +786,35 @@ impl From<::std::io::Error> for DecodeError {
        }
 }
 
+impl Writeable for OptionalField<Script> {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
+               match *self {
+                       OptionalField::Present(ref script) => {
+                               // Note that Writeable for script includes the 16-bit length tag for us
+                               script.write(w)?;
+                       },
+                       OptionalField::Absent => {}
+               }
+               Ok(())
+       }
+}
+
+impl<R: Read> Readable<R> for OptionalField<Script> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
+               match <u16 as Readable<R>>::read(r) {
+                       Ok(len) => {
+                               let mut buf = vec![0; len as usize];
+                               r.read_exact(&mut buf)?;
+                               Ok(OptionalField::Present(Script::from(buf)))
+                       },
+                       Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
+                       Err(e) => Err(e)
+               }
+       }
+}
+
 impl_writeable_len_match!(AcceptChannel, {
-               {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
+               {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
                {_, 270}
        }, {
        temporary_channel_id,
@@ -672,13 +843,16 @@ impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
 
 impl Writeable for ChannelReestablish {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
-               w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
+               w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
                self.channel_id.write(w)?;
                self.next_local_commitment_number.write(w)?;
                self.next_remote_commitment_number.write(w)?;
-               if let Some(ref data_loss_protect) = self.data_loss_protect {
-                       data_loss_protect.your_last_per_commitment_secret.write(w)?;
-                       data_loss_protect.my_current_per_commitment_point.write(w)?;
+               match self.data_loss_protect {
+                       OptionalField::Present(ref data_loss_protect) => {
+                               (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
+                               (*data_loss_protect).my_current_per_commitment_point.write(w)?;
+                       },
+                       OptionalField::Absent => {}
                }
                Ok(())
        }
@@ -693,11 +867,11 @@ impl<R: Read> Readable<R> for ChannelReestablish{
                        data_loss_protect: {
                                match <[u8; 32] as Readable<R>>::read(r) {
                                        Ok(your_last_per_commitment_secret) =>
-                                               Some(DataLossProtect {
+                                               OptionalField::Present(DataLossProtect {
                                                        your_last_per_commitment_secret,
                                                        my_current_per_commitment_point: Readable::read(r)?,
                                                }),
-                                       Err(DecodeError::ShortRead) => None,
+                                       Err(DecodeError::ShortRead) => OptionalField::Absent,
                                        Err(e) => return Err(e)
                                }
                        }
@@ -764,8 +938,8 @@ impl_writeable_len_match!(Init, {
 });
 
 impl_writeable_len_match!(OpenChannel, {
-               { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
-               { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
+               { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
+               { _, 319 }
        }, {
        chain_hash,
        temporary_channel_id,
@@ -854,7 +1028,7 @@ impl<R: Read> Readable<R> for OnionPacket {
                        public_key: {
                                let mut buf = [0u8;33];
                                r.read_exact(&mut buf)?;
-                               PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
+                               PublicKey::from_slice(&buf)
                        },
                        hop_data: Readable::read(r)?,
                        hmac: Readable::read(r)?,
@@ -1096,38 +1270,17 @@ impl Writeable for UnsignedNodeAnnouncement {
                w.write_all(&self.rgb)?;
                self.alias.write(w)?;
 
-               let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
                let mut addrs_to_encode = self.addresses.clone();
                addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
                addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
-               for addr in addrs_to_encode.iter() {
-                       match addr {
-                               &NetAddress::IPv4{addr, port} => {
-                                       addr_slice.push(1);
-                                       addr_slice.extend_from_slice(&addr);
-                                       addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
-                               },
-                               &NetAddress::IPv6{addr, port} => {
-                                       addr_slice.push(2);
-                                       addr_slice.extend_from_slice(&addr);
-                                       addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
-                               },
-                               &NetAddress::OnionV2{addr, port} => {
-                                       addr_slice.push(3);
-                                       addr_slice.extend_from_slice(&addr);
-                                       addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
-                               },
-                               &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
-                                       addr_slice.push(4);
-                                       addr_slice.extend_from_slice(&ed25519_pubkey);
-                                       addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
-                                       addr_slice.push(version);
-                                       addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
-                               },
-                       }
+               let mut addr_len = 0;
+               for addr in &addrs_to_encode {
+                       addr_len += 1 + addr.len();
+               }
+               (addr_len + self.excess_address_data.len() as u16).write(w)?;
+               for addr in addrs_to_encode {
+                       addr.write(w)?;
                }
-               ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
-               w.write_all(&addr_slice[..])?;
                w.write_all(&self.excess_address_data[..])?;
                w.write_all(&self.excess_data[..])?;
                Ok(())
@@ -1146,112 +1299,77 @@ impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
                r.read_exact(&mut rgb)?;
                let alias: [u8; 32] = Readable::read(r)?;
 
-               let addrlen: u16 = Readable::read(r)?;
+               let addr_len: u16 = Readable::read(r)?;
+               let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
                let mut addr_readpos = 0;
-               let mut addresses = Vec::with_capacity(4);
-               let mut f: u8 = 0;
-               let mut excess = 0;
+               let mut excess = false;
+               let mut excess_byte = 0;
                loop {
-                       if addrlen <= addr_readpos { break; }
-                       f = Readable::read(r)?;
-                       match f {
-                               1 => {
-                                       if addresses.len() > 0 {
-                                               return Err(DecodeError::ExtraAddressesPerType);
-                                       }
-                                       if addrlen < addr_readpos + 1 + 6 {
-                                               return Err(DecodeError::BadLengthDescriptor);
-                                       }
-                                       addresses.push(NetAddress::IPv4 {
-                                               addr: {
-                                                       let mut addr = [0; 4];
-                                                       r.read_exact(&mut addr)?;
-                                                       addr
+                       if addr_len <= addr_readpos { break; }
+                       match Readable::read(r) {
+                               Ok(Ok(addr)) => {
+                                       match addr {
+                                               NetAddress::IPv4 { .. } => {
+                                                       if addresses.len() > 0 {
+                                                               return Err(DecodeError::ExtraAddressesPerType);
+                                                       }
                                                },
-                                               port: Readable::read(r)?,
-                                       });
-                                       addr_readpos += 1 + 6
-                               },
-                               2 => {
-                                       if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
-                                               return Err(DecodeError::ExtraAddressesPerType);
-                                       }
-                                       if addrlen < addr_readpos + 1 + 18 {
-                                               return Err(DecodeError::BadLengthDescriptor);
-                                       }
-                                       addresses.push(NetAddress::IPv6 {
-                                               addr: {
-                                                       let mut addr = [0; 16];
-                                                       r.read_exact(&mut addr)?;
-                                                       addr
+                                               NetAddress::IPv6 { .. } => {
+                                                       if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
+                                                               return Err(DecodeError::ExtraAddressesPerType);
+                                                       }
                                                },
-                                               port: Readable::read(r)?,
-                                       });
-                                       addr_readpos += 1 + 18
-                               },
-                               3 => {
-                                       if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
-                                               return Err(DecodeError::ExtraAddressesPerType);
-                                       }
-                                       if addrlen < addr_readpos + 1 + 12 {
-                                               return Err(DecodeError::BadLengthDescriptor);
-                                       }
-                                       addresses.push(NetAddress::OnionV2 {
-                                               addr: {
-                                                       let mut addr = [0; 10];
-                                                       r.read_exact(&mut addr)?;
-                                                       addr
+                                               NetAddress::OnionV2 { .. } => {
+                                                       if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
+                                                               return Err(DecodeError::ExtraAddressesPerType);
+                                                       }
+                                               },
+                                               NetAddress::OnionV3 { .. } => {
+                                                       if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
+                                                               return Err(DecodeError::ExtraAddressesPerType);
+                                                       }
                                                },
-                                               port: Readable::read(r)?,
-                                       });
-                                       addr_readpos += 1 + 12
-                               },
-                               4 => {
-                                       if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
-                                               return Err(DecodeError::ExtraAddressesPerType);
                                        }
-                                       if addrlen < addr_readpos + 1 + 37 {
+                                       if addr_len < addr_readpos + 1 + addr.len() {
                                                return Err(DecodeError::BadLengthDescriptor);
                                        }
-                                       addresses.push(NetAddress::OnionV3 {
-                                               ed25519_pubkey: Readable::read(r)?,
-                                               checksum: Readable::read(r)?,
-                                               version: Readable::read(r)?,
-                                               port: Readable::read(r)?,
-                                       });
-                                       addr_readpos += 1 + 37
+                                       addr_readpos += (1 + addr.len()) as u16;
+                                       addresses.push(addr);
                                },
-                               _ => { excess = 1; break; }
+                               Ok(Err(unknown_descriptor)) => {
+                                       excess = true;
+                                       excess_byte = unknown_descriptor;
+                                       break;
+                               },
+                               Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
+                               Err(e) => return Err(e),
                        }
                }
 
                let mut excess_data = vec![];
-               let excess_address_data = if addr_readpos < addrlen {
-                       let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
-                       r.read_exact(&mut excess_address_data[excess..])?;
-                       if excess == 1 {
-                               excess_address_data[0] = f;
+               let excess_address_data = if addr_readpos < addr_len {
+                       let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
+                       r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
+                       if excess {
+                               excess_address_data[0] = excess_byte;
                        }
                        excess_address_data
                } else {
-                       if excess == 1 {
-                               excess_data.push(f);
+                       if excess {
+                               excess_data.push(excess_byte);
                        }
                        Vec::new()
                };
-
+               r.read_to_end(&mut excess_data)?;
                Ok(UnsignedNodeAnnouncement {
-                       features: features,
-                       timestamp: timestamp,
-                       node_id: node_id,
-                       rgb: rgb,
-                       alias: alias,
-                       addresses: addresses,
-                       excess_address_data: excess_address_data,
-                       excess_data: {
-                               r.read_to_end(&mut excess_data)?;
-                               excess_data
-                       },
+                       features,
+                       timestamp,
+                       node_id,
+                       rgb,
+                       alias,
+                       addresses,
+                       excess_address_data,
+                       excess_data,
                })
        }
 }
@@ -1268,9 +1386,19 @@ impl_writeable_len_match!(NodeAnnouncement, {
 mod tests {
        use hex;
        use ln::msgs;
+       use ln::msgs::{GlobalFeatures, LocalFeatures, OptionalField, OnionErrorPacket};
+       use ln::channelmanager::{PaymentPreimage, PaymentHash};
        use util::ser::Writeable;
+
+       use bitcoin_hashes::sha256d::Hash as Sha256dHash;
+       use bitcoin_hashes::hex::FromHex;
+       use bitcoin::util::address::Address;
+       use bitcoin::network::constants::Network;
+       use bitcoin::blockdata::script::Builder;
+       use bitcoin::blockdata::opcodes;
+
        use secp256k1::key::{PublicKey,SecretKey};
-       use secp256k1::Secp256k1;
+       use secp256k1::{Secp256k1, Message};
 
        #[test]
        fn encoding_channel_reestablish_no_secret() {
@@ -1278,7 +1406,7 @@ mod tests {
                        channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
                        next_local_commitment_number: 3,
                        next_remote_commitment_number: 4,
-                       data_loss_protect: None,
+                       data_loss_protect: OptionalField::Absent,
                };
 
                let encoded_value = cr.encode();
@@ -1292,14 +1420,14 @@ mod tests {
        fn encoding_channel_reestablish_with_secret() {
                let public_key = {
                        let secp_ctx = Secp256k1::new();
-                       PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
+                       PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
                };
 
                let cr = msgs::ChannelReestablish {
                        channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
                        next_local_commitment_number: 3,
                        next_remote_commitment_number: 4,
-                       data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
+                       data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
                };
 
                let encoded_value = cr.encode();
@@ -1308,4 +1436,628 @@ mod tests {
                        vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143]
                );
        }
+
+       macro_rules! get_keys_from {
+               ($slice: expr, $secp_ctx: expr) => {
+                       {
+                               let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
+                               let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
+                               (privkey, pubkey)
+                       }
+               }
+       }
+
+       macro_rules! get_sig_on {
+               ($privkey: expr, $ctx: expr, $string: expr) => {
+                       {
+                               let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
+                               $ctx.sign(&sighash, &$privkey)
+                       }
+               }
+       }
+
+       #[test]
+       fn encoding_announcement_signatures() {
+               let secp_ctx = Secp256k1::new();
+               let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
+               let announcement_signatures = msgs::AnnouncementSignatures {
+                       channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
+                       short_channel_id: 2316138423780173,
+                       node_signature: sig_1,
+                       bitcoin_signature: sig_2,
+               };
+
+               let encoded_value = announcement_signatures.encode();
+               assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
+       }
+
+       fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
+               let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
+               let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
+               let mut features = GlobalFeatures::new();
+               if unknown_features_bits {
+                       features.flags = vec![0xFF, 0xFF];
+               }
+               let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
+                       features,
+                       chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
+                       short_channel_id: 2316138423780173,
+                       node_id_1: pubkey_1,
+                       node_id_2: pubkey_2,
+                       bitcoin_key_1: pubkey_3,
+                       bitcoin_key_2: pubkey_4,
+                       excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
+               };
+               let channel_announcement = msgs::ChannelAnnouncement {
+                       node_signature_1: sig_1,
+                       node_signature_2: sig_2,
+                       bitcoin_signature_1: sig_3,
+                       bitcoin_signature_2: sig_4,
+                       contents: unsigned_channel_announcement,
+               };
+               let encoded_value = channel_announcement.encode();
+               let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
+               if unknown_features_bits {
+                       target_value.append(&mut hex::decode("0002ffff").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("0000").unwrap());
+               }
+               if non_bitcoin_chain_hash {
+                       target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
+               }
+               target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
+               if excess_data {
+                       target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_channel_announcement() {
+               do_encoding_channel_announcement(false, false, false);
+               do_encoding_channel_announcement(true, false, false);
+               do_encoding_channel_announcement(true, true, false);
+               do_encoding_channel_announcement(true, true, true);
+               do_encoding_channel_announcement(false, true, true);
+               do_encoding_channel_announcement(false, false, true);
+               do_encoding_channel_announcement(false, true, false);
+               do_encoding_channel_announcement(true, false, true);
+       }
+
+       fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let mut features = GlobalFeatures::new();
+               if unknown_features_bits {
+                       features.flags = vec![0xFF, 0xFF];
+               }
+               let mut addresses = Vec::new();
+               if ipv4 {
+                       addresses.push(msgs::NetAddress::IPv4 {
+                               addr: [255, 254, 253, 252],
+                               port: 9735
+                       });
+               }
+               if ipv6 {
+                       addresses.push(msgs::NetAddress::IPv6 {
+                               addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
+                               port: 9735
+                       });
+               }
+               if onionv2 {
+                       addresses.push(msgs::NetAddress::OnionV2 {
+                               addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
+                               port: 9735
+                       });
+               }
+               if onionv3 {
+                       addresses.push(msgs::NetAddress::OnionV3 {
+                               ed25519_pubkey: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224],
+                               checksum: 32,
+                               version: 16,
+                               port: 9735
+                       });
+               }
+               let mut addr_len = 0;
+               for addr in &addresses {
+                       addr_len += addr.len() + 1;
+               }
+               let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
+                       features,
+                       timestamp: 20190119,
+                       node_id: pubkey_1,
+                       rgb: [32; 3],
+                       alias: [16;32],
+                       addresses,
+                       excess_address_data: if excess_address_data { vec![33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34, 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84, 174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42, 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105] } else { Vec::new() },
+                       excess_data: if excess_data { vec![59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160, 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8, 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17, 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253] } else { Vec::new() },
+               };
+               addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
+               let node_announcement = msgs::NodeAnnouncement {
+                       signature: sig_1,
+                       contents: unsigned_node_announcement,
+               };
+               let encoded_value = node_announcement.encode();
+               let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
+               if unknown_features_bits {
+                       target_value.append(&mut hex::decode("0002ffff").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("0000").unwrap());
+               }
+               target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
+               target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
+               if ipv4 {
+                       target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
+               }
+               if ipv6 {
+                       target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
+               }
+               if onionv2 {
+                       target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
+               }
+               if onionv3 {
+                       target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
+               }
+               if excess_address_data {
+                       target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
+               }
+               if excess_data {
+                       target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_node_announcement() {
+               do_encoding_node_announcement(true, true, true, true, true, true, true);
+               do_encoding_node_announcement(false, false, false, false, false, false, false);
+               do_encoding_node_announcement(false, true, false, false, false, false, false);
+               do_encoding_node_announcement(false, false, true, false, false, false, false);
+               do_encoding_node_announcement(false, false, false, true, false, false, false);
+               do_encoding_node_announcement(false, false, false, false, true, false, false);
+               do_encoding_node_announcement(false, false, false, false, false, true, false);
+               do_encoding_node_announcement(false, true, false, true, false, true, false);
+               do_encoding_node_announcement(false, false, true, false, true, false, false);
+       }
+
+       fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let unsigned_channel_update = msgs::UnsignedChannelUpdate {
+                       chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
+                       short_channel_id: 2316138423780173,
+                       timestamp: 20190119,
+                       flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
+                       cltv_expiry_delta: 144,
+                       htlc_minimum_msat: 1000000,
+                       fee_base_msat: 10000,
+                       fee_proportional_millionths: 20,
+                       excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
+               };
+               let channel_update = msgs::ChannelUpdate {
+                       signature: sig_1,
+                       contents: unsigned_channel_update
+               };
+               let encoded_value = channel_update.encode();
+               let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
+               if non_bitcoin_chain_hash {
+                       target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
+               }
+               target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
+               if htlc_maximum_msat {
+                       target_value.append(&mut hex::decode("01").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("00").unwrap());
+               }
+               target_value.append(&mut hex::decode("00").unwrap());
+               if direction {
+                       let flag = target_value.last_mut().unwrap();
+                       *flag = 1;
+               }
+               if disable {
+                       let flag = target_value.last_mut().unwrap();
+                       *flag = *flag | 1 << 1;
+               }
+               target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
+               if htlc_maximum_msat {
+                       target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_channel_update() {
+               do_encoding_channel_update(false, false, false, false);
+               do_encoding_channel_update(true, false, false, false);
+               do_encoding_channel_update(false, true, false, false);
+               do_encoding_channel_update(false, false, true, false);
+               do_encoding_channel_update(false, false, false, true);
+               do_encoding_channel_update(true, true, true, true);
+       }
+
+       fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
+               let secp_ctx = Secp256k1::new();
+               let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
+               let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
+               let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
+               let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
+               let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
+               let open_channel = msgs::OpenChannel {
+                       chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
+                       temporary_channel_id: [2; 32],
+                       funding_satoshis: 1311768467284833366,
+                       push_msat: 2536655962884945560,
+                       dust_limit_satoshis: 3608586615801332854,
+                       max_htlc_value_in_flight_msat: 8517154655701053848,
+                       channel_reserve_satoshis: 8665828695742877976,
+                       htlc_minimum_msat: 2316138423780173,
+                       feerate_per_kw: 821716,
+                       to_self_delay: 49340,
+                       max_accepted_htlcs: 49340,
+                       funding_pubkey: pubkey_1,
+                       revocation_basepoint: pubkey_2,
+                       payment_basepoint: pubkey_3,
+                       delayed_payment_basepoint: pubkey_4,
+                       htlc_basepoint: pubkey_5,
+                       first_per_commitment_point: pubkey_6,
+                       channel_flags: if random_bit { 1 << 5 } else { 0 },
+                       shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
+               };
+               let encoded_value = open_channel.encode();
+               let mut target_value = Vec::new();
+               if non_bitcoin_chain_hash {
+                       target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
+               }
+               target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
+               if random_bit {
+                       target_value.append(&mut hex::decode("20").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("00").unwrap());
+               }
+               if shutdown {
+                       target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_open_channel() {
+               do_encoding_open_channel(false, false, false);
+               do_encoding_open_channel(true, false, false);
+               do_encoding_open_channel(false, true, false);
+               do_encoding_open_channel(false, false, true);
+               do_encoding_open_channel(true, true, true);
+       }
+
+       fn do_encoding_accept_channel(shutdown: bool) {
+               let secp_ctx = Secp256k1::new();
+               let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
+               let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
+               let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
+               let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
+               let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
+               let accept_channel = msgs::AcceptChannel {
+                       temporary_channel_id: [2; 32],
+                       dust_limit_satoshis: 1311768467284833366,
+                       max_htlc_value_in_flight_msat: 2536655962884945560,
+                       channel_reserve_satoshis: 3608586615801332854,
+                       htlc_minimum_msat: 2316138423780173,
+                       minimum_depth: 821716,
+                       to_self_delay: 49340,
+                       max_accepted_htlcs: 49340,
+                       funding_pubkey: pubkey_1,
+                       revocation_basepoint: pubkey_2,
+                       payment_basepoint: pubkey_3,
+                       delayed_payment_basepoint: pubkey_4,
+                       htlc_basepoint: pubkey_5,
+                       first_per_commitment_point: pubkey_6,
+                       shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
+               };
+               let encoded_value = accept_channel.encode();
+               let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
+               if shutdown {
+                       target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_accept_channel() {
+               do_encoding_accept_channel(false);
+               do_encoding_accept_channel(true);
+       }
+
+       #[test]
+       fn encoding_funding_created() {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let funding_created = msgs::FundingCreated {
+                       temporary_channel_id: [2; 32],
+                       funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
+                       funding_output_index: 255,
+                       signature: sig_1,
+               };
+               let encoded_value = funding_created.encode();
+               let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_funding_signed() {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let funding_signed = msgs::FundingSigned {
+                       channel_id: [2; 32],
+                       signature: sig_1,
+               };
+               let encoded_value = funding_signed.encode();
+               let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_funding_locked() {
+               let secp_ctx = Secp256k1::new();
+               let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let funding_locked = msgs::FundingLocked {
+                       channel_id: [2; 32],
+                       next_per_commitment_point: pubkey_1,
+               };
+               let encoded_value = funding_locked.encode();
+               let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       fn do_encoding_shutdown(script_type: u8) {
+               let secp_ctx = Secp256k1::new();
+               let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
+               let shutdown = msgs::Shutdown {
+                       channel_id: [2; 32],
+                       scriptpubkey: if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() } else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
+               };
+               let encoded_value = shutdown.encode();
+               let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
+               if script_type == 1 {
+                       target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
+               } else if script_type == 2 {
+                       target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
+               } else if script_type == 3 {
+                       target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
+               } else if script_type == 4 {
+                       target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_shutdown() {
+               do_encoding_shutdown(1);
+               do_encoding_shutdown(2);
+               do_encoding_shutdown(3);
+               do_encoding_shutdown(4);
+       }
+
+       #[test]
+       fn encoding_closing_signed() {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let closing_signed = msgs::ClosingSigned {
+                       channel_id: [2; 32],
+                       fee_satoshis: 2316138423780173,
+                       signature: sig_1,
+               };
+               let encoded_value = closing_signed.encode();
+               let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_update_add_htlc() {
+               let secp_ctx = Secp256k1::new();
+               let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let onion_routing_packet = msgs::OnionPacket {
+                       version: 255,
+                       public_key: Ok(pubkey_1),
+                       hop_data: [1; 20*65],
+                       hmac: [2; 32]
+               };
+               let update_add_htlc = msgs::UpdateAddHTLC {
+                       channel_id: [2; 32],
+                       htlc_id: 2316138423780173,
+                       amount_msat: 3608586615801332854,
+                       payment_hash: PaymentHash([1; 32]),
+                       cltv_expiry: 821716,
+                       onion_routing_packet
+               };
+               let encoded_value = update_add_htlc.encode();
+               let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_update_fulfill_htlc() {
+               let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
+                       channel_id: [2; 32],
+                       htlc_id: 2316138423780173,
+                       payment_preimage: PaymentPreimage([1; 32]),
+               };
+               let encoded_value = update_fulfill_htlc.encode();
+               let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_update_fail_htlc() {
+               let reason = OnionErrorPacket {
+                       data: [1; 32].to_vec(),
+               };
+               let update_fail_htlc = msgs::UpdateFailHTLC {
+                       channel_id: [2; 32],
+                       htlc_id: 2316138423780173,
+                       reason
+               };
+               let encoded_value = update_fail_htlc.encode();
+               let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_update_fail_malformed_htlc() {
+               let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
+                       channel_id: [2; 32],
+                       htlc_id: 2316138423780173,
+                       sha256_of_onion: [1; 32],
+                       failure_code: 255
+               };
+               let encoded_value = update_fail_malformed_htlc.encode();
+               let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       fn do_encoding_commitment_signed(htlcs: bool) {
+               let secp_ctx = Secp256k1::new();
+               let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
+               let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
+               let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
+               let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
+               let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
+               let commitment_signed = msgs::CommitmentSigned {
+                       channel_id: [2; 32],
+                       signature: sig_1,
+                       htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
+               };
+               let encoded_value = commitment_signed.encode();
+               let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
+               if htlcs {
+                       target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("0000").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_commitment_signed() {
+               do_encoding_commitment_signed(true);
+               do_encoding_commitment_signed(false);
+       }
+
+       #[test]
+       fn encoding_revoke_and_ack() {
+               let secp_ctx = Secp256k1::new();
+               let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
+               let raa = msgs::RevokeAndACK {
+                       channel_id: [2; 32],
+                       per_commitment_secret: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+                       next_per_commitment_point: pubkey_1,
+               };
+               let encoded_value = raa.encode();
+               let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_update_fee() {
+               let update_fee = msgs::UpdateFee {
+                       channel_id: [2; 32],
+                       feerate_per_kw: 20190119,
+               };
+               let encoded_value = update_fee.encode();
+               let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       fn do_encoding_init(unknown_global_bits: bool, initial_routing_sync: bool) {
+               let mut global = GlobalFeatures::new();
+               if unknown_global_bits {
+                       global.flags = vec![0xFF, 0xFF];
+               }
+               let mut local = LocalFeatures::new();
+               if initial_routing_sync {
+                       local.set_initial_routing_sync();
+               }
+               let init = msgs::Init {
+                       global_features: global,
+                       local_features: local,
+               };
+               let encoded_value = init.encode();
+               let mut target_value = Vec::new();
+               if unknown_global_bits {
+                       target_value.append(&mut hex::decode("0002ffff").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("0000").unwrap());
+               }
+               if initial_routing_sync {
+                       target_value.append(&mut hex::decode("00012a").unwrap());
+               } else {
+                       target_value.append(&mut hex::decode("000122").unwrap());
+               }
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_init() {
+               do_encoding_init(false, false);
+               do_encoding_init(true, false);
+               do_encoding_init(false, true);
+               do_encoding_init(true, true);
+       }
+
+       #[test]
+       fn encoding_error() {
+               let error = msgs::ErrorMessage {
+                       channel_id: [2; 32],
+                       data: String::from("rust-lightning"),
+               };
+               let encoded_value = error.encode();
+               let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_ping() {
+               let ping = msgs::Ping {
+                       ponglen: 64,
+                       byteslen: 64
+               };
+               let encoded_value = ping.encode();
+               let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
+
+       #[test]
+       fn encoding_pong() {
+               let pong = msgs::Pong {
+                       byteslen: 64
+               };
+               let encoded_value = pong.encode();
+               let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
+               assert_eq!(encoded_value, target_value);
+       }
 }