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