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