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