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