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