Correct excess-data handling in ChannelUpdate
[rust-lightning] / src / ln / msgs.rs
1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use secp256k1;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::{deserialize,serialize};
6 use bitcoin::blockdata::script::Script;
7
8 use std::error::Error;
9 use std::{cmp, fmt};
10 use std::result::Result;
11
12 use util::{byte_utils, internal_traits, events};
13
14 pub trait MsgEncodable {
15         fn encode(&self) -> Vec<u8>;
16         #[inline]
17         fn encoded_len(&self) -> usize { self.encode().len() }
18         #[inline]
19         fn encode_with_len(&self) -> Vec<u8> {
20                 let enc = self.encode();
21                 let mut res = Vec::with_capacity(enc.len() + 2);
22                 res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
23                 res.extend_from_slice(&enc);
24                 res
25         }
26 }
27 #[derive(Debug)]
28 pub enum DecodeError {
29         /// Unknown realm byte in an OnionHopData packet
30         UnknownRealmByte,
31         /// Failed to decode a public key (ie it's invalid)
32         BadPublicKey,
33         /// Failed to decode a signature (ie it's invalid)
34         BadSignature,
35         /// Value expected to be text wasn't decodable as text
36         BadText,
37         /// Buffer too short
38         ShortRead,
39         /// node_announcement included more than one address of a given type!
40         ExtraAddressesPerType,
41         /// A length descriptor in the packet didn't describe the later data correctly
42         /// (currently only generated in node_announcement)
43         BadLengthDescriptor,
44 }
45 pub trait MsgDecodable: Sized {
46         fn decode(v: &[u8]) -> Result<Self, DecodeError>;
47 }
48
49 /// Tracks localfeatures which are only in init messages
50 #[derive(Clone, PartialEq)]
51 pub struct LocalFeatures {
52         flags: Vec<u8>,
53 }
54
55 impl LocalFeatures {
56         pub fn new() -> LocalFeatures {
57                 LocalFeatures {
58                         flags: Vec::new(),
59                 }
60         }
61
62         pub fn supports_data_loss_protect(&self) -> bool {
63                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
64         }
65         pub fn requires_data_loss_protect(&self) -> bool {
66                 self.flags.len() > 0 && (self.flags[0] & 1) != 0
67         }
68
69         pub fn initial_routing_sync(&self) -> bool {
70                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
71         }
72         pub fn set_initial_routing_sync(&mut self) {
73                 if self.flags.len() == 0 {
74                         self.flags.resize(1, 1 << 3);
75                 } else {
76                         self.flags[0] |= 1 << 3;
77                 }
78         }
79
80         pub fn supports_upfront_shutdown_script(&self) -> bool {
81                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
82         }
83         pub fn requires_upfront_shutdown_script(&self) -> bool {
84                 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
85         }
86
87         pub fn requires_unknown_bits(&self) -> bool {
88                 for (idx, &byte) in self.flags.iter().enumerate() {
89                         if idx != 0 && (byte & 0x55) != 0 {
90                                 return true;
91                         } else if idx == 0 && (byte & 0x14) != 0 {
92                                 return true;
93                         }
94                 }
95                 return false;
96         }
97
98         pub fn supports_unknown_bits(&self) -> bool {
99                 for (idx, &byte) in self.flags.iter().enumerate() {
100                         if idx != 0 && byte != 0 {
101                                 return true;
102                         } else if idx == 0 && (byte & 0xc4) != 0 {
103                                 return true;
104                         }
105                 }
106                 return false;
107         }
108 }
109
110 /// Tracks globalfeatures which are in init messages and routing announcements
111 #[derive(Clone, PartialEq)]
112 pub struct GlobalFeatures {
113         flags: Vec<u8>,
114 }
115
116 impl GlobalFeatures {
117         pub fn new() -> GlobalFeatures {
118                 GlobalFeatures {
119                         flags: Vec::new(),
120                 }
121         }
122
123         pub fn requires_unknown_bits(&self) -> bool {
124                 for &byte in self.flags.iter() {
125                         if (byte & 0x55) != 0 {
126                                 return true;
127                         }
128                 }
129                 return false;
130         }
131
132         pub fn supports_unknown_bits(&self) -> bool {
133                 for &byte in self.flags.iter() {
134                         if byte != 0 {
135                                 return true;
136                         }
137                 }
138                 return false;
139         }
140 }
141
142 pub struct Init {
143         pub global_features: GlobalFeatures,
144         pub local_features: LocalFeatures,
145 }
146
147 pub struct ErrorMessage {
148         pub channel_id: [u8; 32],
149         pub data: String,
150 }
151
152 pub struct Ping {
153         pub ponglen: u16,
154         pub byteslen: u16,
155 }
156
157 pub struct Pong {
158         pub byteslen: u16,
159 }
160
161 pub struct OpenChannel {
162         pub chain_hash: Sha256dHash,
163         pub temporary_channel_id: [u8; 32],
164         pub funding_satoshis: u64,
165         pub push_msat: u64,
166         pub dust_limit_satoshis: u64,
167         pub max_htlc_value_in_flight_msat: u64,
168         pub channel_reserve_satoshis: u64,
169         pub htlc_minimum_msat: u64,
170         pub feerate_per_kw: u32,
171         pub to_self_delay: u16,
172         pub max_accepted_htlcs: u16,
173         pub funding_pubkey: PublicKey,
174         pub revocation_basepoint: PublicKey,
175         pub payment_basepoint: PublicKey,
176         pub delayed_payment_basepoint: PublicKey,
177         pub htlc_basepoint: PublicKey,
178         pub first_per_commitment_point: PublicKey,
179         pub channel_flags: u8,
180         pub shutdown_scriptpubkey: Option<Script>,
181 }
182
183 pub struct AcceptChannel {
184         pub temporary_channel_id: [u8; 32],
185         pub dust_limit_satoshis: u64,
186         pub max_htlc_value_in_flight_msat: u64,
187         pub channel_reserve_satoshis: u64,
188         pub htlc_minimum_msat: u64,
189         pub minimum_depth: u32,
190         pub to_self_delay: u16,
191         pub max_accepted_htlcs: u16,
192         pub funding_pubkey: PublicKey,
193         pub revocation_basepoint: PublicKey,
194         pub payment_basepoint: PublicKey,
195         pub delayed_payment_basepoint: PublicKey,
196         pub htlc_basepoint: PublicKey,
197         pub first_per_commitment_point: PublicKey,
198         pub shutdown_scriptpubkey: Option<Script>,
199 }
200
201 pub struct FundingCreated {
202         pub temporary_channel_id: [u8; 32],
203         pub funding_txid: Sha256dHash,
204         pub funding_output_index: u16,
205         pub signature: Signature,
206 }
207
208 pub struct FundingSigned {
209         pub channel_id: [u8; 32],
210         pub signature: Signature,
211 }
212
213 pub struct FundingLocked {
214         pub channel_id: [u8; 32],
215         pub next_per_commitment_point: PublicKey,
216 }
217
218 pub struct Shutdown {
219         pub channel_id: [u8; 32],
220         pub scriptpubkey: Script,
221 }
222
223 pub struct ClosingSigned {
224         pub channel_id: [u8; 32],
225         pub fee_satoshis: u64,
226         pub signature: Signature,
227 }
228
229 #[derive(Clone)]
230 pub struct UpdateAddHTLC {
231         pub channel_id: [u8; 32],
232         pub htlc_id: u64,
233         pub amount_msat: u64,
234         pub payment_hash: [u8; 32],
235         pub cltv_expiry: u32,
236         pub onion_routing_packet: OnionPacket,
237 }
238
239 #[derive(Clone)]
240 pub struct UpdateFulfillHTLC {
241         pub channel_id: [u8; 32],
242         pub htlc_id: u64,
243         pub payment_preimage: [u8; 32],
244 }
245
246 #[derive(Clone)]
247 pub struct UpdateFailHTLC {
248         pub channel_id: [u8; 32],
249         pub htlc_id: u64,
250         pub reason: OnionErrorPacket,
251 }
252
253 #[derive(Clone)]
254 pub struct UpdateFailMalformedHTLC {
255         pub channel_id: [u8; 32],
256         pub htlc_id: u64,
257         pub sha256_of_onion: [u8; 32],
258         pub failure_code: u16,
259 }
260
261 #[derive(Clone)]
262 pub struct CommitmentSigned {
263         pub channel_id: [u8; 32],
264         pub signature: Signature,
265         pub htlc_signatures: Vec<Signature>,
266 }
267
268 pub struct RevokeAndACK {
269         pub channel_id: [u8; 32],
270         pub per_commitment_secret: [u8; 32],
271         pub next_per_commitment_point: PublicKey,
272 }
273
274 pub struct UpdateFee {
275         pub channel_id: [u8; 32],
276         pub feerate_per_kw: u32,
277 }
278
279 pub struct DataLossProtect {
280         pub your_last_per_commitment_secret: [u8; 32],
281         pub my_current_per_commitment_point: PublicKey,
282 }
283
284 pub struct ChannelReestablish {
285         pub channel_id: [u8; 32],
286         pub next_local_commitment_number: u64,
287         pub next_remote_commitment_number: u64,
288         pub data_loss_protect: Option<DataLossProtect>,
289 }
290
291 #[derive(Clone)]
292 pub struct AnnouncementSignatures {
293         pub channel_id: [u8; 32],
294         pub short_channel_id: u64,
295         pub node_signature: Signature,
296         pub bitcoin_signature: Signature,
297 }
298
299 #[derive(Clone)]
300 pub enum NetAddress {
301         IPv4 {
302                 addr: [u8; 4],
303                 port: u16,
304         },
305         IPv6 {
306                 addr: [u8; 16],
307                 port: u16,
308         },
309         OnionV2 {
310                 addr: [u8; 10],
311                 port: u16,
312         },
313         OnionV3 {
314                 ed25519_pubkey: [u8; 32],
315                 checksum: u16,
316                 version: u8,
317                 port: u16,
318         },
319 }
320 impl NetAddress {
321         fn get_id(&self) -> u8 {
322                 match self {
323                         &NetAddress::IPv4 {..} => { 1 },
324                         &NetAddress::IPv6 {..} => { 2 },
325                         &NetAddress::OnionV2 {..} => { 3 },
326                         &NetAddress::OnionV3 {..} => { 4 },
327                 }
328         }
329 }
330
331 pub struct UnsignedNodeAnnouncement {
332         pub features: GlobalFeatures,
333         pub timestamp: u32,
334         pub node_id: PublicKey,
335         pub rgb: [u8; 3],
336         pub alias: [u8; 32],
337         /// List of addresses on which this node is reachable. Note that you may only have up to one
338         /// address of each type, if you have more, they may be silently discarded or we may panic!
339         pub addresses: Vec<NetAddress>,
340 }
341 pub struct NodeAnnouncement {
342         pub signature: Signature,
343         pub contents: UnsignedNodeAnnouncement,
344 }
345
346 #[derive(PartialEq, Clone)]
347 pub struct UnsignedChannelAnnouncement {
348         pub features: GlobalFeatures,
349         pub chain_hash: Sha256dHash,
350         pub short_channel_id: u64,
351         pub node_id_1: PublicKey,
352         pub node_id_2: PublicKey,
353         pub bitcoin_key_1: PublicKey,
354         pub bitcoin_key_2: PublicKey,
355         pub excess_data: Vec<u8>,
356 }
357 #[derive(PartialEq, Clone)]
358 pub struct ChannelAnnouncement {
359         pub node_signature_1: Signature,
360         pub node_signature_2: Signature,
361         pub bitcoin_signature_1: Signature,
362         pub bitcoin_signature_2: Signature,
363         pub contents: UnsignedChannelAnnouncement,
364 }
365
366 #[derive(PartialEq, Clone)]
367 pub struct UnsignedChannelUpdate {
368         pub chain_hash: Sha256dHash,
369         pub short_channel_id: u64,
370         pub timestamp: u32,
371         pub flags: u16,
372         pub cltv_expiry_delta: u16,
373         pub htlc_minimum_msat: u64,
374         pub fee_base_msat: u32,
375         pub fee_proportional_millionths: u32,
376         pub excess_data: Vec<u8>,
377 }
378 #[derive(PartialEq, Clone)]
379 pub struct ChannelUpdate {
380         pub signature: Signature,
381         pub contents: UnsignedChannelUpdate,
382 }
383
384 /// Used to put an error message in a HandleError
385 pub enum ErrorAction {
386         /// The peer took some action which made us think they were useless. Disconnect them.
387         DisconnectPeer {
388                 msg: Option<ErrorMessage>
389         },
390         /// The peer did something harmless that we weren't able to process, just log and ignore
391         IgnoreError,
392         /// The peer did something incorrect. Tell them.
393         SendErrorMessage {
394                 msg: ErrorMessage
395         },
396 }
397
398 pub struct HandleError { //TODO: rename me
399         pub err: &'static str,
400         pub action: Option<ErrorAction>, //TODO: Make this required
401 }
402
403 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
404 /// transaction updates if they were pending.
405 pub struct CommitmentUpdate {
406         pub update_add_htlcs: Vec<UpdateAddHTLC>,
407         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
408         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
409         pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
410         pub commitment_signed: CommitmentSigned,
411 }
412
413 pub enum HTLCFailChannelUpdate {
414         ChannelUpdateMessage {
415                 msg: ChannelUpdate,
416         },
417         ChannelClosed {
418                 short_channel_id: u64,
419         },
420 }
421
422 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
423 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
424 /// paralell when the two calls have the same their_node_id.
425 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
426         //Channel init:
427         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
428         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
429         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
430         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
431         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
432
433         // Channl close:
434         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
435         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
436
437         // HTLC handling:
438         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
439         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
440         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
441         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
442         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
443         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
444
445         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
446
447         // Channel-to-announce:
448         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
449
450         // Error conditions:
451         /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
452         /// is believed to be possible in the future (eg they're sending us messages we don't
453         /// understand or indicate they require unknown feature bits), no_connection_possible is set
454         /// and any outstanding channels should be failed.
455         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
456
457         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
458 }
459
460 pub trait RoutingMessageHandler : Send + Sync {
461         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
462         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
463         /// or returning an Err otherwise.
464         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
465         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
466         fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
467 }
468
469 pub struct OnionRealm0HopData {
470         pub short_channel_id: u64,
471         pub amt_to_forward: u64,
472         pub outgoing_cltv_value: u32,
473         // 12 bytes of 0-padding
474 }
475
476 pub struct OnionHopData {
477         pub realm: u8,
478         pub data: OnionRealm0HopData,
479         pub hmac: [u8; 32],
480 }
481 unsafe impl internal_traits::NoDealloc for OnionHopData{}
482
483 #[derive(Clone)]
484 pub struct OnionPacket {
485         pub version: u8,
486         /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
487         /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
488         /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
489         pub public_key: Result<PublicKey, secp256k1::Error>,
490         pub hop_data: [u8; 20*65],
491         pub hmac: [u8; 32],
492 }
493
494 pub struct DecodedOnionErrorPacket {
495         pub hmac: [u8; 32],
496         pub failuremsg: Vec<u8>,
497         pub pad: Vec<u8>,
498 }
499
500 #[derive(Clone)]
501 pub struct OnionErrorPacket {
502         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
503         // (TODO) We limit it in decode to much lower...
504         pub data: Vec<u8>,
505 }
506
507 impl Error for DecodeError {
508         fn description(&self) -> &str {
509                 match *self {
510                         DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
511                         DecodeError::BadPublicKey => "Invalid public key in packet",
512                         DecodeError::BadSignature => "Invalid signature in packet",
513                         DecodeError::BadText => "Invalid text in packet",
514                         DecodeError::ShortRead => "Packet extended beyond the provided bytes",
515                         DecodeError::ExtraAddressesPerType => "More than one address of a single type",
516                         DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
517                 }
518         }
519 }
520 impl fmt::Display for DecodeError {
521         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522                 f.write_str(self.description())
523         }
524 }
525
526 impl fmt::Debug for HandleError {
527         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528                 f.write_str(self.err)
529         }
530 }
531
532 macro_rules! secp_pubkey {
533         ( $ctx: expr, $slice: expr ) => {
534                 match PublicKey::from_slice($ctx, $slice) {
535                         Ok(key) => key,
536                         Err(_) => return Err(DecodeError::BadPublicKey)
537                 }
538         };
539 }
540
541 macro_rules! secp_signature {
542         ( $ctx: expr, $slice: expr ) => {
543                 match Signature::from_compact($ctx, $slice) {
544                         Ok(sig) => sig,
545                         Err(_) => return Err(DecodeError::BadSignature)
546                 }
547         };
548 }
549
550 impl MsgDecodable for LocalFeatures {
551         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
552                 if v.len() < 2 { return Err(DecodeError::ShortRead); }
553                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
554                 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
555                 let mut flags = Vec::with_capacity(len);
556                 flags.extend_from_slice(&v[2..2 + len]);
557                 Ok(Self {
558                         flags: flags
559                 })
560         }
561 }
562 impl MsgEncodable for LocalFeatures {
563         fn encode(&self) -> Vec<u8> {
564                 let mut res = Vec::with_capacity(self.flags.len() + 2);
565                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
566                 res.extend_from_slice(&self.flags[..]);
567                 res
568         }
569         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
570 }
571
572 impl MsgDecodable for GlobalFeatures {
573         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
574                 if v.len() < 2 { return Err(DecodeError::ShortRead); }
575                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
576                 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
577                 let mut flags = Vec::with_capacity(len);
578                 flags.extend_from_slice(&v[2..2 + len]);
579                 Ok(Self {
580                         flags: flags
581                 })
582         }
583 }
584 impl MsgEncodable for GlobalFeatures {
585         fn encode(&self) -> Vec<u8> {
586                 let mut res = Vec::with_capacity(self.flags.len() + 2);
587                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
588                 res.extend_from_slice(&self.flags[..]);
589                 res
590         }
591         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
592 }
593
594 impl MsgDecodable for Init {
595         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
596                 let global_features = GlobalFeatures::decode(v)?;
597                 if v.len() < global_features.flags.len() + 4 {
598                         return Err(DecodeError::ShortRead);
599                 }
600                 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
601                 Ok(Self {
602                         global_features: global_features,
603                         local_features: local_features,
604                 })
605         }
606 }
607 impl MsgEncodable for Init {
608         fn encode(&self) -> Vec<u8> {
609                 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
610                 res.extend_from_slice(&self.global_features.encode()[..]);
611                 res.extend_from_slice(&self.local_features.encode()[..]);
612                 res
613         }
614 }
615
616 impl MsgDecodable for Ping {
617         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
618                 if v.len() < 4 {
619                         return Err(DecodeError::ShortRead);
620                 }
621                 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
622                 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
623                 if v.len() < 4 + byteslen as usize {
624                         return Err(DecodeError::ShortRead);
625                 }
626                 Ok(Self {
627                         ponglen,
628                         byteslen,
629                 })
630         }
631 }
632 impl MsgEncodable for Ping {
633         fn encode(&self) -> Vec<u8> {
634                 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
635                 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
636                 res.resize(2 + self.byteslen as usize, 0);
637                 res
638         }
639 }
640
641 impl MsgDecodable for Pong {
642         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
643                 if v.len() < 2 {
644                         return Err(DecodeError::ShortRead);
645                 }
646                 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
647                 if v.len() < 2 + byteslen as usize {
648                         return Err(DecodeError::ShortRead);
649                 }
650                 Ok(Self {
651                         byteslen
652                 })
653         }
654 }
655 impl MsgEncodable for Pong {
656         fn encode(&self) -> Vec<u8> {
657                 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
658                 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
659                 res.resize(2 + self.byteslen as usize, 0);
660                 res
661         }
662 }
663
664 impl MsgDecodable for OpenChannel {
665         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
666                 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
667                         return Err(DecodeError::ShortRead);
668                 }
669                 let ctx = Secp256k1::without_caps();
670
671                 let mut shutdown_scriptpubkey = None;
672                 if v.len() >= 321 {
673                         let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
674                         if v.len() < 321+len {
675                                 return Err(DecodeError::ShortRead);
676                         }
677                         shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
678                 }
679
680                 Ok(OpenChannel {
681                         chain_hash: deserialize(&v[0..32]).unwrap(),
682                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
683                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
684                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
685                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
686                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
687                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
688                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
689                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
690                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
691                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
692                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
693                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
694                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
695                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
696                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
697                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
698                         channel_flags: v[318],
699                         shutdown_scriptpubkey: shutdown_scriptpubkey
700                 })
701         }
702 }
703 impl MsgEncodable for OpenChannel {
704         fn encode(&self) -> Vec<u8> {
705                 let mut res = match &self.shutdown_scriptpubkey {
706                         &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
707                         &None => Vec::with_capacity(319),
708                 };
709                 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
710                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
711                 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
712                 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
713                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
714                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
715                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
716                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
717                 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
718                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
719                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
720                 res.extend_from_slice(&self.funding_pubkey.serialize());
721                 res.extend_from_slice(&self.revocation_basepoint.serialize());
722                 res.extend_from_slice(&self.payment_basepoint.serialize());
723                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
724                 res.extend_from_slice(&self.htlc_basepoint.serialize());
725                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
726                 res.push(self.channel_flags);
727                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
728                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
729                         res.extend_from_slice(&script[..]);
730                 }
731                 res
732         }
733 }
734
735 impl MsgDecodable for AcceptChannel {
736         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
737                 if v.len() < 32+4*8+4+2*2+6*33 {
738                         return Err(DecodeError::ShortRead);
739                 }
740                 let ctx = Secp256k1::without_caps();
741
742                 let mut shutdown_scriptpubkey = None;
743                 if v.len() >= 272 {
744                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
745                         if v.len() < 272+len {
746                                 return Err(DecodeError::ShortRead);
747                         }
748                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
749                 }
750
751                 let mut temporary_channel_id = [0; 32];
752                 temporary_channel_id[..].copy_from_slice(&v[0..32]);
753                 Ok(Self {
754                         temporary_channel_id,
755                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
756                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
757                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
758                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
759                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
760                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
761                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
762                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
763                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
764                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
765                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
766                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
767                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
768                         shutdown_scriptpubkey: shutdown_scriptpubkey
769                 })
770         }
771 }
772 impl MsgEncodable for AcceptChannel {
773         fn encode(&self) -> Vec<u8> {
774                 let mut res = match &self.shutdown_scriptpubkey {
775                         &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
776                         &None => Vec::with_capacity(270),
777                 };
778                 res.extend_from_slice(&self.temporary_channel_id);
779                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
780                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
781                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
782                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
783                 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
784                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
785                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
786                 res.extend_from_slice(&self.funding_pubkey.serialize());
787                 res.extend_from_slice(&self.revocation_basepoint.serialize());
788                 res.extend_from_slice(&self.payment_basepoint.serialize());
789                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
790                 res.extend_from_slice(&self.htlc_basepoint.serialize());
791                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
792                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
793                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
794                         res.extend_from_slice(&script[..]);
795                 }
796                 res
797         }
798 }
799
800 impl MsgDecodable for FundingCreated {
801         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
802                 if v.len() < 32+32+2+64 {
803                         return Err(DecodeError::ShortRead);
804                 }
805                 let ctx = Secp256k1::without_caps();
806                 let mut temporary_channel_id = [0; 32];
807                 temporary_channel_id[..].copy_from_slice(&v[0..32]);
808                 Ok(Self {
809                         temporary_channel_id,
810                         funding_txid: deserialize(&v[32..64]).unwrap(),
811                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
812                         signature: secp_signature!(&ctx, &v[66..130]),
813                 })
814         }
815 }
816 impl MsgEncodable for FundingCreated {
817         fn encode(&self) -> Vec<u8> {
818                 let mut res = Vec::with_capacity(32+32+2+64);
819                 res.extend_from_slice(&self.temporary_channel_id);
820                 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
821                 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
822                 let secp_ctx = Secp256k1::without_caps();
823                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
824                 res
825         }
826 }
827
828 impl MsgDecodable for FundingSigned {
829         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
830                 if v.len() < 32+64 {
831                         return Err(DecodeError::ShortRead);
832                 }
833                 let ctx = Secp256k1::without_caps();
834                 let mut channel_id = [0; 32];
835                 channel_id[..].copy_from_slice(&v[0..32]);
836                 Ok(Self {
837                         channel_id,
838                         signature: secp_signature!(&ctx, &v[32..96]),
839                 })
840         }
841 }
842 impl MsgEncodable for FundingSigned {
843         fn encode(&self) -> Vec<u8> {
844                 let mut res = Vec::with_capacity(32+64);
845                 res.extend_from_slice(&self.channel_id);
846                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
847                 res
848         }
849 }
850
851 impl MsgDecodable for FundingLocked {
852         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
853                 if v.len() < 32+33 {
854                         return Err(DecodeError::ShortRead);
855                 }
856                 let ctx = Secp256k1::without_caps();
857                 let mut channel_id = [0; 32];
858                 channel_id[..].copy_from_slice(&v[0..32]);
859                 Ok(Self {
860                         channel_id,
861                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
862                 })
863         }
864 }
865 impl MsgEncodable for FundingLocked {
866         fn encode(&self) -> Vec<u8> {
867                 let mut res = Vec::with_capacity(32+33);
868                 res.extend_from_slice(&self.channel_id);
869                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
870                 res
871         }
872 }
873
874 impl MsgDecodable for Shutdown {
875         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
876                 if v.len() < 32 + 2 {
877                         return Err(DecodeError::ShortRead);
878                 }
879                 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
880                 if v.len() < 32 + 2 + scriptlen {
881                         return Err(DecodeError::ShortRead);
882                 }
883                 let mut channel_id = [0; 32];
884                 channel_id[..].copy_from_slice(&v[0..32]);
885                 Ok(Self {
886                         channel_id,
887                         scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
888                 })
889         }
890 }
891 impl MsgEncodable for Shutdown {
892         fn encode(&self) -> Vec<u8> {
893                 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
894                 res.extend_from_slice(&self.channel_id);
895                 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
896                 res.extend_from_slice(&self.scriptpubkey[..]);
897                 res
898         }
899 }
900
901 impl MsgDecodable for ClosingSigned {
902         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
903                 if v.len() < 32 + 8 + 64 {
904                         return Err(DecodeError::ShortRead);
905                 }
906                 let secp_ctx = Secp256k1::without_caps();
907                 let mut channel_id = [0; 32];
908                 channel_id[..].copy_from_slice(&v[0..32]);
909                 Ok(Self {
910                         channel_id,
911                         fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
912                         signature: secp_signature!(&secp_ctx, &v[40..104]),
913                 })
914         }
915 }
916 impl MsgEncodable for ClosingSigned {
917         fn encode(&self) -> Vec<u8> {
918                 let mut res = Vec::with_capacity(32+8+64);
919                 res.extend_from_slice(&self.channel_id);
920                 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
921                 let secp_ctx = Secp256k1::without_caps();
922                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
923                 res
924         }
925 }
926
927 impl MsgDecodable for UpdateAddHTLC {
928         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
929                 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
930                         return Err(DecodeError::ShortRead);
931                 }
932                 let mut channel_id = [0; 32];
933                 channel_id[..].copy_from_slice(&v[0..32]);
934                 let mut payment_hash = [0; 32];
935                 payment_hash.copy_from_slice(&v[48..80]);
936                 Ok(Self{
937                         channel_id,
938                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
939                         amount_msat: byte_utils::slice_to_be64(&v[40..48]),
940                         payment_hash,
941                         cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
942                         onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
943                 })
944         }
945 }
946 impl MsgEncodable for UpdateAddHTLC {
947         fn encode(&self) -> Vec<u8> {
948                 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
949                 res.extend_from_slice(&self.channel_id);
950                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
951                 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
952                 res.extend_from_slice(&self.payment_hash);
953                 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
954                 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
955                 res
956         }
957 }
958
959 impl MsgDecodable for UpdateFulfillHTLC {
960         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
961                 if v.len() < 32+8+32 {
962                         return Err(DecodeError::ShortRead);
963                 }
964                 let mut channel_id = [0; 32];
965                 channel_id[..].copy_from_slice(&v[0..32]);
966                 let mut payment_preimage = [0; 32];
967                 payment_preimage.copy_from_slice(&v[40..72]);
968                 Ok(Self{
969                         channel_id,
970                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
971                         payment_preimage,
972                 })
973         }
974 }
975 impl MsgEncodable for UpdateFulfillHTLC {
976         fn encode(&self) -> Vec<u8> {
977                 let mut res = Vec::with_capacity(32+8+32);
978                 res.extend_from_slice(&self.channel_id);
979                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
980                 res.extend_from_slice(&self.payment_preimage);
981                 res
982         }
983 }
984
985 impl MsgDecodable for UpdateFailHTLC {
986         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
987                 if v.len() < 32+8 {
988                         return Err(DecodeError::ShortRead);
989                 }
990                 let mut channel_id = [0; 32];
991                 channel_id[..].copy_from_slice(&v[0..32]);
992                 Ok(Self{
993                         channel_id,
994                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
995                         reason: OnionErrorPacket::decode(&v[40..])?,
996                 })
997         }
998 }
999 impl MsgEncodable for UpdateFailHTLC {
1000         fn encode(&self) -> Vec<u8> {
1001                 let reason = self.reason.encode();
1002                 let mut res = Vec::with_capacity(32+8+reason.len());
1003                 res.extend_from_slice(&self.channel_id);
1004                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1005                 res.extend_from_slice(&reason[..]);
1006                 res
1007         }
1008 }
1009
1010 impl MsgDecodable for UpdateFailMalformedHTLC {
1011         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1012                 if v.len() < 32+8+32+2 {
1013                         return Err(DecodeError::ShortRead);
1014                 }
1015                 let mut channel_id = [0; 32];
1016                 channel_id[..].copy_from_slice(&v[0..32]);
1017                 let mut sha256_of_onion = [0; 32];
1018                 sha256_of_onion.copy_from_slice(&v[40..72]);
1019                 Ok(Self{
1020                         channel_id,
1021                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1022                         sha256_of_onion,
1023                         failure_code: byte_utils::slice_to_be16(&v[72..74]),
1024                 })
1025         }
1026 }
1027 impl MsgEncodable for UpdateFailMalformedHTLC {
1028         fn encode(&self) -> Vec<u8> {
1029                 let mut res = Vec::with_capacity(32+8+32+2);
1030                 res.extend_from_slice(&self.channel_id);
1031                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1032                 res.extend_from_slice(&self.sha256_of_onion);
1033                 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1034                 res
1035         }
1036 }
1037
1038 impl MsgDecodable for CommitmentSigned {
1039         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1040                 if v.len() < 32+64+2 {
1041                         return Err(DecodeError::ShortRead);
1042                 }
1043                 let mut channel_id = [0; 32];
1044                 channel_id[..].copy_from_slice(&v[0..32]);
1045
1046                 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1047                 if v.len() < 32+64+2+htlcs*64 {
1048                         return Err(DecodeError::ShortRead);
1049                 }
1050                 let mut htlc_signatures = Vec::with_capacity(htlcs);
1051                 let secp_ctx = Secp256k1::without_caps();
1052                 for i in 0..htlcs {
1053                         htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1054                 }
1055                 Ok(Self {
1056                         channel_id,
1057                         signature: secp_signature!(&secp_ctx, &v[32..96]),
1058                         htlc_signatures,
1059                 })
1060         }
1061 }
1062 impl MsgEncodable for CommitmentSigned {
1063         fn encode(&self) -> Vec<u8> {
1064                 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1065                 res.extend_from_slice(&self.channel_id);
1066                 let secp_ctx = Secp256k1::without_caps();
1067                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1068                 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1069                 for i in 0..self.htlc_signatures.len() {
1070                         res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1071                 }
1072                 res
1073         }
1074 }
1075
1076 impl MsgDecodable for RevokeAndACK {
1077         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1078                 if v.len() < 32+32+33 {
1079                         return Err(DecodeError::ShortRead);
1080                 }
1081                 let mut channel_id = [0; 32];
1082                 channel_id[..].copy_from_slice(&v[0..32]);
1083                 let mut per_commitment_secret = [0; 32];
1084                 per_commitment_secret.copy_from_slice(&v[32..64]);
1085                 let secp_ctx = Secp256k1::without_caps();
1086                 Ok(Self {
1087                         channel_id,
1088                         per_commitment_secret,
1089                         next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1090                 })
1091         }
1092 }
1093 impl MsgEncodable for RevokeAndACK {
1094         fn encode(&self) -> Vec<u8> {
1095                 let mut res = Vec::with_capacity(32+32+33);
1096                 res.extend_from_slice(&self.channel_id);
1097                 res.extend_from_slice(&self.per_commitment_secret);
1098                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1099                 res
1100         }
1101 }
1102
1103 impl MsgDecodable for UpdateFee {
1104         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1105                 if v.len() < 32+4 {
1106                         return Err(DecodeError::ShortRead);
1107                 }
1108                 let mut channel_id = [0; 32];
1109                 channel_id[..].copy_from_slice(&v[0..32]);
1110                 Ok(Self {
1111                         channel_id,
1112                         feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1113                 })
1114         }
1115 }
1116 impl MsgEncodable for UpdateFee {
1117         fn encode(&self) -> Vec<u8> {
1118                 let mut res = Vec::with_capacity(32+4);
1119                 res.extend_from_slice(&self.channel_id);
1120                 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1121                 res
1122         }
1123 }
1124
1125 impl MsgDecodable for ChannelReestablish {
1126         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1127                 if v.len() < 32+2*8 {
1128                         return Err(DecodeError::ShortRead);
1129                 }
1130
1131                 let data_loss_protect = if v.len() > 32+2*8 {
1132                         if v.len() < 32+2*8 + 33+32 {
1133                                 return Err(DecodeError::ShortRead);
1134                         }
1135                         let mut inner_array = [0; 32];
1136                         inner_array.copy_from_slice(&v[48..48+32]);
1137                         Some(DataLossProtect {
1138                                 your_last_per_commitment_secret: inner_array,
1139                                 my_current_per_commitment_point: secp_pubkey!(&Secp256k1::without_caps(), &v[48+32..48+32+33]),
1140                         })
1141                 } else { None };
1142
1143                 Ok(Self {
1144                         channel_id: deserialize(&v[0..32]).unwrap(),
1145                         next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1146                         next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1147                         data_loss_protect: data_loss_protect,
1148                 })
1149         }
1150 }
1151 impl MsgEncodable for ChannelReestablish {
1152         fn encode(&self) -> Vec<u8> {
1153                 let mut res = Vec::with_capacity(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
1154
1155                 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1156                 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1157                 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1158
1159                 if let &Some(ref data_loss_protect) = &self.data_loss_protect {
1160                         res.extend_from_slice(&data_loss_protect.your_last_per_commitment_secret[..]);
1161                         res.extend_from_slice(&data_loss_protect.my_current_per_commitment_point.serialize());
1162                 }
1163                 res
1164         }
1165 }
1166
1167 impl MsgDecodable for AnnouncementSignatures {
1168         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1169                 if v.len() < 32+8+64*2 {
1170                         return Err(DecodeError::ShortRead);
1171                 }
1172                 let secp_ctx = Secp256k1::without_caps();
1173                 let mut channel_id = [0; 32];
1174                 channel_id[..].copy_from_slice(&v[0..32]);
1175                 Ok(Self {
1176                         channel_id,
1177                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1178                         node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1179                         bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1180                 })
1181         }
1182 }
1183 impl MsgEncodable for AnnouncementSignatures {
1184         fn encode(&self) -> Vec<u8> {
1185                 let mut res = Vec::with_capacity(32+8+64*2);
1186                 res.extend_from_slice(&self.channel_id);
1187                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1188                 let secp_ctx = Secp256k1::without_caps();
1189                 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1190                 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1191                 res
1192         }
1193 }
1194
1195 impl MsgDecodable for UnsignedNodeAnnouncement {
1196         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1197                 let features = GlobalFeatures::decode(&v[..])?;
1198                 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1199                         return Err(DecodeError::ShortRead);
1200                 }
1201                 let start = features.encoded_len();
1202
1203                 let mut rgb = [0; 3];
1204                 rgb.copy_from_slice(&v[start + 37..start + 40]);
1205
1206                 let mut alias = [0; 32];
1207                 alias.copy_from_slice(&v[start + 40..start + 72]);
1208
1209                 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1210                 if v.len() < start + 74 + addrlen {
1211                         return Err(DecodeError::ShortRead);
1212                 }
1213                 let addr_read_limit = start + 74 + addrlen;
1214
1215                 let mut addresses = Vec::with_capacity(4);
1216                 let mut read_pos = start + 74;
1217                 loop {
1218                         if addr_read_limit <= read_pos { break; }
1219                         match v[read_pos] {
1220                                 0 => { read_pos += 1; },
1221                                 1 => {
1222                                         if addresses.len() > 0 {
1223                                                 return Err(DecodeError::ExtraAddressesPerType);
1224                                         }
1225                                         if addr_read_limit < read_pos + 1 + 6 {
1226                                                 return Err(DecodeError::BadLengthDescriptor);
1227                                         }
1228                                         let mut addr = [0; 4];
1229                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1230                                         addresses.push(NetAddress::IPv4 {
1231                                                 addr,
1232                                                 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1233                                         });
1234                                         read_pos += 1 + 6;
1235                                 },
1236                                 2 => {
1237                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1238                                                 return Err(DecodeError::ExtraAddressesPerType);
1239                                         }
1240                                         if addr_read_limit < read_pos + 1 + 18 {
1241                                                 return Err(DecodeError::BadLengthDescriptor);
1242                                         }
1243                                         let mut addr = [0; 16];
1244                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1245                                         addresses.push(NetAddress::IPv6 {
1246                                                 addr,
1247                                                 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1248                                         });
1249                                         read_pos += 1 + 18;
1250                                 },
1251                                 3 => {
1252                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1253                                                 return Err(DecodeError::ExtraAddressesPerType);
1254                                         }
1255                                         if addr_read_limit < read_pos + 1 + 12 {
1256                                                 return Err(DecodeError::BadLengthDescriptor);
1257                                         }
1258                                         let mut addr = [0; 10];
1259                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1260                                         addresses.push(NetAddress::OnionV2 {
1261                                                 addr,
1262                                                 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1263                                         });
1264                                         read_pos += 1 + 12;
1265                                 },
1266                                 4 => {
1267                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1268                                                 return Err(DecodeError::ExtraAddressesPerType);
1269                                         }
1270                                         if addr_read_limit < read_pos + 1 + 37 {
1271                                                 return Err(DecodeError::BadLengthDescriptor);
1272                                         }
1273                                         let mut ed25519_pubkey = [0; 32];
1274                                         ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1275                                         addresses.push(NetAddress::OnionV3 {
1276                                                 ed25519_pubkey,
1277                                                 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1278                                                 version: v[read_pos + 35],
1279                                                 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1280                                         });
1281                                         read_pos += 1 + 37;
1282                                 },
1283                                 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1284                         }
1285                 }
1286
1287                 let secp_ctx = Secp256k1::without_caps();
1288                 Ok(Self {
1289                         features,
1290                         timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1291                         node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1292                         rgb,
1293                         alias,
1294                         addresses,
1295                 })
1296         }
1297 }
1298 impl MsgEncodable for UnsignedNodeAnnouncement {
1299         fn encode(&self) -> Vec<u8> {
1300                 let features = self.features.encode();
1301                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1302                 res.extend_from_slice(&features[..]);
1303                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1304                 res.extend_from_slice(&self.node_id.serialize());
1305                 res.extend_from_slice(&self.rgb);
1306                 res.extend_from_slice(&self.alias);
1307                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1308                 let mut addrs_to_encode = self.addresses.clone();
1309                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1310                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1311                 for addr in addrs_to_encode.iter() {
1312                         match addr {
1313                                 &NetAddress::IPv4{addr, port} => {
1314                                         addr_slice.push(1);
1315                                         addr_slice.extend_from_slice(&addr);
1316                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1317                                 },
1318                                 &NetAddress::IPv6{addr, port} => {
1319                                         addr_slice.push(2);
1320                                         addr_slice.extend_from_slice(&addr);
1321                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1322                                 },
1323                                 &NetAddress::OnionV2{addr, port} => {
1324                                         addr_slice.push(3);
1325                                         addr_slice.extend_from_slice(&addr);
1326                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1327                                 },
1328                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1329                                         addr_slice.push(4);
1330                                         addr_slice.extend_from_slice(&ed25519_pubkey);
1331                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1332                                         addr_slice.push(version);
1333                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1334                                 },
1335                         }
1336                 }
1337                 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1338                 res.extend_from_slice(&addr_slice[..]);
1339                 res
1340         }
1341 }
1342
1343 impl MsgDecodable for NodeAnnouncement {
1344         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1345                 if v.len() < 64 {
1346                         return Err(DecodeError::ShortRead);
1347                 }
1348                 let secp_ctx = Secp256k1::without_caps();
1349                 Ok(Self {
1350                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1351                         contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1352                 })
1353         }
1354 }
1355 impl MsgEncodable for NodeAnnouncement {
1356         fn encode(&self) -> Vec<u8> {
1357                 let contents = self.contents.encode();
1358                 let mut res = Vec::with_capacity(64 + contents.len());
1359                 let secp_ctx = Secp256k1::without_caps();
1360                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1361                 res.extend_from_slice(&contents);
1362                 res
1363         }
1364 }
1365
1366 impl MsgDecodable for UnsignedChannelAnnouncement {
1367         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1368                 let features = GlobalFeatures::decode(&v[..])?;
1369                 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1370                         return Err(DecodeError::ShortRead);
1371                 }
1372                 let start = features.encoded_len();
1373                 let secp_ctx = Secp256k1::without_caps();
1374                 let mut excess_data = Vec::with_capacity(v.len() - start - 172);
1375                 excess_data.extend_from_slice(&v[start + 172..]);
1376                 Ok(Self {
1377                         features,
1378                         chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1379                         short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1380                         node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1381                         node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1382                         bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1383                         bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1384                         excess_data,
1385                 })
1386         }
1387 }
1388 impl MsgEncodable for UnsignedChannelAnnouncement {
1389         fn encode(&self) -> Vec<u8> {
1390                 let features = self.features.encode();
1391                 let mut res = Vec::with_capacity(172 + features.len() + self.excess_data.len());
1392                 res.extend_from_slice(&features[..]);
1393                 res.extend_from_slice(&self.chain_hash[..]);
1394                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1395                 res.extend_from_slice(&self.node_id_1.serialize());
1396                 res.extend_from_slice(&self.node_id_2.serialize());
1397                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1398                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1399                 res.extend_from_slice(&self.excess_data[..]);
1400                 res
1401         }
1402 }
1403
1404 impl MsgDecodable for ChannelAnnouncement {
1405         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1406                 if v.len() < 64*4 {
1407                         return Err(DecodeError::ShortRead);
1408                 }
1409                 let secp_ctx = Secp256k1::without_caps();
1410                 Ok(Self {
1411                         node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1412                         node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1413                         bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1414                         bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1415                         contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1416                 })
1417         }
1418 }
1419 impl MsgEncodable for ChannelAnnouncement {
1420         fn encode(&self) -> Vec<u8> {
1421                 let secp_ctx = Secp256k1::without_caps();
1422                 let contents = self.contents.encode();
1423                 let mut res = Vec::with_capacity(64 + contents.len());
1424                 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1425                 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1426                 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1427                 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1428                 res.extend_from_slice(&contents);
1429                 res
1430         }
1431 }
1432
1433 impl MsgDecodable for UnsignedChannelUpdate {
1434         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1435                 if v.len() < 32+8+4+2+2+8+4+4 {
1436                         return Err(DecodeError::ShortRead);
1437                 }
1438                 let mut excess_data = Vec::with_capacity(v.len() - 64);
1439                 excess_data.extend_from_slice(&v[64..]);
1440                 Ok(Self {
1441                         chain_hash: deserialize(&v[0..32]).unwrap(),
1442                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1443                         timestamp: byte_utils::slice_to_be32(&v[40..44]),
1444                         flags: byte_utils::slice_to_be16(&v[44..46]),
1445                         cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1446                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1447                         fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1448                         fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1449                         excess_data
1450                 })
1451         }
1452 }
1453 impl MsgEncodable for UnsignedChannelUpdate {
1454         fn encode(&self) -> Vec<u8> {
1455                 let mut res = Vec::with_capacity(64 + self.excess_data.len());
1456                 res.extend_from_slice(&self.chain_hash[..]);
1457                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1458                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1459                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1460                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1461                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1462                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1463                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1464                 res.extend_from_slice(&self.excess_data[..]);
1465                 res
1466         }
1467 }
1468
1469 impl MsgDecodable for ChannelUpdate {
1470         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1471                 if v.len() < 128 {
1472                         return Err(DecodeError::ShortRead);
1473                 }
1474                 let secp_ctx = Secp256k1::without_caps();
1475                 Ok(Self {
1476                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1477                         contents: UnsignedChannelUpdate::decode(&v[64..])?,
1478                 })
1479         }
1480 }
1481 impl MsgEncodable for ChannelUpdate {
1482         fn encode(&self) -> Vec<u8> {
1483                 let mut res = Vec::with_capacity(128);
1484                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1485                 res.extend_from_slice(&self.contents.encode()[..]);
1486                 res
1487         }
1488 }
1489
1490 impl MsgDecodable for OnionRealm0HopData {
1491         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1492                 if v.len() < 32 {
1493                         return Err(DecodeError::ShortRead);
1494                 }
1495                 Ok(OnionRealm0HopData {
1496                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1497                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1498                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1499                 })
1500         }
1501 }
1502 impl MsgEncodable for OnionRealm0HopData {
1503         fn encode(&self) -> Vec<u8> {
1504                 let mut res = Vec::with_capacity(32);
1505                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1506                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1507                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1508                 res.resize(32, 0);
1509                 res
1510         }
1511 }
1512
1513 impl MsgDecodable for OnionHopData {
1514         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1515                 if v.len() < 65 {
1516                         return Err(DecodeError::ShortRead);
1517                 }
1518                 let realm = v[0];
1519                 if realm != 0 {
1520                         return Err(DecodeError::UnknownRealmByte);
1521                 }
1522                 let mut hmac = [0; 32];
1523                 hmac[..].copy_from_slice(&v[33..65]);
1524                 Ok(OnionHopData {
1525                         realm: realm,
1526                         data: OnionRealm0HopData::decode(&v[1..33])?,
1527                         hmac: hmac,
1528                 })
1529         }
1530 }
1531 impl MsgEncodable for OnionHopData {
1532         fn encode(&self) -> Vec<u8> {
1533                 let mut res = Vec::with_capacity(65);
1534                 res.push(self.realm);
1535                 res.extend_from_slice(&self.data.encode()[..]);
1536                 res.extend_from_slice(&self.hmac);
1537                 res
1538         }
1539 }
1540
1541 impl MsgDecodable for OnionPacket {
1542         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1543                 if v.len() < 1+33+20*65+32 {
1544                         return Err(DecodeError::ShortRead);
1545                 }
1546                 let mut hop_data = [0; 20*65];
1547                 hop_data.copy_from_slice(&v[34..1334]);
1548                 let mut hmac = [0; 32];
1549                 hmac.copy_from_slice(&v[1334..1366]);
1550                 let secp_ctx = Secp256k1::without_caps();
1551                 Ok(Self {
1552                         version: v[0],
1553                         public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1554                         hop_data,
1555                         hmac,
1556                 })
1557         }
1558 }
1559 impl MsgEncodable for OnionPacket {
1560         fn encode(&self) -> Vec<u8> {
1561                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1562                 res.push(self.version);
1563                 match self.public_key {
1564                         Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1565                         Err(_) => res.extend_from_slice(&[0; 33]),
1566                 }
1567                 res.extend_from_slice(&self.hop_data);
1568                 res.extend_from_slice(&self.hmac);
1569                 res
1570         }
1571 }
1572
1573 impl MsgDecodable for DecodedOnionErrorPacket {
1574         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1575                 if v.len() < 32 + 4 {
1576                         return Err(DecodeError::ShortRead);
1577                 }
1578                 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1579                 if v.len() < 32 + 4 + failuremsg_len {
1580                         return Err(DecodeError::ShortRead);
1581                 }
1582                 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1583                 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1584                         return Err(DecodeError::ShortRead);
1585                 }
1586
1587                 let mut hmac = [0; 32];
1588                 hmac.copy_from_slice(&v[0..32]);
1589                 Ok(Self {
1590                         hmac,
1591                         failuremsg: v[34..34 + failuremsg_len].to_vec(),
1592                         pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1593                 })
1594         }
1595 }
1596 impl MsgEncodable for DecodedOnionErrorPacket {
1597         fn encode(&self) -> Vec<u8> {
1598                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1599                 res.extend_from_slice(&self.hmac);
1600                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1601                 res.extend_from_slice(&self.failuremsg);
1602                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1603                 res.extend_from_slice(&self.pad);
1604                 res
1605         }
1606 }
1607
1608 impl MsgDecodable for OnionErrorPacket {
1609         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1610                 if v.len() < 2 {
1611                         return Err(DecodeError::ShortRead);
1612                 }
1613                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1614                 if v.len() < 2 + len {
1615                         return Err(DecodeError::ShortRead);
1616                 }
1617                 Ok(Self {
1618                         data: v[2..len+2].to_vec(),
1619                 })
1620         }
1621 }
1622 impl MsgEncodable for OnionErrorPacket {
1623         fn encode(&self) -> Vec<u8> {
1624                 let mut res = Vec::with_capacity(2 + self.data.len());
1625                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1626                 res.extend_from_slice(&self.data);
1627                 res
1628         }
1629 }
1630
1631 impl MsgEncodable for ErrorMessage {
1632         fn encode(&self) -> Vec<u8> {
1633                 let mut res = Vec::with_capacity(34 + self.data.len());
1634                 res.extend_from_slice(&self.channel_id);
1635                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1636                 res.extend_from_slice(&self.data.as_bytes());
1637                 res
1638         }
1639 }
1640 impl MsgDecodable for ErrorMessage {
1641         fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1642                 if v.len() < 34 {
1643                         return Err(DecodeError::ShortRead);
1644                 }
1645                 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1646                 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1647                 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1648                         Ok(s) => s,
1649                         Err(_) => return Err(DecodeError::BadText),
1650                 };
1651                 let mut channel_id = [0; 32];
1652                 channel_id[..].copy_from_slice(&v[0..32]);
1653                 Ok(Self {
1654                         channel_id,
1655                         data,
1656                 })
1657         }
1658 }
1659
1660 #[cfg(test)]
1661 mod tests {
1662         use hex;
1663         use ln::msgs::MsgEncodable;
1664         use ln::msgs;
1665         use secp256k1::key::{PublicKey,SecretKey};
1666         use secp256k1::Secp256k1;
1667
1668         #[test]
1669         fn encoding_channel_reestablish_no_secret() {
1670                 let cr = msgs::ChannelReestablish {
1671                         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],
1672                         next_local_commitment_number: 3,
1673                         next_remote_commitment_number: 4,
1674                         data_loss_protect: None,
1675                 };
1676
1677                 let encoded_value = cr.encode();
1678                 assert_eq!(
1679                         encoded_value,
1680                         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]
1681                 );
1682         }
1683
1684         #[test]
1685         fn encoding_channel_reestablish_with_secret() {
1686                 let public_key = {
1687                         let secp_ctx = Secp256k1::new();
1688                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1689                 };
1690
1691                 let cr = msgs::ChannelReestablish {
1692                         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],
1693                         next_local_commitment_number: 3,
1694                         next_remote_commitment_number: 4,
1695                         data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1696                 };
1697
1698                 let encoded_value = cr.encode();
1699                 assert_eq!(
1700                         encoded_value,
1701                         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]
1702                 );
1703         }
1704 }