Make field error of LightingError mandatory
[rust-lightning] / src / ln / msgs.rs
index b70d44cba2ac0e9d0ebd1d43e70ef8c3b979872f..277d96d168733e890be98391b6017aa7df138b50 100644 (file)
@@ -18,7 +18,7 @@
 use secp256k1::key::PublicKey;
 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;
@@ -59,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
        }
@@ -86,30 +90,21 @@ 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 )
+               })
        }
 }
 
@@ -530,7 +525,7 @@ pub struct ChannelUpdate {
        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.
@@ -548,11 +543,11 @@ 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
@@ -621,42 +616,42 @@ pub enum OptionalField<T> {
 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<(), 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<(), 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<(), 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<(), 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<(), 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<(), 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<(), 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<(), 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
@@ -668,7 +663,7 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn
        /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
        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<(), HandleError>;
+       fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), LightningError>;
 
        // Error:
        /// Handle an incoming error message from the given peer.
@@ -679,13 +674,13 @@ pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Syn
 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
@@ -715,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],
@@ -776,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)
        }
@@ -1392,10 +1386,16 @@ impl_writeable_len_match!(NodeAnnouncement, {
 mod tests {
        use hex;
        use ln::msgs;
-       use ln::msgs::{GlobalFeatures, OptionalField};
+       use ln::msgs::{GlobalFeatures, LocalFeatures, OptionalField, OnionErrorPacket};
+       use ln::channelmanager::{PaymentPreimage, PaymentHash};
        use util::ser::Writeable;
 
-       use bitcoin::util::hash::Sha256dHash;
+       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, Message};
@@ -1689,4 +1689,375 @@ mod tests {
                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);
+       }
 }