Fix test for ChannelReestablish
[rust-lightning] / src / ln / msgs.rs
1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use secp256k1;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::{deserialize,serialize};
6 use bitcoin::blockdata::script::Script;
7
8 use std::error::Error;
9 use std::{cmp, fmt};
10 use std::result::Result;
11
12 use util::{byte_utils, internal_traits, events};
13
14 pub trait MsgEncodable {
15         fn encode(&self) -> Vec<u8>;
16         #[inline]
17         fn encoded_len(&self) -> usize { self.encode().len() }
18         #[inline]
19         fn encode_with_len(&self) -> Vec<u8> {
20                 let enc = self.encode();
21                 let mut res = Vec::with_capacity(enc.len() + 2);
22                 res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
23                 res.extend_from_slice(&enc);
24                 res
25         }
26 }
27 #[derive(Debug)]
28 pub enum DecodeError {
29         /// Unknown realm byte in an OnionHopData packet
30         UnknownRealmByte,
31         /// Failed to decode a public key (ie it's invalid)
32         BadPublicKey,
33         /// Failed to decode a signature (ie it's invalid)
34         BadSignature,
35         /// Value expected to be text wasn't decodable as text
36         BadText,
37         /// Buffer too short
38         ShortRead,
39         /// node_announcement included more than one address of a given type!
40         ExtraAddressesPerType,
41         /// A length descriptor in the packet didn't describe the later data correctly
42         /// (currently only generated in node_announcement)
43         BadLengthDescriptor,
44 }
45 pub trait MsgDecodable: Sized {
46         fn decode(v: &[u8]) -> Result<Self, DecodeError>;
47 }
48
49 /// Tracks localfeatures which are only in init messages
50 #[derive(Clone, PartialEq)]
51 pub struct LocalFeatures {
52         flags: Vec<u8>,
53 }
54
55 impl LocalFeatures {
56         pub fn new() -> LocalFeatures {
57                 LocalFeatures {
58                         flags: Vec::new(),
59                 }
60         }
61
62         pub fn supports_data_loss_protect(&self) -> bool {
63                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
64         }
65         pub fn requires_data_loss_protect(&self) -> bool {
66                 self.flags.len() > 0 && (self.flags[0] & 1) != 0
67         }
68
69         pub fn initial_routing_sync(&self) -> bool {
70                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
71         }
72         pub fn set_initial_routing_sync(&mut self) {
73                 if self.flags.len() == 0 {
74                         self.flags.resize(1, 1 << 3);
75                 } else {
76                         self.flags[0] |= 1 << 3;
77                 }
78         }
79
80         pub fn supports_upfront_shutdown_script(&self) -> bool {
81                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
82         }
83         pub fn requires_upfront_shutdown_script(&self) -> bool {
84                 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
85         }
86
87         pub fn requires_unknown_bits(&self) -> bool {
88                 for (idx, &byte) in self.flags.iter().enumerate() {
89                         if idx != 0 && (byte & 0x55) != 0 {
90                                 return true;
91                         } else if idx == 0 && (byte & 0x14) != 0 {
92                                 return true;
93                         }
94                 }
95                 return false;
96         }
97
98         pub fn supports_unknown_bits(&self) -> bool {
99                 for (idx, &byte) in self.flags.iter().enumerate() {
100                         if idx != 0 && byte != 0 {
101                                 return true;
102                         } else if idx == 0 && (byte & 0xc4) != 0 {
103                                 return true;
104                         }
105                 }
106                 return false;
107         }
108 }
109
110 /// Tracks globalfeatures which are in init messages and routing announcements
111 #[derive(Clone, PartialEq)]
112 pub struct GlobalFeatures {
113         flags: Vec<u8>,
114 }
115
116 impl GlobalFeatures {
117         pub fn new() -> GlobalFeatures {
118                 GlobalFeatures {
119                         flags: Vec::new(),
120                 }
121         }
122
123         pub fn requires_unknown_bits(&self) -> bool {
124                 for &byte in self.flags.iter() {
125                         if (byte & 0x55) != 0 {
126                                 return true;
127                         }
128                 }
129                 return false;
130         }
131
132         pub fn supports_unknown_bits(&self) -> bool {
133                 for &byte in self.flags.iter() {
134                         if byte != 0 {
135                                 return true;
136                         }
137                 }
138                 return false;
139         }
140 }
141
142 pub struct Init {
143         pub global_features: GlobalFeatures,
144         pub local_features: LocalFeatures,
145 }
146
147 pub struct ErrorMessage {
148         pub channel_id: [u8; 32],
149         pub data: String,
150 }
151
152 pub struct Ping {
153         pub ponglen: u16,
154         pub byteslen: u16,
155 }
156
157 pub struct Pong {
158         pub byteslen: u16,
159 }
160
161 pub struct OpenChannel {
162         pub chain_hash: Sha256dHash,
163         pub temporary_channel_id: [u8; 32],
164         pub funding_satoshis: u64,
165         pub push_msat: u64,
166         pub dust_limit_satoshis: u64,
167         pub max_htlc_value_in_flight_msat: u64,
168         pub channel_reserve_satoshis: u64,
169         pub htlc_minimum_msat: u64,
170         pub feerate_per_kw: u32,
171         pub to_self_delay: u16,
172         pub max_accepted_htlcs: u16,
173         pub funding_pubkey: PublicKey,
174         pub revocation_basepoint: PublicKey,
175         pub payment_basepoint: PublicKey,
176         pub delayed_payment_basepoint: PublicKey,
177         pub htlc_basepoint: PublicKey,
178         pub first_per_commitment_point: PublicKey,
179         pub channel_flags: u8,
180         pub shutdown_scriptpubkey: Option<Script>,
181 }
182
183 pub struct AcceptChannel {
184         pub temporary_channel_id: [u8; 32],
185         pub dust_limit_satoshis: u64,
186         pub max_htlc_value_in_flight_msat: u64,
187         pub channel_reserve_satoshis: u64,
188         pub htlc_minimum_msat: u64,
189         pub minimum_depth: u32,
190         pub to_self_delay: u16,
191         pub max_accepted_htlcs: u16,
192         pub funding_pubkey: PublicKey,
193         pub revocation_basepoint: PublicKey,
194         pub payment_basepoint: PublicKey,
195         pub delayed_payment_basepoint: PublicKey,
196         pub htlc_basepoint: PublicKey,
197         pub first_per_commitment_point: PublicKey,
198         pub shutdown_scriptpubkey: Option<Script>,
199 }
200
201 pub struct FundingCreated {
202         pub temporary_channel_id: [u8; 32],
203         pub funding_txid: Sha256dHash,
204         pub funding_output_index: u16,
205         pub signature: Signature,
206 }
207
208 pub struct FundingSigned {
209         pub channel_id: [u8; 32],
210         pub signature: Signature,
211 }
212
213 pub struct FundingLocked {
214         pub channel_id: [u8; 32],
215         pub next_per_commitment_point: PublicKey,
216 }
217
218 pub struct Shutdown {
219         pub channel_id: [u8; 32],
220         pub scriptpubkey: Script,
221 }
222
223 pub struct ClosingSigned {
224         pub channel_id: [u8; 32],
225         pub fee_satoshis: u64,
226         pub signature: Signature,
227 }
228
229 #[derive(Clone)]
230 pub struct UpdateAddHTLC {
231         pub channel_id: [u8; 32],
232         pub htlc_id: u64,
233         pub amount_msat: u64,
234         pub payment_hash: [u8; 32],
235         pub cltv_expiry: u32,
236         pub onion_routing_packet: OnionPacket,
237 }
238
239 #[derive(Clone)]
240 pub struct UpdateFulfillHTLC {
241         pub channel_id: [u8; 32],
242         pub htlc_id: u64,
243         pub payment_preimage: [u8; 32],
244 }
245
246 #[derive(Clone)]
247 pub struct UpdateFailHTLC {
248         pub channel_id: [u8; 32],
249         pub htlc_id: u64,
250         pub reason: OnionErrorPacket,
251 }
252
253 #[derive(Clone)]
254 pub struct UpdateFailMalformedHTLC {
255         pub channel_id: [u8; 32],
256         pub htlc_id: u64,
257         pub sha256_of_onion: [u8; 32],
258         pub failure_code: u16,
259 }
260
261 #[derive(Clone)]
262 pub struct CommitmentSigned {
263         pub channel_id: [u8; 32],
264         pub signature: Signature,
265         pub htlc_signatures: Vec<Signature>,
266 }
267
268 pub struct RevokeAndACK {
269         pub channel_id: [u8; 32],
270         pub per_commitment_secret: [u8; 32],
271         pub next_per_commitment_point: PublicKey,
272 }
273
274 pub struct UpdateFee {
275         pub channel_id: [u8; 32],
276         pub feerate_per_kw: u32,
277 }
278
279 pub struct ChannelReestablish {
280         pub channel_id: [u8; 32],
281         pub next_local_commitment_number: u64,
282         pub next_remote_commitment_number: u64,
283         pub your_last_per_commitment_secret: Option<[u8; 32]>,
284         pub my_current_per_commitment_point: Option<PublicKey>,
285 }
286
287 #[derive(Clone)]
288 pub struct AnnouncementSignatures {
289         pub channel_id: [u8; 32],
290         pub short_channel_id: u64,
291         pub node_signature: Signature,
292         pub bitcoin_signature: Signature,
293 }
294
295 #[derive(Clone)]
296 pub enum NetAddress {
297         IPv4 {
298                 addr: [u8; 4],
299                 port: u16,
300         },
301         IPv6 {
302                 addr: [u8; 16],
303                 port: u16,
304         },
305         OnionV2 {
306                 addr: [u8; 10],
307                 port: u16,
308         },
309         OnionV3 {
310                 ed25519_pubkey: [u8; 32],
311                 checksum: u16,
312                 version: u8,
313                 port: u16,
314         },
315 }
316 impl NetAddress {
317         fn get_id(&self) -> u8 {
318                 match self {
319                         &NetAddress::IPv4 {..} => { 1 },
320                         &NetAddress::IPv6 {..} => { 2 },
321                         &NetAddress::OnionV2 {..} => { 3 },
322                         &NetAddress::OnionV3 {..} => { 4 },
323                 }
324         }
325 }
326
327 pub struct UnsignedNodeAnnouncement {
328         pub features: GlobalFeatures,
329         pub timestamp: u32,
330         pub node_id: PublicKey,
331         pub rgb: [u8; 3],
332         pub alias: [u8; 32],
333         /// List of addresses on which this node is reachable. Note that you may only have up to one
334         /// address of each type, if you have more, they may be silently discarded or we may panic!
335         pub addresses: Vec<NetAddress>,
336 }
337 pub struct NodeAnnouncement {
338         pub signature: Signature,
339         pub contents: UnsignedNodeAnnouncement,
340 }
341
342 #[derive(PartialEq, Clone)]
343 pub struct UnsignedChannelAnnouncement {
344         pub features: GlobalFeatures,
345         pub chain_hash: Sha256dHash,
346         pub short_channel_id: u64,
347         pub node_id_1: PublicKey,
348         pub node_id_2: PublicKey,
349         pub bitcoin_key_1: PublicKey,
350         pub bitcoin_key_2: PublicKey,
351 }
352 #[derive(PartialEq, Clone)]
353 pub struct ChannelAnnouncement {
354         pub node_signature_1: Signature,
355         pub node_signature_2: Signature,
356         pub bitcoin_signature_1: Signature,
357         pub bitcoin_signature_2: Signature,
358         pub contents: UnsignedChannelAnnouncement,
359 }
360
361 #[derive(PartialEq, Clone)]
362 pub struct UnsignedChannelUpdate {
363         pub chain_hash: Sha256dHash,
364         pub short_channel_id: u64,
365         pub timestamp: u32,
366         pub flags: u16,
367         pub cltv_expiry_delta: u16,
368         pub htlc_minimum_msat: u64,
369         pub fee_base_msat: u32,
370         pub fee_proportional_millionths: u32,
371 }
372 #[derive(PartialEq, Clone)]
373 pub struct ChannelUpdate {
374         pub signature: Signature,
375         pub contents: UnsignedChannelUpdate,
376 }
377
378 /// Used to put an error message in a HandleError
379 pub enum ErrorAction {
380         /// The peer took some action which made us think they were useless. Disconnect them.
381         DisconnectPeer {
382                 msg: Option<ErrorMessage>
383         },
384         /// The peer did something harmless that we weren't able to process, just log and ignore
385         IgnoreError,
386         /// The peer did something incorrect. Tell them.
387         SendErrorMessage {
388                 msg: ErrorMessage
389         },
390 }
391
392 pub struct HandleError { //TODO: rename me
393         pub err: &'static str,
394         pub action: Option<ErrorAction>, //TODO: Make this required
395 }
396
397 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
398 /// transaction updates if they were pending.
399 pub struct CommitmentUpdate {
400         pub update_add_htlcs: Vec<UpdateAddHTLC>,
401         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
402         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
403         pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
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         // Error conditions:
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         fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
452 }
453
454 pub trait RoutingMessageHandler : Send + Sync {
455         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
456         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
457         /// or returning an Err otherwise.
458         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
459         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
460         fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
461 }
462
463 pub struct OnionRealm0HopData {
464         pub short_channel_id: u64,
465         pub amt_to_forward: u64,
466         pub outgoing_cltv_value: u32,
467         // 12 bytes of 0-padding
468 }
469
470 pub struct OnionHopData {
471         pub realm: u8,
472         pub data: OnionRealm0HopData,
473         pub hmac: [u8; 32],
474 }
475 unsafe impl internal_traits::NoDealloc for OnionHopData{}
476
477 #[derive(Clone)]
478 pub struct OnionPacket {
479         pub version: u8,
480         /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
481         /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
482         /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
483         pub public_key: Result<PublicKey, secp256k1::Error>,
484         pub hop_data: [u8; 20*65],
485         pub hmac: [u8; 32],
486 }
487
488 pub struct DecodedOnionErrorPacket {
489         pub hmac: [u8; 32],
490         pub failuremsg: Vec<u8>,
491         pub pad: Vec<u8>,
492 }
493
494 #[derive(Clone)]
495 pub struct OnionErrorPacket {
496         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
497         // (TODO) We limit it in decode to much lower...
498         pub data: Vec<u8>,
499 }
500
501 impl Error for DecodeError {
502         fn description(&self) -> &str {
503                 match *self {
504                         DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
505                         DecodeError::BadPublicKey => "Invalid public key in packet",
506                         DecodeError::BadSignature => "Invalid signature in packet",
507                         DecodeError::BadText => "Invalid text in packet",
508                         DecodeError::ShortRead => "Packet extended beyond the provided bytes",
509                         DecodeError::ExtraAddressesPerType => "More than one address of a single type",
510                         DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
511                 }
512         }
513 }
514 impl fmt::Display for DecodeError {
515         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516                 f.write_str(self.description())
517         }
518 }
519
520 impl fmt::Debug for HandleError {
521         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522                 f.write_str(self.err)
523         }
524 }
525
526 macro_rules! secp_pubkey {
527         ( $ctx: expr, $slice: expr ) => {
528                 match PublicKey::from_slice($ctx, $slice) {
529                         Ok(key) => key,
530                         Err(_) => return Err(DecodeError::BadPublicKey)
531                 }
532         };
533 }
534
535 macro_rules! secp_signature {
536         ( $ctx: expr, $slice: expr ) => {
537                 match Signature::from_compact($ctx, $slice) {
538                         Ok(sig) => sig,
539                         Err(_) => return Err(DecodeError::BadSignature)
540                 }
541         };
542 }
543
544 impl MsgDecodable for LocalFeatures {
545         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
546                 if v.len() < 2 { return Err(DecodeError::ShortRead); }
547                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
548                 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
549                 let mut flags = Vec::with_capacity(len);
550                 flags.extend_from_slice(&v[2..2 + len]);
551                 Ok(Self {
552                         flags: flags
553                 })
554         }
555 }
556 impl MsgEncodable for LocalFeatures {
557         fn encode(&self) -> Vec<u8> {
558                 let mut res = Vec::with_capacity(self.flags.len() + 2);
559                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
560                 res.extend_from_slice(&self.flags[..]);
561                 res
562         }
563         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
564 }
565
566 impl MsgDecodable for GlobalFeatures {
567         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
568                 if v.len() < 2 { return Err(DecodeError::ShortRead); }
569                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
570                 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
571                 let mut flags = Vec::with_capacity(len);
572                 flags.extend_from_slice(&v[2..2 + len]);
573                 Ok(Self {
574                         flags: flags
575                 })
576         }
577 }
578 impl MsgEncodable for GlobalFeatures {
579         fn encode(&self) -> Vec<u8> {
580                 let mut res = Vec::with_capacity(self.flags.len() + 2);
581                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
582                 res.extend_from_slice(&self.flags[..]);
583                 res
584         }
585         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
586 }
587
588 impl MsgDecodable for Init {
589         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
590                 let global_features = GlobalFeatures::decode(v)?;
591                 if v.len() < global_features.flags.len() + 4 {
592                         return Err(DecodeError::ShortRead);
593                 }
594                 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
595                 Ok(Self {
596                         global_features: global_features,
597                         local_features: local_features,
598                 })
599         }
600 }
601 impl MsgEncodable for Init {
602         fn encode(&self) -> Vec<u8> {
603                 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
604                 res.extend_from_slice(&self.global_features.encode()[..]);
605                 res.extend_from_slice(&self.local_features.encode()[..]);
606                 res
607         }
608 }
609
610 impl MsgDecodable for Ping {
611         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
612                 if v.len() < 4 {
613                         return Err(DecodeError::ShortRead);
614                 }
615                 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
616                 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
617                 if v.len() < 4 + byteslen as usize {
618                         return Err(DecodeError::ShortRead);
619                 }
620                 Ok(Self {
621                         ponglen,
622                         byteslen,
623                 })
624         }
625 }
626 impl MsgEncodable for Ping {
627         fn encode(&self) -> Vec<u8> {
628                 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
629                 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
630                 res.resize(2 + self.byteslen as usize, 0);
631                 res
632         }
633 }
634
635 impl MsgDecodable for Pong {
636         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
637                 if v.len() < 2 {
638                         return Err(DecodeError::ShortRead);
639                 }
640                 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
641                 if v.len() < 2 + byteslen as usize {
642                         return Err(DecodeError::ShortRead);
643                 }
644                 Ok(Self {
645                         byteslen
646                 })
647         }
648 }
649 impl MsgEncodable for Pong {
650         fn encode(&self) -> Vec<u8> {
651                 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
652                 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
653                 res.resize(2 + self.byteslen as usize, 0);
654                 res
655         }
656 }
657
658 impl MsgDecodable for OpenChannel {
659         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
660                 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
661                         return Err(DecodeError::ShortRead);
662                 }
663                 let ctx = Secp256k1::without_caps();
664
665                 let mut shutdown_scriptpubkey = None;
666                 if v.len() >= 321 {
667                         let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
668                         if v.len() < 321+len {
669                                 return Err(DecodeError::ShortRead);
670                         }
671                         shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
672                 }
673
674                 Ok(OpenChannel {
675                         chain_hash: deserialize(&v[0..32]).unwrap(),
676                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
677                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
678                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
679                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
680                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
681                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
682                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
683                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
684                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
685                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
686                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
687                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
688                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
689                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
690                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
691                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
692                         channel_flags: v[318],
693                         shutdown_scriptpubkey: shutdown_scriptpubkey
694                 })
695         }
696 }
697 impl MsgEncodable for OpenChannel {
698         fn encode(&self) -> Vec<u8> {
699                 let mut res = match &self.shutdown_scriptpubkey {
700                         &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
701                         &None => Vec::with_capacity(319),
702                 };
703                 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
704                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
705                 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
706                 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
707                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
708                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
709                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
710                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
711                 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
712                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
713                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
714                 res.extend_from_slice(&self.funding_pubkey.serialize());
715                 res.extend_from_slice(&self.revocation_basepoint.serialize());
716                 res.extend_from_slice(&self.payment_basepoint.serialize());
717                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
718                 res.extend_from_slice(&self.htlc_basepoint.serialize());
719                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
720                 res.push(self.channel_flags);
721                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
722                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
723                         res.extend_from_slice(&script[..]);
724                 }
725                 res
726         }
727 }
728
729 impl MsgDecodable for AcceptChannel {
730         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
731                 if v.len() < 32+4*8+4+2*2+6*33 {
732                         return Err(DecodeError::ShortRead);
733                 }
734                 let ctx = Secp256k1::without_caps();
735
736                 let mut shutdown_scriptpubkey = None;
737                 if v.len() >= 272 {
738                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
739                         if v.len() < 272+len {
740                                 return Err(DecodeError::ShortRead);
741                         }
742                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
743                 }
744
745                 let mut temporary_channel_id = [0; 32];
746                 temporary_channel_id[..].copy_from_slice(&v[0..32]);
747                 Ok(Self {
748                         temporary_channel_id,
749                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
750                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
751                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
752                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
753                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
754                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
755                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
756                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
757                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
758                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
759                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
760                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
761                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
762                         shutdown_scriptpubkey: shutdown_scriptpubkey
763                 })
764         }
765 }
766 impl MsgEncodable for AcceptChannel {
767         fn encode(&self) -> Vec<u8> {
768                 let mut res = match &self.shutdown_scriptpubkey {
769                         &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
770                         &None => Vec::with_capacity(270),
771                 };
772                 res.extend_from_slice(&self.temporary_channel_id);
773                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
774                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
775                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
776                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
777                 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
778                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
779                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
780                 res.extend_from_slice(&self.funding_pubkey.serialize());
781                 res.extend_from_slice(&self.revocation_basepoint.serialize());
782                 res.extend_from_slice(&self.payment_basepoint.serialize());
783                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
784                 res.extend_from_slice(&self.htlc_basepoint.serialize());
785                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
786                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
787                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
788                         res.extend_from_slice(&script[..]);
789                 }
790                 res
791         }
792 }
793
794 impl MsgDecodable for FundingCreated {
795         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
796                 if v.len() < 32+32+2+64 {
797                         return Err(DecodeError::ShortRead);
798                 }
799                 let ctx = Secp256k1::without_caps();
800                 let mut temporary_channel_id = [0; 32];
801                 temporary_channel_id[..].copy_from_slice(&v[0..32]);
802                 Ok(Self {
803                         temporary_channel_id,
804                         funding_txid: deserialize(&v[32..64]).unwrap(),
805                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
806                         signature: secp_signature!(&ctx, &v[66..130]),
807                 })
808         }
809 }
810 impl MsgEncodable for FundingCreated {
811         fn encode(&self) -> Vec<u8> {
812                 let mut res = Vec::with_capacity(32+32+2+64);
813                 res.extend_from_slice(&self.temporary_channel_id);
814                 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
815                 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
816                 let secp_ctx = Secp256k1::without_caps();
817                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
818                 res
819         }
820 }
821
822 impl MsgDecodable for FundingSigned {
823         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
824                 if v.len() < 32+64 {
825                         return Err(DecodeError::ShortRead);
826                 }
827                 let ctx = Secp256k1::without_caps();
828                 let mut channel_id = [0; 32];
829                 channel_id[..].copy_from_slice(&v[0..32]);
830                 Ok(Self {
831                         channel_id,
832                         signature: secp_signature!(&ctx, &v[32..96]),
833                 })
834         }
835 }
836 impl MsgEncodable for FundingSigned {
837         fn encode(&self) -> Vec<u8> {
838                 let mut res = Vec::with_capacity(32+64);
839                 res.extend_from_slice(&self.channel_id);
840                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
841                 res
842         }
843 }
844
845 impl MsgDecodable for FundingLocked {
846         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
847                 if v.len() < 32+33 {
848                         return Err(DecodeError::ShortRead);
849                 }
850                 let ctx = Secp256k1::without_caps();
851                 let mut channel_id = [0; 32];
852                 channel_id[..].copy_from_slice(&v[0..32]);
853                 Ok(Self {
854                         channel_id,
855                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
856                 })
857         }
858 }
859 impl MsgEncodable for FundingLocked {
860         fn encode(&self) -> Vec<u8> {
861                 let mut res = Vec::with_capacity(32+33);
862                 res.extend_from_slice(&self.channel_id);
863                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
864                 res
865         }
866 }
867
868 impl MsgDecodable for Shutdown {
869         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
870                 if v.len() < 32 + 2 {
871                         return Err(DecodeError::ShortRead);
872                 }
873                 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
874                 if v.len() < 32 + 2 + scriptlen {
875                         return Err(DecodeError::ShortRead);
876                 }
877                 let mut channel_id = [0; 32];
878                 channel_id[..].copy_from_slice(&v[0..32]);
879                 Ok(Self {
880                         channel_id,
881                         scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
882                 })
883         }
884 }
885 impl MsgEncodable for Shutdown {
886         fn encode(&self) -> Vec<u8> {
887                 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
888                 res.extend_from_slice(&self.channel_id);
889                 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
890                 res.extend_from_slice(&self.scriptpubkey[..]);
891                 res
892         }
893 }
894
895 impl MsgDecodable for ClosingSigned {
896         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
897                 if v.len() < 32 + 8 + 64 {
898                         return Err(DecodeError::ShortRead);
899                 }
900                 let secp_ctx = Secp256k1::without_caps();
901                 let mut channel_id = [0; 32];
902                 channel_id[..].copy_from_slice(&v[0..32]);
903                 Ok(Self {
904                         channel_id,
905                         fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
906                         signature: secp_signature!(&secp_ctx, &v[40..104]),
907                 })
908         }
909 }
910 impl MsgEncodable for ClosingSigned {
911         fn encode(&self) -> Vec<u8> {
912                 let mut res = Vec::with_capacity(32+8+64);
913                 res.extend_from_slice(&self.channel_id);
914                 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
915                 let secp_ctx = Secp256k1::without_caps();
916                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
917                 res
918         }
919 }
920
921 impl MsgDecodable for UpdateAddHTLC {
922         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
923                 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
924                         return Err(DecodeError::ShortRead);
925                 }
926                 let mut channel_id = [0; 32];
927                 channel_id[..].copy_from_slice(&v[0..32]);
928                 let mut payment_hash = [0; 32];
929                 payment_hash.copy_from_slice(&v[48..80]);
930                 Ok(Self{
931                         channel_id,
932                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
933                         amount_msat: byte_utils::slice_to_be64(&v[40..48]),
934                         payment_hash,
935                         cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
936                         onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
937                 })
938         }
939 }
940 impl MsgEncodable for UpdateAddHTLC {
941         fn encode(&self) -> Vec<u8> {
942                 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
943                 res.extend_from_slice(&self.channel_id);
944                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
945                 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
946                 res.extend_from_slice(&self.payment_hash);
947                 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
948                 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
949                 res
950         }
951 }
952
953 impl MsgDecodable for UpdateFulfillHTLC {
954         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
955                 if v.len() < 32+8+32 {
956                         return Err(DecodeError::ShortRead);
957                 }
958                 let mut channel_id = [0; 32];
959                 channel_id[..].copy_from_slice(&v[0..32]);
960                 let mut payment_preimage = [0; 32];
961                 payment_preimage.copy_from_slice(&v[40..72]);
962                 Ok(Self{
963                         channel_id,
964                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
965                         payment_preimage,
966                 })
967         }
968 }
969 impl MsgEncodable for UpdateFulfillHTLC {
970         fn encode(&self) -> Vec<u8> {
971                 let mut res = Vec::with_capacity(32+8+32);
972                 res.extend_from_slice(&self.channel_id);
973                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
974                 res.extend_from_slice(&self.payment_preimage);
975                 res
976         }
977 }
978
979 impl MsgDecodable for UpdateFailHTLC {
980         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
981                 if v.len() < 32+8 {
982                         return Err(DecodeError::ShortRead);
983                 }
984                 let mut channel_id = [0; 32];
985                 channel_id[..].copy_from_slice(&v[0..32]);
986                 Ok(Self{
987                         channel_id,
988                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
989                         reason: OnionErrorPacket::decode(&v[40..])?,
990                 })
991         }
992 }
993 impl MsgEncodable for UpdateFailHTLC {
994         fn encode(&self) -> Vec<u8> {
995                 let reason = self.reason.encode();
996                 let mut res = Vec::with_capacity(32+8+reason.len());
997                 res.extend_from_slice(&self.channel_id);
998                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
999                 res.extend_from_slice(&reason[..]);
1000                 res
1001         }
1002 }
1003
1004 impl MsgDecodable for UpdateFailMalformedHTLC {
1005         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1006                 if v.len() < 32+8+32+2 {
1007                         return Err(DecodeError::ShortRead);
1008                 }
1009                 let mut channel_id = [0; 32];
1010                 channel_id[..].copy_from_slice(&v[0..32]);
1011                 let mut sha256_of_onion = [0; 32];
1012                 sha256_of_onion.copy_from_slice(&v[40..72]);
1013                 Ok(Self{
1014                         channel_id,
1015                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1016                         sha256_of_onion,
1017                         failure_code: byte_utils::slice_to_be16(&v[72..74]),
1018                 })
1019         }
1020 }
1021 impl MsgEncodable for UpdateFailMalformedHTLC {
1022         fn encode(&self) -> Vec<u8> {
1023                 let mut res = Vec::with_capacity(32+8+32+2);
1024                 res.extend_from_slice(&self.channel_id);
1025                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1026                 res.extend_from_slice(&self.sha256_of_onion);
1027                 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1028                 res
1029         }
1030 }
1031
1032 impl MsgDecodable for CommitmentSigned {
1033         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1034                 if v.len() < 32+64+2 {
1035                         return Err(DecodeError::ShortRead);
1036                 }
1037                 let mut channel_id = [0; 32];
1038                 channel_id[..].copy_from_slice(&v[0..32]);
1039
1040                 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1041                 if v.len() < 32+64+2+htlcs*64 {
1042                         return Err(DecodeError::ShortRead);
1043                 }
1044                 let mut htlc_signatures = Vec::with_capacity(htlcs);
1045                 let secp_ctx = Secp256k1::without_caps();
1046                 for i in 0..htlcs {
1047                         htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1048                 }
1049                 Ok(Self {
1050                         channel_id,
1051                         signature: secp_signature!(&secp_ctx, &v[32..96]),
1052                         htlc_signatures,
1053                 })
1054         }
1055 }
1056 impl MsgEncodable for CommitmentSigned {
1057         fn encode(&self) -> Vec<u8> {
1058                 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1059                 res.extend_from_slice(&self.channel_id);
1060                 let secp_ctx = Secp256k1::without_caps();
1061                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1062                 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1063                 for i in 0..self.htlc_signatures.len() {
1064                         res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1065                 }
1066                 res
1067         }
1068 }
1069
1070 impl MsgDecodable for RevokeAndACK {
1071         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1072                 if v.len() < 32+32+33 {
1073                         return Err(DecodeError::ShortRead);
1074                 }
1075                 let mut channel_id = [0; 32];
1076                 channel_id[..].copy_from_slice(&v[0..32]);
1077                 let mut per_commitment_secret = [0; 32];
1078                 per_commitment_secret.copy_from_slice(&v[32..64]);
1079                 let secp_ctx = Secp256k1::without_caps();
1080                 Ok(Self {
1081                         channel_id,
1082                         per_commitment_secret,
1083                         next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1084                 })
1085         }
1086 }
1087 impl MsgEncodable for RevokeAndACK {
1088         fn encode(&self) -> Vec<u8> {
1089                 let mut res = Vec::with_capacity(32+32+33);
1090                 res.extend_from_slice(&self.channel_id);
1091                 res.extend_from_slice(&self.per_commitment_secret);
1092                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1093                 res
1094         }
1095 }
1096
1097 impl MsgDecodable for UpdateFee {
1098         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1099                 if v.len() < 32+4 {
1100                         return Err(DecodeError::ShortRead);
1101                 }
1102                 let mut channel_id = [0; 32];
1103                 channel_id[..].copy_from_slice(&v[0..32]);
1104                 Ok(Self {
1105                         channel_id,
1106                         feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1107                 })
1108         }
1109 }
1110 impl MsgEncodable for UpdateFee {
1111         fn encode(&self) -> Vec<u8> {
1112                 let mut res = Vec::with_capacity(32+4);
1113                 res.extend_from_slice(&self.channel_id);
1114                 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1115                 res
1116         }
1117 }
1118
1119 impl MsgDecodable for ChannelReestablish {
1120         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1121                 if v.len() < 32+2*8 {
1122                         return Err(DecodeError::ShortRead);
1123                 }
1124
1125                 let (your_last_per_commitment_secret, my_current_per_commitment_point) = if v.len() > 32+2*8 {
1126                         if v.len() < 32+2*8 + 33+32 {
1127                                 return Err(DecodeError::ShortRead);
1128                         }
1129                         let mut inner_array = [0; 32];
1130                         inner_array.copy_from_slice(&v[48..48+32]);
1131                         (Some(inner_array), {
1132                                 let ctx = Secp256k1::without_caps();
1133                                 Some(secp_pubkey!(&ctx, &v[48+32..48+32+33]))
1134                         })
1135                 } else { (None, None) };
1136
1137                 Ok(Self {
1138                         channel_id: deserialize(&v[0..32]).unwrap(),
1139                         next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1140                         next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1141                         your_last_per_commitment_secret: your_last_per_commitment_secret,
1142                         my_current_per_commitment_point: my_current_per_commitment_point,
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*8+33+32 } else { 32+2*8 });
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                         res.extend_from_slice(&self.my_current_per_commitment_point.expect("my_current_per_commitment_point should have been filled").serialize());
1157                 }
1158                 res
1159         }
1160 }
1161
1162 impl MsgDecodable for AnnouncementSignatures {
1163         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1164                 if v.len() < 32+8+64*2 {
1165                         return Err(DecodeError::ShortRead);
1166                 }
1167                 let secp_ctx = Secp256k1::without_caps();
1168                 let mut channel_id = [0; 32];
1169                 channel_id[..].copy_from_slice(&v[0..32]);
1170                 Ok(Self {
1171                         channel_id,
1172                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1173                         node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1174                         bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1175                 })
1176         }
1177 }
1178 impl MsgEncodable for AnnouncementSignatures {
1179         fn encode(&self) -> Vec<u8> {
1180                 let mut res = Vec::with_capacity(32+8+64*2);
1181                 res.extend_from_slice(&self.channel_id);
1182                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1183                 let secp_ctx = Secp256k1::without_caps();
1184                 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1185                 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1186                 res
1187         }
1188 }
1189
1190 impl MsgDecodable for UnsignedNodeAnnouncement {
1191         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1192                 let features = GlobalFeatures::decode(&v[..])?;
1193                 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1194                         return Err(DecodeError::ShortRead);
1195                 }
1196                 let start = features.encoded_len();
1197
1198                 let mut rgb = [0; 3];
1199                 rgb.copy_from_slice(&v[start + 37..start + 40]);
1200
1201                 let mut alias = [0; 32];
1202                 alias.copy_from_slice(&v[start + 40..start + 72]);
1203
1204                 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1205                 if v.len() < start + 74 + addrlen {
1206                         return Err(DecodeError::ShortRead);
1207                 }
1208                 let addr_read_limit = start + 74 + addrlen;
1209
1210                 let mut addresses = Vec::with_capacity(4);
1211                 let mut read_pos = start + 74;
1212                 loop {
1213                         if addr_read_limit <= read_pos { break; }
1214                         match v[read_pos] {
1215                                 0 => { read_pos += 1; },
1216                                 1 => {
1217                                         if addresses.len() > 0 {
1218                                                 return Err(DecodeError::ExtraAddressesPerType);
1219                                         }
1220                                         if addr_read_limit < read_pos + 1 + 6 {
1221                                                 return Err(DecodeError::BadLengthDescriptor);
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 addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1233                                                 return Err(DecodeError::ExtraAddressesPerType);
1234                                         }
1235                                         if addr_read_limit < read_pos + 1 + 18 {
1236                                                 return Err(DecodeError::BadLengthDescriptor);
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 addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1248                                                 return Err(DecodeError::ExtraAddressesPerType);
1249                                         }
1250                                         if addr_read_limit < read_pos + 1 + 12 {
1251                                                 return Err(DecodeError::BadLengthDescriptor);
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 addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1263                                                 return Err(DecodeError::ExtraAddressesPerType);
1264                                         }
1265                                         if addr_read_limit < read_pos + 1 + 37 {
1266                                                 return Err(DecodeError::BadLengthDescriptor);
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::ShortRead);
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::ShortRead);
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::ShortRead);
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::ShortRead);
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::ShortRead);
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::ShortRead);
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::ShortRead);
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::ShortRead);
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: PublicKey::from_slice(&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                 match self.public_key {
1551                         Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1552                         Err(_) => res.extend_from_slice(&[0; 33]),
1553                 }
1554                 res.extend_from_slice(&self.hop_data);
1555                 res.extend_from_slice(&self.hmac);
1556                 res
1557         }
1558 }
1559
1560 impl MsgDecodable for DecodedOnionErrorPacket {
1561         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1562                 if v.len() < 32 + 4 {
1563                         return Err(DecodeError::ShortRead);
1564                 }
1565                 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1566                 if v.len() < 32 + 4 + failuremsg_len {
1567                         return Err(DecodeError::ShortRead);
1568                 }
1569                 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1570                 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1571                         return Err(DecodeError::ShortRead);
1572                 }
1573
1574                 let mut hmac = [0; 32];
1575                 hmac.copy_from_slice(&v[0..32]);
1576                 Ok(Self {
1577                         hmac,
1578                         failuremsg: v[34..34 + failuremsg_len].to_vec(),
1579                         pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1580                 })
1581         }
1582 }
1583 impl MsgEncodable for DecodedOnionErrorPacket {
1584         fn encode(&self) -> Vec<u8> {
1585                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1586                 res.extend_from_slice(&self.hmac);
1587                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1588                 res.extend_from_slice(&self.failuremsg);
1589                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1590                 res.extend_from_slice(&self.pad);
1591                 res
1592         }
1593 }
1594
1595 impl MsgDecodable for OnionErrorPacket {
1596         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1597                 if v.len() < 2 {
1598                         return Err(DecodeError::ShortRead);
1599                 }
1600                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1601                 if v.len() < 2 + len {
1602                         return Err(DecodeError::ShortRead);
1603                 }
1604                 Ok(Self {
1605                         data: v[2..len+2].to_vec(),
1606                 })
1607         }
1608 }
1609 impl MsgEncodable for OnionErrorPacket {
1610         fn encode(&self) -> Vec<u8> {
1611                 let mut res = Vec::with_capacity(2 + self.data.len());
1612                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1613                 res.extend_from_slice(&self.data);
1614                 res
1615         }
1616 }
1617
1618 impl MsgEncodable for ErrorMessage {
1619         fn encode(&self) -> Vec<u8> {
1620                 let mut res = Vec::with_capacity(34 + self.data.len());
1621                 res.extend_from_slice(&self.channel_id);
1622                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1623                 res.extend_from_slice(&self.data.as_bytes());
1624                 res
1625         }
1626 }
1627 impl MsgDecodable for ErrorMessage {
1628         fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1629                 if v.len() < 34 {
1630                         return Err(DecodeError::ShortRead);
1631                 }
1632                 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1633                 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1634                 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1635                         Ok(s) => s,
1636                         Err(_) => return Err(DecodeError::BadText),
1637                 };
1638                 let mut channel_id = [0; 32];
1639                 channel_id[..].copy_from_slice(&v[0..32]);
1640                 Ok(Self {
1641                         channel_id,
1642                         data,
1643                 })
1644         }
1645 }
1646
1647 #[cfg(test)]
1648 mod tests {
1649         use hex;
1650         use ln::msgs::MsgEncodable;
1651         use ln::msgs;
1652         use secp256k1::key::{PublicKey,SecretKey};
1653         use secp256k1::Secp256k1;
1654
1655         #[test]
1656         fn encoding_channel_reestablish_no_secret() {
1657                 let public_key = {
1658                         let secp_ctx = Secp256k1::new();
1659                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1660                 };
1661
1662                 let cr = msgs::ChannelReestablish {
1663                         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],
1664                         next_local_commitment_number: 3,
1665                         next_remote_commitment_number: 4,
1666                         your_last_per_commitment_secret: None,
1667                         my_current_per_commitment_point: None,
1668                 };
1669
1670                 let encoded_value = cr.encode();
1671                 assert_eq!(
1672                         encoded_value,
1673                         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]
1674                 );
1675         }
1676
1677         #[test]
1678         fn encoding_channel_reestablish_with_secret() {
1679                 let public_key = {
1680                         let secp_ctx = Secp256k1::new();
1681                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1682                 };
1683
1684                 let cr = msgs::ChannelReestablish {
1685                         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],
1686                         next_local_commitment_number: 3,
1687                         next_remote_commitment_number: 4,
1688                         your_last_per_commitment_secret: Some([9; 32]),
1689                         my_current_per_commitment_point: Some(public_key),
1690                 };
1691
1692                 let encoded_value = cr.encode();
1693                 assert_eq!(
1694                         encoded_value,
1695                         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]
1696                 );
1697         }
1698 }