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