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