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