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