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