Return a malformed HTLC message when ephemeral pubkey is garbage
[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: 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+33 {
1122                         return Err(DecodeError::ShortRead);
1123                 }
1124
1125                 let your_last_per_commitment_secret = if v.len() > 32+2*8+33 {
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                 } else { None };
1133
1134                 let option_size = match &your_last_per_commitment_secret {
1135                         &Some(ref _ary) => 32,
1136                         &None => 0,
1137                 };
1138                 Ok(Self {
1139                         channel_id: deserialize(&v[0..32]).unwrap(),
1140                         next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1141                         next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1142                         your_last_per_commitment_secret: your_last_per_commitment_secret,
1143                         my_current_per_commitment_point: {
1144                                 let ctx = Secp256k1::without_caps();
1145                                 secp_pubkey!(&ctx, &v[48+option_size..48+option_size+33])
1146                         }
1147                 })
1148         }
1149 }
1150 impl MsgEncodable for ChannelReestablish {
1151         fn encode(&self) -> Vec<u8> {
1152                 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 });
1153
1154                 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1155                 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1156                 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1157
1158                 if let &Some(ref ary) = &self.your_last_per_commitment_secret {
1159                         res.extend_from_slice(&ary[..]);
1160                 }
1161
1162                 res.extend_from_slice(&self.my_current_per_commitment_point.serialize());
1163                 res
1164         }
1165 }
1166
1167 impl MsgDecodable for AnnouncementSignatures {
1168         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1169                 if v.len() < 32+8+64*2 {
1170                         return Err(DecodeError::ShortRead);
1171                 }
1172                 let secp_ctx = Secp256k1::without_caps();
1173                 let mut channel_id = [0; 32];
1174                 channel_id[..].copy_from_slice(&v[0..32]);
1175                 Ok(Self {
1176                         channel_id,
1177                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1178                         node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1179                         bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1180                 })
1181         }
1182 }
1183 impl MsgEncodable for AnnouncementSignatures {
1184         fn encode(&self) -> Vec<u8> {
1185                 let mut res = Vec::with_capacity(32+8+64*2);
1186                 res.extend_from_slice(&self.channel_id);
1187                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1188                 let secp_ctx = Secp256k1::without_caps();
1189                 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1190                 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1191                 res
1192         }
1193 }
1194
1195 impl MsgDecodable for UnsignedNodeAnnouncement {
1196         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1197                 let features = GlobalFeatures::decode(&v[..])?;
1198                 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1199                         return Err(DecodeError::ShortRead);
1200                 }
1201                 let start = features.encoded_len();
1202
1203                 let mut rgb = [0; 3];
1204                 rgb.copy_from_slice(&v[start + 37..start + 40]);
1205
1206                 let mut alias = [0; 32];
1207                 alias.copy_from_slice(&v[start + 40..start + 72]);
1208
1209                 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1210                 if v.len() < start + 74 + addrlen {
1211                         return Err(DecodeError::ShortRead);
1212                 }
1213                 let addr_read_limit = start + 74 + addrlen;
1214
1215                 let mut addresses = Vec::with_capacity(4);
1216                 let mut read_pos = start + 74;
1217                 loop {
1218                         if addr_read_limit <= read_pos { break; }
1219                         match v[read_pos] {
1220                                 0 => { read_pos += 1; },
1221                                 1 => {
1222                                         if addresses.len() > 0 {
1223                                                 return Err(DecodeError::ExtraAddressesPerType);
1224                                         }
1225                                         if addr_read_limit < read_pos + 1 + 6 {
1226                                                 return Err(DecodeError::BadLengthDescriptor);
1227                                         }
1228                                         let mut addr = [0; 4];
1229                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1230                                         addresses.push(NetAddress::IPv4 {
1231                                                 addr,
1232                                                 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1233                                         });
1234                                         read_pos += 1 + 6;
1235                                 },
1236                                 2 => {
1237                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1238                                                 return Err(DecodeError::ExtraAddressesPerType);
1239                                         }
1240                                         if addr_read_limit < read_pos + 1 + 18 {
1241                                                 return Err(DecodeError::BadLengthDescriptor);
1242                                         }
1243                                         let mut addr = [0; 16];
1244                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1245                                         addresses.push(NetAddress::IPv6 {
1246                                                 addr,
1247                                                 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1248                                         });
1249                                         read_pos += 1 + 18;
1250                                 },
1251                                 3 => {
1252                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1253                                                 return Err(DecodeError::ExtraAddressesPerType);
1254                                         }
1255                                         if addr_read_limit < read_pos + 1 + 12 {
1256                                                 return Err(DecodeError::BadLengthDescriptor);
1257                                         }
1258                                         let mut addr = [0; 10];
1259                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1260                                         addresses.push(NetAddress::OnionV2 {
1261                                                 addr,
1262                                                 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1263                                         });
1264                                         read_pos += 1 + 12;
1265                                 },
1266                                 4 => {
1267                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1268                                                 return Err(DecodeError::ExtraAddressesPerType);
1269                                         }
1270                                         if addr_read_limit < read_pos + 1 + 37 {
1271                                                 return Err(DecodeError::BadLengthDescriptor);
1272                                         }
1273                                         let mut ed25519_pubkey = [0; 32];
1274                                         ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1275                                         addresses.push(NetAddress::OnionV3 {
1276                                                 ed25519_pubkey,
1277                                                 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1278                                                 version: v[read_pos + 35],
1279                                                 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1280                                         });
1281                                         read_pos += 1 + 37;
1282                                 },
1283                                 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1284                         }
1285                 }
1286
1287                 let secp_ctx = Secp256k1::without_caps();
1288                 Ok(Self {
1289                         features,
1290                         timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1291                         node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1292                         rgb,
1293                         alias,
1294                         addresses,
1295                 })
1296         }
1297 }
1298 impl MsgEncodable for UnsignedNodeAnnouncement {
1299         fn encode(&self) -> Vec<u8> {
1300                 let features = self.features.encode();
1301                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1302                 res.extend_from_slice(&features[..]);
1303                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1304                 res.extend_from_slice(&self.node_id.serialize());
1305                 res.extend_from_slice(&self.rgb);
1306                 res.extend_from_slice(&self.alias);
1307                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1308                 let mut addrs_to_encode = self.addresses.clone();
1309                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1310                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1311                 for addr in addrs_to_encode.iter() {
1312                         match addr {
1313                                 &NetAddress::IPv4{addr, port} => {
1314                                         addr_slice.push(1);
1315                                         addr_slice.extend_from_slice(&addr);
1316                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1317                                 },
1318                                 &NetAddress::IPv6{addr, port} => {
1319                                         addr_slice.push(2);
1320                                         addr_slice.extend_from_slice(&addr);
1321                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1322                                 },
1323                                 &NetAddress::OnionV2{addr, port} => {
1324                                         addr_slice.push(3);
1325                                         addr_slice.extend_from_slice(&addr);
1326                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1327                                 },
1328                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1329                                         addr_slice.push(4);
1330                                         addr_slice.extend_from_slice(&ed25519_pubkey);
1331                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1332                                         addr_slice.push(version);
1333                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1334                                 },
1335                         }
1336                 }
1337                 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1338                 res.extend_from_slice(&addr_slice[..]);
1339                 res
1340         }
1341 }
1342
1343 impl MsgDecodable for NodeAnnouncement {
1344         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1345                 if v.len() < 64 {
1346                         return Err(DecodeError::ShortRead);
1347                 }
1348                 let secp_ctx = Secp256k1::without_caps();
1349                 Ok(Self {
1350                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1351                         contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1352                 })
1353         }
1354 }
1355 impl MsgEncodable for NodeAnnouncement {
1356         fn encode(&self) -> Vec<u8> {
1357                 let contents = self.contents.encode();
1358                 let mut res = Vec::with_capacity(64 + contents.len());
1359                 let secp_ctx = Secp256k1::without_caps();
1360                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1361                 res.extend_from_slice(&contents);
1362                 res
1363         }
1364 }
1365
1366 impl MsgDecodable for UnsignedChannelAnnouncement {
1367         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1368                 let features = GlobalFeatures::decode(&v[..])?;
1369                 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1370                         return Err(DecodeError::ShortRead);
1371                 }
1372                 let start = features.encoded_len();
1373                 let secp_ctx = Secp256k1::without_caps();
1374                 Ok(Self {
1375                         features,
1376                         chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1377                         short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1378                         node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1379                         node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1380                         bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1381                         bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1382                 })
1383         }
1384 }
1385 impl MsgEncodable for UnsignedChannelAnnouncement {
1386         fn encode(&self) -> Vec<u8> {
1387                 let features = self.features.encode();
1388                 let mut res = Vec::with_capacity(172 + features.len());
1389                 res.extend_from_slice(&features[..]);
1390                 res.extend_from_slice(&self.chain_hash[..]);
1391                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1392                 res.extend_from_slice(&self.node_id_1.serialize());
1393                 res.extend_from_slice(&self.node_id_2.serialize());
1394                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1395                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1396                 res
1397         }
1398 }
1399
1400 impl MsgDecodable for ChannelAnnouncement {
1401         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1402                 if v.len() < 64*4 {
1403                         return Err(DecodeError::ShortRead);
1404                 }
1405                 let secp_ctx = Secp256k1::without_caps();
1406                 Ok(Self {
1407                         node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1408                         node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1409                         bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1410                         bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1411                         contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1412                 })
1413         }
1414 }
1415 impl MsgEncodable for ChannelAnnouncement {
1416         fn encode(&self) -> Vec<u8> {
1417                 let secp_ctx = Secp256k1::without_caps();
1418                 let contents = self.contents.encode();
1419                 let mut res = Vec::with_capacity(64 + contents.len());
1420                 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1421                 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1422                 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1423                 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1424                 res.extend_from_slice(&contents);
1425                 res
1426         }
1427 }
1428
1429 impl MsgDecodable for UnsignedChannelUpdate {
1430         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1431                 if v.len() < 32+8+4+2+2+8+4+4 {
1432                         return Err(DecodeError::ShortRead);
1433                 }
1434                 Ok(Self {
1435                         chain_hash: deserialize(&v[0..32]).unwrap(),
1436                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1437                         timestamp: byte_utils::slice_to_be32(&v[40..44]),
1438                         flags: byte_utils::slice_to_be16(&v[44..46]),
1439                         cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1440                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1441                         fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1442                         fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1443                 })
1444         }
1445 }
1446 impl MsgEncodable for UnsignedChannelUpdate {
1447         fn encode(&self) -> Vec<u8> {
1448                 let mut res = Vec::with_capacity(64);
1449                 res.extend_from_slice(&self.chain_hash[..]);
1450                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1451                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1452                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1453                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1454                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1455                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1456                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1457                 res
1458         }
1459 }
1460
1461 impl MsgDecodable for ChannelUpdate {
1462         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1463                 if v.len() < 128 {
1464                         return Err(DecodeError::ShortRead);
1465                 }
1466                 let secp_ctx = Secp256k1::without_caps();
1467                 Ok(Self {
1468                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1469                         contents: UnsignedChannelUpdate::decode(&v[64..])?,
1470                 })
1471         }
1472 }
1473 impl MsgEncodable for ChannelUpdate {
1474         fn encode(&self) -> Vec<u8> {
1475                 let mut res = Vec::with_capacity(128);
1476                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1477                 res.extend_from_slice(&self.contents.encode()[..]);
1478                 res
1479         }
1480 }
1481
1482 impl MsgDecodable for OnionRealm0HopData {
1483         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1484                 if v.len() < 32 {
1485                         return Err(DecodeError::ShortRead);
1486                 }
1487                 Ok(OnionRealm0HopData {
1488                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1489                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1490                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1491                 })
1492         }
1493 }
1494 impl MsgEncodable for OnionRealm0HopData {
1495         fn encode(&self) -> Vec<u8> {
1496                 let mut res = Vec::with_capacity(32);
1497                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1498                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1499                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1500                 res.resize(32, 0);
1501                 res
1502         }
1503 }
1504
1505 impl MsgDecodable for OnionHopData {
1506         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1507                 if v.len() < 65 {
1508                         return Err(DecodeError::ShortRead);
1509                 }
1510                 let realm = v[0];
1511                 if realm != 0 {
1512                         return Err(DecodeError::UnknownRealmByte);
1513                 }
1514                 let mut hmac = [0; 32];
1515                 hmac[..].copy_from_slice(&v[33..65]);
1516                 Ok(OnionHopData {
1517                         realm: realm,
1518                         data: OnionRealm0HopData::decode(&v[1..33])?,
1519                         hmac: hmac,
1520                 })
1521         }
1522 }
1523 impl MsgEncodable for OnionHopData {
1524         fn encode(&self) -> Vec<u8> {
1525                 let mut res = Vec::with_capacity(65);
1526                 res.push(self.realm);
1527                 res.extend_from_slice(&self.data.encode()[..]);
1528                 res.extend_from_slice(&self.hmac);
1529                 res
1530         }
1531 }
1532
1533 impl MsgDecodable for OnionPacket {
1534         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1535                 if v.len() < 1+33+20*65+32 {
1536                         return Err(DecodeError::ShortRead);
1537                 }
1538                 let mut hop_data = [0; 20*65];
1539                 hop_data.copy_from_slice(&v[34..1334]);
1540                 let mut hmac = [0; 32];
1541                 hmac.copy_from_slice(&v[1334..1366]);
1542                 let secp_ctx = Secp256k1::without_caps();
1543                 Ok(Self {
1544                         version: v[0],
1545                         public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1546                         hop_data,
1547                         hmac,
1548                 })
1549         }
1550 }
1551 impl MsgEncodable for OnionPacket {
1552         fn encode(&self) -> Vec<u8> {
1553                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1554                 res.push(self.version);
1555                 match self.public_key {
1556                         Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1557                         Err(_) => res.extend_from_slice(&[0; 33]),
1558                 }
1559                 res.extend_from_slice(&self.hop_data);
1560                 res.extend_from_slice(&self.hmac);
1561                 res
1562         }
1563 }
1564
1565 impl MsgDecodable for DecodedOnionErrorPacket {
1566         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1567                 if v.len() < 32 + 4 {
1568                         return Err(DecodeError::ShortRead);
1569                 }
1570                 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1571                 if v.len() < 32 + 4 + failuremsg_len {
1572                         return Err(DecodeError::ShortRead);
1573                 }
1574                 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1575                 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1576                         return Err(DecodeError::ShortRead);
1577                 }
1578
1579                 let mut hmac = [0; 32];
1580                 hmac.copy_from_slice(&v[0..32]);
1581                 Ok(Self {
1582                         hmac,
1583                         failuremsg: v[34..34 + failuremsg_len].to_vec(),
1584                         pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1585                 })
1586         }
1587 }
1588 impl MsgEncodable for DecodedOnionErrorPacket {
1589         fn encode(&self) -> Vec<u8> {
1590                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1591                 res.extend_from_slice(&self.hmac);
1592                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1593                 res.extend_from_slice(&self.failuremsg);
1594                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1595                 res.extend_from_slice(&self.pad);
1596                 res
1597         }
1598 }
1599
1600 impl MsgDecodable for OnionErrorPacket {
1601         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1602                 if v.len() < 2 {
1603                         return Err(DecodeError::ShortRead);
1604                 }
1605                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1606                 if v.len() < 2 + len {
1607                         return Err(DecodeError::ShortRead);
1608                 }
1609                 Ok(Self {
1610                         data: v[2..len+2].to_vec(),
1611                 })
1612         }
1613 }
1614 impl MsgEncodable for OnionErrorPacket {
1615         fn encode(&self) -> Vec<u8> {
1616                 let mut res = Vec::with_capacity(2 + self.data.len());
1617                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1618                 res.extend_from_slice(&self.data);
1619                 res
1620         }
1621 }
1622
1623 impl MsgEncodable for ErrorMessage {
1624         fn encode(&self) -> Vec<u8> {
1625                 let mut res = Vec::with_capacity(34 + self.data.len());
1626                 res.extend_from_slice(&self.channel_id);
1627                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1628                 res.extend_from_slice(&self.data.as_bytes());
1629                 res
1630         }
1631 }
1632 impl MsgDecodable for ErrorMessage {
1633         fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1634                 if v.len() < 34 {
1635                         return Err(DecodeError::ShortRead);
1636                 }
1637                 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1638                 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1639                 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1640                         Ok(s) => s,
1641                         Err(_) => return Err(DecodeError::BadText),
1642                 };
1643                 let mut channel_id = [0; 32];
1644                 channel_id[..].copy_from_slice(&v[0..32]);
1645                 Ok(Self {
1646                         channel_id,
1647                         data,
1648                 })
1649         }
1650 }
1651
1652 #[cfg(test)]
1653 mod tests {
1654         use hex;
1655         use ln::msgs::MsgEncodable;
1656         use ln::msgs;
1657         use secp256k1::key::{PublicKey,SecretKey};
1658         use secp256k1::Secp256k1;
1659
1660         #[test]
1661         fn encoding_channel_reestablish_no_secret() {
1662                 let public_key = {
1663                         let secp_ctx = Secp256k1::new();
1664                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1665                 };
1666
1667                 let cr = msgs::ChannelReestablish {
1668                         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],
1669                         next_local_commitment_number: 3,
1670                         next_remote_commitment_number: 4,
1671                         your_last_per_commitment_secret: None,
1672                         my_current_per_commitment_point: public_key,
1673                 };
1674
1675                 let encoded_value = cr.encode();
1676                 assert_eq!(
1677                         encoded_value,
1678                         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]
1679                 );
1680         }
1681
1682         #[test]
1683         fn encoding_channel_reestablish_with_secret() {
1684                 let public_key = {
1685                         let secp_ctx = Secp256k1::new();
1686                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1687                 };
1688
1689                 let cr = msgs::ChannelReestablish {
1690                         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],
1691                         next_local_commitment_number: 3,
1692                         next_remote_commitment_number: 4,
1693                         your_last_per_commitment_secret: Some([9; 32]),
1694                         my_current_per_commitment_point: public_key,
1695                 };
1696
1697                 let encoded_value = cr.encode();
1698                 assert_eq!(
1699                         encoded_value,
1700                         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]
1701                 );
1702         }
1703 }