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