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