Also fwd channel_update and node_announcement immediately
[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
685                 Ok(OpenChannel {
686                         chain_hash: deserialize(&v[0..32]).unwrap(),
687                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
688                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
689                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
690                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
691                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
692                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
693                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
694                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
695                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
696                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
697                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
698                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
699                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
700                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
701                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
702                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
703                         channel_flags: v[318],
704                         shutdown_scriptpubkey: shutdown_scriptpubkey
705                 })
706         }
707 }
708 impl MsgEncodable for OpenChannel {
709         fn encode(&self) -> Vec<u8> {
710                 let mut res = match &self.shutdown_scriptpubkey {
711                         &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
712                         &None => Vec::with_capacity(319),
713                 };
714                 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
715                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
716                 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
717                 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
718                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
719                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
720                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
721                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
722                 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
723                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
724                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
725                 res.extend_from_slice(&self.funding_pubkey.serialize());
726                 res.extend_from_slice(&self.revocation_basepoint.serialize());
727                 res.extend_from_slice(&self.payment_basepoint.serialize());
728                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
729                 res.extend_from_slice(&self.htlc_basepoint.serialize());
730                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
731                 res.push(self.channel_flags);
732                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
733                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
734                         res.extend_from_slice(&script[..]);
735                 }
736                 res
737         }
738 }
739
740 impl MsgDecodable for AcceptChannel {
741         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
742                 if v.len() < 32+4*8+4+2*2+6*33 {
743                         return Err(DecodeError::ShortRead);
744                 }
745                 let ctx = Secp256k1::without_caps();
746
747                 let mut shutdown_scriptpubkey = None;
748                 if v.len() >= 272 {
749                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
750                         if v.len() < 272+len {
751                                 return Err(DecodeError::ShortRead);
752                         }
753                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
754                 }
755
756                 let mut temporary_channel_id = [0; 32];
757                 temporary_channel_id[..].copy_from_slice(&v[0..32]);
758                 Ok(Self {
759                         temporary_channel_id,
760                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
761                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
762                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
763                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
764                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
765                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
766                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
767                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
768                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
769                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
770                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
771                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
772                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
773                         shutdown_scriptpubkey: shutdown_scriptpubkey
774                 })
775         }
776 }
777 impl MsgEncodable for AcceptChannel {
778         fn encode(&self) -> Vec<u8> {
779                 let mut res = match &self.shutdown_scriptpubkey {
780                         &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
781                         &None => Vec::with_capacity(270),
782                 };
783                 res.extend_from_slice(&self.temporary_channel_id);
784                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
785                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
786                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
787                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
788                 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
789                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
790                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
791                 res.extend_from_slice(&self.funding_pubkey.serialize());
792                 res.extend_from_slice(&self.revocation_basepoint.serialize());
793                 res.extend_from_slice(&self.payment_basepoint.serialize());
794                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
795                 res.extend_from_slice(&self.htlc_basepoint.serialize());
796                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
797                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
798                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
799                         res.extend_from_slice(&script[..]);
800                 }
801                 res
802         }
803 }
804
805 impl MsgDecodable for FundingCreated {
806         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
807                 if v.len() < 32+32+2+64 {
808                         return Err(DecodeError::ShortRead);
809                 }
810                 let ctx = Secp256k1::without_caps();
811                 let mut temporary_channel_id = [0; 32];
812                 temporary_channel_id[..].copy_from_slice(&v[0..32]);
813                 Ok(Self {
814                         temporary_channel_id,
815                         funding_txid: deserialize(&v[32..64]).unwrap(),
816                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
817                         signature: secp_signature!(&ctx, &v[66..130]),
818                 })
819         }
820 }
821 impl MsgEncodable for FundingCreated {
822         fn encode(&self) -> Vec<u8> {
823                 let mut res = Vec::with_capacity(32+32+2+64);
824                 res.extend_from_slice(&self.temporary_channel_id);
825                 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
826                 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
827                 let secp_ctx = Secp256k1::without_caps();
828                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
829                 res
830         }
831 }
832
833 impl MsgDecodable for FundingSigned {
834         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
835                 if v.len() < 32+64 {
836                         return Err(DecodeError::ShortRead);
837                 }
838                 let ctx = Secp256k1::without_caps();
839                 let mut channel_id = [0; 32];
840                 channel_id[..].copy_from_slice(&v[0..32]);
841                 Ok(Self {
842                         channel_id,
843                         signature: secp_signature!(&ctx, &v[32..96]),
844                 })
845         }
846 }
847 impl MsgEncodable for FundingSigned {
848         fn encode(&self) -> Vec<u8> {
849                 let mut res = Vec::with_capacity(32+64);
850                 res.extend_from_slice(&self.channel_id);
851                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
852                 res
853         }
854 }
855
856 impl MsgDecodable for FundingLocked {
857         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
858                 if v.len() < 32+33 {
859                         return Err(DecodeError::ShortRead);
860                 }
861                 let ctx = Secp256k1::without_caps();
862                 let mut channel_id = [0; 32];
863                 channel_id[..].copy_from_slice(&v[0..32]);
864                 Ok(Self {
865                         channel_id,
866                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
867                 })
868         }
869 }
870 impl MsgEncodable for FundingLocked {
871         fn encode(&self) -> Vec<u8> {
872                 let mut res = Vec::with_capacity(32+33);
873                 res.extend_from_slice(&self.channel_id);
874                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
875                 res
876         }
877 }
878
879 impl MsgDecodable for Shutdown {
880         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
881                 if v.len() < 32 + 2 {
882                         return Err(DecodeError::ShortRead);
883                 }
884                 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
885                 if v.len() < 32 + 2 + scriptlen {
886                         return Err(DecodeError::ShortRead);
887                 }
888                 let mut channel_id = [0; 32];
889                 channel_id[..].copy_from_slice(&v[0..32]);
890                 Ok(Self {
891                         channel_id,
892                         scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
893                 })
894         }
895 }
896 impl MsgEncodable for Shutdown {
897         fn encode(&self) -> Vec<u8> {
898                 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
899                 res.extend_from_slice(&self.channel_id);
900                 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
901                 res.extend_from_slice(&self.scriptpubkey[..]);
902                 res
903         }
904 }
905
906 impl MsgDecodable for ClosingSigned {
907         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
908                 if v.len() < 32 + 8 + 64 {
909                         return Err(DecodeError::ShortRead);
910                 }
911                 let secp_ctx = Secp256k1::without_caps();
912                 let mut channel_id = [0; 32];
913                 channel_id[..].copy_from_slice(&v[0..32]);
914                 Ok(Self {
915                         channel_id,
916                         fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
917                         signature: secp_signature!(&secp_ctx, &v[40..104]),
918                 })
919         }
920 }
921 impl MsgEncodable for ClosingSigned {
922         fn encode(&self) -> Vec<u8> {
923                 let mut res = Vec::with_capacity(32+8+64);
924                 res.extend_from_slice(&self.channel_id);
925                 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
926                 let secp_ctx = Secp256k1::without_caps();
927                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
928                 res
929         }
930 }
931
932 impl MsgDecodable for UpdateAddHTLC {
933         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
934                 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
935                         return Err(DecodeError::ShortRead);
936                 }
937                 let mut channel_id = [0; 32];
938                 channel_id[..].copy_from_slice(&v[0..32]);
939                 let mut payment_hash = [0; 32];
940                 payment_hash.copy_from_slice(&v[48..80]);
941                 Ok(Self{
942                         channel_id,
943                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
944                         amount_msat: byte_utils::slice_to_be64(&v[40..48]),
945                         payment_hash,
946                         cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
947                         onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
948                 })
949         }
950 }
951 impl MsgEncodable for UpdateAddHTLC {
952         fn encode(&self) -> Vec<u8> {
953                 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
954                 res.extend_from_slice(&self.channel_id);
955                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
956                 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
957                 res.extend_from_slice(&self.payment_hash);
958                 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
959                 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
960                 res
961         }
962 }
963
964 impl MsgDecodable for UpdateFulfillHTLC {
965         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
966                 if v.len() < 32+8+32 {
967                         return Err(DecodeError::ShortRead);
968                 }
969                 let mut channel_id = [0; 32];
970                 channel_id[..].copy_from_slice(&v[0..32]);
971                 let mut payment_preimage = [0; 32];
972                 payment_preimage.copy_from_slice(&v[40..72]);
973                 Ok(Self{
974                         channel_id,
975                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
976                         payment_preimage,
977                 })
978         }
979 }
980 impl MsgEncodable for UpdateFulfillHTLC {
981         fn encode(&self) -> Vec<u8> {
982                 let mut res = Vec::with_capacity(32+8+32);
983                 res.extend_from_slice(&self.channel_id);
984                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
985                 res.extend_from_slice(&self.payment_preimage);
986                 res
987         }
988 }
989
990 impl MsgDecodable for UpdateFailHTLC {
991         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
992                 if v.len() < 32+8 {
993                         return Err(DecodeError::ShortRead);
994                 }
995                 let mut channel_id = [0; 32];
996                 channel_id[..].copy_from_slice(&v[0..32]);
997                 Ok(Self{
998                         channel_id,
999                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1000                         reason: OnionErrorPacket::decode(&v[40..])?,
1001                 })
1002         }
1003 }
1004 impl MsgEncodable for UpdateFailHTLC {
1005         fn encode(&self) -> Vec<u8> {
1006                 let reason = self.reason.encode();
1007                 let mut res = Vec::with_capacity(32+8+reason.len());
1008                 res.extend_from_slice(&self.channel_id);
1009                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1010                 res.extend_from_slice(&reason[..]);
1011                 res
1012         }
1013 }
1014
1015 impl MsgDecodable for UpdateFailMalformedHTLC {
1016         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1017                 if v.len() < 32+8+32+2 {
1018                         return Err(DecodeError::ShortRead);
1019                 }
1020                 let mut channel_id = [0; 32];
1021                 channel_id[..].copy_from_slice(&v[0..32]);
1022                 let mut sha256_of_onion = [0; 32];
1023                 sha256_of_onion.copy_from_slice(&v[40..72]);
1024                 Ok(Self{
1025                         channel_id,
1026                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1027                         sha256_of_onion,
1028                         failure_code: byte_utils::slice_to_be16(&v[72..74]),
1029                 })
1030         }
1031 }
1032 impl MsgEncodable for UpdateFailMalformedHTLC {
1033         fn encode(&self) -> Vec<u8> {
1034                 let mut res = Vec::with_capacity(32+8+32+2);
1035                 res.extend_from_slice(&self.channel_id);
1036                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1037                 res.extend_from_slice(&self.sha256_of_onion);
1038                 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1039                 res
1040         }
1041 }
1042
1043 impl MsgDecodable for CommitmentSigned {
1044         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1045                 if v.len() < 32+64+2 {
1046                         return Err(DecodeError::ShortRead);
1047                 }
1048                 let mut channel_id = [0; 32];
1049                 channel_id[..].copy_from_slice(&v[0..32]);
1050
1051                 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1052                 if v.len() < 32+64+2+htlcs*64 {
1053                         return Err(DecodeError::ShortRead);
1054                 }
1055                 let mut htlc_signatures = Vec::with_capacity(htlcs);
1056                 let secp_ctx = Secp256k1::without_caps();
1057                 for i in 0..htlcs {
1058                         htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1059                 }
1060                 Ok(Self {
1061                         channel_id,
1062                         signature: secp_signature!(&secp_ctx, &v[32..96]),
1063                         htlc_signatures,
1064                 })
1065         }
1066 }
1067 impl MsgEncodable for CommitmentSigned {
1068         fn encode(&self) -> Vec<u8> {
1069                 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1070                 res.extend_from_slice(&self.channel_id);
1071                 let secp_ctx = Secp256k1::without_caps();
1072                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1073                 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1074                 for i in 0..self.htlc_signatures.len() {
1075                         res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1076                 }
1077                 res
1078         }
1079 }
1080
1081 impl MsgDecodable for RevokeAndACK {
1082         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1083                 if v.len() < 32+32+33 {
1084                         return Err(DecodeError::ShortRead);
1085                 }
1086                 let mut channel_id = [0; 32];
1087                 channel_id[..].copy_from_slice(&v[0..32]);
1088                 let mut per_commitment_secret = [0; 32];
1089                 per_commitment_secret.copy_from_slice(&v[32..64]);
1090                 let secp_ctx = Secp256k1::without_caps();
1091                 Ok(Self {
1092                         channel_id,
1093                         per_commitment_secret,
1094                         next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1095                 })
1096         }
1097 }
1098 impl MsgEncodable for RevokeAndACK {
1099         fn encode(&self) -> Vec<u8> {
1100                 let mut res = Vec::with_capacity(32+32+33);
1101                 res.extend_from_slice(&self.channel_id);
1102                 res.extend_from_slice(&self.per_commitment_secret);
1103                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1104                 res
1105         }
1106 }
1107
1108 impl MsgDecodable for UpdateFee {
1109         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1110                 if v.len() < 32+4 {
1111                         return Err(DecodeError::ShortRead);
1112                 }
1113                 let mut channel_id = [0; 32];
1114                 channel_id[..].copy_from_slice(&v[0..32]);
1115                 Ok(Self {
1116                         channel_id,
1117                         feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1118                 })
1119         }
1120 }
1121 impl MsgEncodable for UpdateFee {
1122         fn encode(&self) -> Vec<u8> {
1123                 let mut res = Vec::with_capacity(32+4);
1124                 res.extend_from_slice(&self.channel_id);
1125                 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1126                 res
1127         }
1128 }
1129
1130 impl MsgDecodable for ChannelReestablish {
1131         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1132                 if v.len() < 32+2*8 {
1133                         return Err(DecodeError::ShortRead);
1134                 }
1135
1136                 let data_loss_protect = if v.len() > 32+2*8 {
1137                         if v.len() < 32+2*8 + 33+32 {
1138                                 return Err(DecodeError::ShortRead);
1139                         }
1140                         let mut inner_array = [0; 32];
1141                         inner_array.copy_from_slice(&v[48..48+32]);
1142                         Some(DataLossProtect {
1143                                 your_last_per_commitment_secret: inner_array,
1144                                 my_current_per_commitment_point: secp_pubkey!(&Secp256k1::without_caps(), &v[48+32..48+32+33]),
1145                         })
1146                 } else { None };
1147
1148                 Ok(Self {
1149                         channel_id: deserialize(&v[0..32]).unwrap(),
1150                         next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1151                         next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1152                         data_loss_protect: data_loss_protect,
1153                 })
1154         }
1155 }
1156 impl MsgEncodable for ChannelReestablish {
1157         fn encode(&self) -> Vec<u8> {
1158                 let mut res = Vec::with_capacity(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
1159
1160                 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1161                 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1162                 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1163
1164                 if let &Some(ref data_loss_protect) = &self.data_loss_protect {
1165                         res.extend_from_slice(&data_loss_protect.your_last_per_commitment_secret[..]);
1166                         res.extend_from_slice(&data_loss_protect.my_current_per_commitment_point.serialize());
1167                 }
1168                 res
1169         }
1170 }
1171
1172 impl MsgDecodable for AnnouncementSignatures {
1173         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1174                 if v.len() < 32+8+64*2 {
1175                         return Err(DecodeError::ShortRead);
1176                 }
1177                 let secp_ctx = Secp256k1::without_caps();
1178                 let mut channel_id = [0; 32];
1179                 channel_id[..].copy_from_slice(&v[0..32]);
1180                 Ok(Self {
1181                         channel_id,
1182                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1183                         node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1184                         bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1185                 })
1186         }
1187 }
1188 impl MsgEncodable for AnnouncementSignatures {
1189         fn encode(&self) -> Vec<u8> {
1190                 let mut res = Vec::with_capacity(32+8+64*2);
1191                 res.extend_from_slice(&self.channel_id);
1192                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1193                 let secp_ctx = Secp256k1::without_caps();
1194                 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1195                 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1196                 res
1197         }
1198 }
1199
1200 impl MsgDecodable for UnsignedNodeAnnouncement {
1201         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1202                 let features = GlobalFeatures::decode(&v[..])?;
1203                 if features.requires_unknown_bits() {
1204                         return Err(DecodeError::UnknownRequiredFeature);
1205                 }
1206
1207                 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1208                         return Err(DecodeError::ShortRead);
1209                 }
1210                 let start = features.encoded_len();
1211
1212                 let mut rgb = [0; 3];
1213                 rgb.copy_from_slice(&v[start + 37..start + 40]);
1214
1215                 let mut alias = [0; 32];
1216                 alias.copy_from_slice(&v[start + 40..start + 72]);
1217
1218                 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1219                 if v.len() < start + 74 + addrlen {
1220                         return Err(DecodeError::ShortRead);
1221                 }
1222                 let addr_read_limit = start + 74 + addrlen;
1223
1224                 let mut addresses = Vec::with_capacity(4);
1225                 let mut read_pos = start + 74;
1226                 loop {
1227                         if addr_read_limit <= read_pos { break; }
1228                         match v[read_pos] {
1229                                 1 => {
1230                                         if addresses.len() > 0 {
1231                                                 return Err(DecodeError::ExtraAddressesPerType);
1232                                         }
1233                                         if addr_read_limit < read_pos + 1 + 6 {
1234                                                 return Err(DecodeError::BadLengthDescriptor);
1235                                         }
1236                                         let mut addr = [0; 4];
1237                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1238                                         addresses.push(NetAddress::IPv4 {
1239                                                 addr,
1240                                                 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1241                                         });
1242                                         read_pos += 1 + 6;
1243                                 },
1244                                 2 => {
1245                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1246                                                 return Err(DecodeError::ExtraAddressesPerType);
1247                                         }
1248                                         if addr_read_limit < read_pos + 1 + 18 {
1249                                                 return Err(DecodeError::BadLengthDescriptor);
1250                                         }
1251                                         let mut addr = [0; 16];
1252                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1253                                         addresses.push(NetAddress::IPv6 {
1254                                                 addr,
1255                                                 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1256                                         });
1257                                         read_pos += 1 + 18;
1258                                 },
1259                                 3 => {
1260                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1261                                                 return Err(DecodeError::ExtraAddressesPerType);
1262                                         }
1263                                         if addr_read_limit < read_pos + 1 + 12 {
1264                                                 return Err(DecodeError::BadLengthDescriptor);
1265                                         }
1266                                         let mut addr = [0; 10];
1267                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1268                                         addresses.push(NetAddress::OnionV2 {
1269                                                 addr,
1270                                                 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1271                                         });
1272                                         read_pos += 1 + 12;
1273                                 },
1274                                 4 => {
1275                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1276                                                 return Err(DecodeError::ExtraAddressesPerType);
1277                                         }
1278                                         if addr_read_limit < read_pos + 1 + 37 {
1279                                                 return Err(DecodeError::BadLengthDescriptor);
1280                                         }
1281                                         let mut ed25519_pubkey = [0; 32];
1282                                         ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1283                                         addresses.push(NetAddress::OnionV3 {
1284                                                 ed25519_pubkey,
1285                                                 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1286                                                 version: v[read_pos + 35],
1287                                                 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1288                                         });
1289                                         read_pos += 1 + 37;
1290                                 },
1291                                 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1292                         }
1293                 }
1294
1295                 let excess_address_data = if read_pos < addr_read_limit {
1296                         let mut excess_address_data = Vec::with_capacity(addr_read_limit - read_pos);
1297                         excess_address_data.extend_from_slice(&v[read_pos..addr_read_limit]);
1298                         excess_address_data
1299                 } else { Vec::new() };
1300
1301                 let mut excess_data = Vec::with_capacity(v.len() - addr_read_limit);
1302                 excess_data.extend_from_slice(&v[addr_read_limit..]);
1303
1304                 let secp_ctx = Secp256k1::without_caps();
1305                 Ok(Self {
1306                         features,
1307                         timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1308                         node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1309                         rgb,
1310                         alias,
1311                         addresses,
1312                         excess_address_data,
1313                         excess_data,
1314                 })
1315         }
1316 }
1317 impl MsgEncodable for UnsignedNodeAnnouncement {
1318         fn encode(&self) -> Vec<u8> {
1319                 let features = self.features.encode();
1320                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len()*7 + self.excess_address_data.len() + self.excess_data.len());
1321                 res.extend_from_slice(&features[..]);
1322                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1323                 res.extend_from_slice(&self.node_id.serialize());
1324                 res.extend_from_slice(&self.rgb);
1325                 res.extend_from_slice(&self.alias);
1326                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1327                 let mut addrs_to_encode = self.addresses.clone();
1328                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1329                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1330                 for addr in addrs_to_encode.iter() {
1331                         match addr {
1332                                 &NetAddress::IPv4{addr, port} => {
1333                                         addr_slice.push(1);
1334                                         addr_slice.extend_from_slice(&addr);
1335                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1336                                 },
1337                                 &NetAddress::IPv6{addr, port} => {
1338                                         addr_slice.push(2);
1339                                         addr_slice.extend_from_slice(&addr);
1340                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1341                                 },
1342                                 &NetAddress::OnionV2{addr, port} => {
1343                                         addr_slice.push(3);
1344                                         addr_slice.extend_from_slice(&addr);
1345                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1346                                 },
1347                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1348                                         addr_slice.push(4);
1349                                         addr_slice.extend_from_slice(&ed25519_pubkey);
1350                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1351                                         addr_slice.push(version);
1352                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1353                                 },
1354                         }
1355                 }
1356                 res.extend_from_slice(&byte_utils::be16_to_array((addr_slice.len() + self.excess_address_data.len()) as u16));
1357                 res.extend_from_slice(&addr_slice[..]);
1358                 res.extend_from_slice(&self.excess_address_data[..]);
1359                 res.extend_from_slice(&self.excess_data[..]);
1360                 res
1361         }
1362 }
1363
1364 impl MsgDecodable for NodeAnnouncement {
1365         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1366                 if v.len() < 64 {
1367                         return Err(DecodeError::ShortRead);
1368                 }
1369                 let secp_ctx = Secp256k1::without_caps();
1370                 Ok(Self {
1371                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1372                         contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1373                 })
1374         }
1375 }
1376 impl MsgEncodable for NodeAnnouncement {
1377         fn encode(&self) -> Vec<u8> {
1378                 let contents = self.contents.encode();
1379                 let mut res = Vec::with_capacity(64 + contents.len());
1380                 let secp_ctx = Secp256k1::without_caps();
1381                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1382                 res.extend_from_slice(&contents);
1383                 res
1384         }
1385 }
1386
1387 impl MsgDecodable for UnsignedChannelAnnouncement {
1388         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1389                 let features = GlobalFeatures::decode(&v[..])?;
1390                 if features.requires_unknown_bits() {
1391                         return Err(DecodeError::UnknownRequiredFeature);
1392                 }
1393                 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1394                         return Err(DecodeError::ShortRead);
1395                 }
1396                 let start = features.encoded_len();
1397                 let secp_ctx = Secp256k1::without_caps();
1398                 let mut excess_data = Vec::with_capacity(v.len() - start - 172);
1399                 excess_data.extend_from_slice(&v[start + 172..]);
1400                 Ok(Self {
1401                         features,
1402                         chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1403                         short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1404                         node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1405                         node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1406                         bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1407                         bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1408                         excess_data,
1409                 })
1410         }
1411 }
1412 impl MsgEncodable for UnsignedChannelAnnouncement {
1413         fn encode(&self) -> Vec<u8> {
1414                 let features = self.features.encode();
1415                 let mut res = Vec::with_capacity(172 + features.len() + self.excess_data.len());
1416                 res.extend_from_slice(&features[..]);
1417                 res.extend_from_slice(&self.chain_hash[..]);
1418                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1419                 res.extend_from_slice(&self.node_id_1.serialize());
1420                 res.extend_from_slice(&self.node_id_2.serialize());
1421                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1422                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1423                 res.extend_from_slice(&self.excess_data[..]);
1424                 res
1425         }
1426 }
1427
1428 impl MsgDecodable for ChannelAnnouncement {
1429         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1430                 if v.len() < 64*4 {
1431                         return Err(DecodeError::ShortRead);
1432                 }
1433                 let secp_ctx = Secp256k1::without_caps();
1434                 Ok(Self {
1435                         node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1436                         node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1437                         bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1438                         bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1439                         contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1440                 })
1441         }
1442 }
1443 impl MsgEncodable for ChannelAnnouncement {
1444         fn encode(&self) -> Vec<u8> {
1445                 let secp_ctx = Secp256k1::without_caps();
1446                 let contents = self.contents.encode();
1447                 let mut res = Vec::with_capacity(64 + contents.len());
1448                 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1449                 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1450                 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1451                 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1452                 res.extend_from_slice(&contents);
1453                 res
1454         }
1455 }
1456
1457 impl MsgDecodable for UnsignedChannelUpdate {
1458         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1459                 if v.len() < 32+8+4+2+2+8+4+4 {
1460                         return Err(DecodeError::ShortRead);
1461                 }
1462                 let mut excess_data = Vec::with_capacity(v.len() - 64);
1463                 excess_data.extend_from_slice(&v[64..]);
1464                 Ok(Self {
1465                         chain_hash: deserialize(&v[0..32]).unwrap(),
1466                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1467                         timestamp: byte_utils::slice_to_be32(&v[40..44]),
1468                         flags: byte_utils::slice_to_be16(&v[44..46]),
1469                         cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1470                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1471                         fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1472                         fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1473                         excess_data
1474                 })
1475         }
1476 }
1477 impl MsgEncodable for UnsignedChannelUpdate {
1478         fn encode(&self) -> Vec<u8> {
1479                 let mut res = Vec::with_capacity(64 + self.excess_data.len());
1480                 res.extend_from_slice(&self.chain_hash[..]);
1481                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1482                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1483                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1484                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1485                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1486                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1487                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1488                 res.extend_from_slice(&self.excess_data[..]);
1489                 res
1490         }
1491 }
1492
1493 impl MsgDecodable for ChannelUpdate {
1494         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1495                 if v.len() < 128 {
1496                         return Err(DecodeError::ShortRead);
1497                 }
1498                 let secp_ctx = Secp256k1::without_caps();
1499                 Ok(Self {
1500                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1501                         contents: UnsignedChannelUpdate::decode(&v[64..])?,
1502                 })
1503         }
1504 }
1505 impl MsgEncodable for ChannelUpdate {
1506         fn encode(&self) -> Vec<u8> {
1507                 let mut res = Vec::with_capacity(128);
1508                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1509                 res.extend_from_slice(&self.contents.encode()[..]);
1510                 res
1511         }
1512 }
1513
1514 impl MsgDecodable for OnionRealm0HopData {
1515         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1516                 if v.len() < 32 {
1517                         return Err(DecodeError::ShortRead);
1518                 }
1519                 Ok(OnionRealm0HopData {
1520                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1521                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1522                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1523                 })
1524         }
1525 }
1526 impl MsgEncodable for OnionRealm0HopData {
1527         fn encode(&self) -> Vec<u8> {
1528                 let mut res = Vec::with_capacity(32);
1529                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1530                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1531                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1532                 res.resize(32, 0);
1533                 res
1534         }
1535 }
1536
1537 impl MsgDecodable for OnionHopData {
1538         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1539                 if v.len() < 65 {
1540                         return Err(DecodeError::ShortRead);
1541                 }
1542                 let realm = v[0];
1543                 if realm != 0 {
1544                         return Err(DecodeError::UnknownRealmByte);
1545                 }
1546                 let mut hmac = [0; 32];
1547                 hmac[..].copy_from_slice(&v[33..65]);
1548                 Ok(OnionHopData {
1549                         realm: realm,
1550                         data: OnionRealm0HopData::decode(&v[1..33])?,
1551                         hmac: hmac,
1552                 })
1553         }
1554 }
1555 impl MsgEncodable for OnionHopData {
1556         fn encode(&self) -> Vec<u8> {
1557                 let mut res = Vec::with_capacity(65);
1558                 res.push(self.realm);
1559                 res.extend_from_slice(&self.data.encode()[..]);
1560                 res.extend_from_slice(&self.hmac);
1561                 res
1562         }
1563 }
1564
1565 impl MsgDecodable for OnionPacket {
1566         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1567                 if v.len() < 1+33+20*65+32 {
1568                         return Err(DecodeError::ShortRead);
1569                 }
1570                 let mut hop_data = [0; 20*65];
1571                 hop_data.copy_from_slice(&v[34..1334]);
1572                 let mut hmac = [0; 32];
1573                 hmac.copy_from_slice(&v[1334..1366]);
1574                 let secp_ctx = Secp256k1::without_caps();
1575                 Ok(Self {
1576                         version: v[0],
1577                         public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1578                         hop_data,
1579                         hmac,
1580                 })
1581         }
1582 }
1583 impl MsgEncodable for OnionPacket {
1584         fn encode(&self) -> Vec<u8> {
1585                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1586                 res.push(self.version);
1587                 match self.public_key {
1588                         Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1589                         Err(_) => res.extend_from_slice(&[0; 33]),
1590                 }
1591                 res.extend_from_slice(&self.hop_data);
1592                 res.extend_from_slice(&self.hmac);
1593                 res
1594         }
1595 }
1596
1597 impl MsgDecodable for DecodedOnionErrorPacket {
1598         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1599                 if v.len() < 32 + 4 {
1600                         return Err(DecodeError::ShortRead);
1601                 }
1602                 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1603                 if v.len() < 32 + 4 + failuremsg_len {
1604                         return Err(DecodeError::ShortRead);
1605                 }
1606                 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1607                 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1608                         return Err(DecodeError::ShortRead);
1609                 }
1610
1611                 let mut hmac = [0; 32];
1612                 hmac.copy_from_slice(&v[0..32]);
1613                 Ok(Self {
1614                         hmac,
1615                         failuremsg: v[34..34 + failuremsg_len].to_vec(),
1616                         pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1617                 })
1618         }
1619 }
1620 impl MsgEncodable for DecodedOnionErrorPacket {
1621         fn encode(&self) -> Vec<u8> {
1622                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1623                 res.extend_from_slice(&self.hmac);
1624                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1625                 res.extend_from_slice(&self.failuremsg);
1626                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1627                 res.extend_from_slice(&self.pad);
1628                 res
1629         }
1630 }
1631
1632 impl MsgDecodable for OnionErrorPacket {
1633         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1634                 if v.len() < 2 {
1635                         return Err(DecodeError::ShortRead);
1636                 }
1637                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1638                 if v.len() < 2 + len {
1639                         return Err(DecodeError::ShortRead);
1640                 }
1641                 Ok(Self {
1642                         data: v[2..len+2].to_vec(),
1643                 })
1644         }
1645 }
1646 impl MsgEncodable for OnionErrorPacket {
1647         fn encode(&self) -> Vec<u8> {
1648                 let mut res = Vec::with_capacity(2 + self.data.len());
1649                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1650                 res.extend_from_slice(&self.data);
1651                 res
1652         }
1653 }
1654
1655 impl MsgEncodable for ErrorMessage {
1656         fn encode(&self) -> Vec<u8> {
1657                 let mut res = Vec::with_capacity(34 + self.data.len());
1658                 res.extend_from_slice(&self.channel_id);
1659                 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1660                 res.extend_from_slice(&self.data.as_bytes());
1661                 res
1662         }
1663 }
1664 impl MsgDecodable for ErrorMessage {
1665         fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1666                 if v.len() < 34 {
1667                         return Err(DecodeError::ShortRead);
1668                 }
1669                 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1670                 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1671                 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1672                         Ok(s) => s,
1673                         Err(_) => return Err(DecodeError::BadText),
1674                 };
1675                 let mut channel_id = [0; 32];
1676                 channel_id[..].copy_from_slice(&v[0..32]);
1677                 Ok(Self {
1678                         channel_id,
1679                         data,
1680                 })
1681         }
1682 }
1683
1684 #[cfg(test)]
1685 mod tests {
1686         use hex;
1687         use ln::msgs::MsgEncodable;
1688         use ln::msgs;
1689         use secp256k1::key::{PublicKey,SecretKey};
1690         use secp256k1::Secp256k1;
1691
1692         #[test]
1693         fn encoding_channel_reestablish_no_secret() {
1694                 let cr = msgs::ChannelReestablish {
1695                         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],
1696                         next_local_commitment_number: 3,
1697                         next_remote_commitment_number: 4,
1698                         data_loss_protect: None,
1699                 };
1700
1701                 let encoded_value = cr.encode();
1702                 assert_eq!(
1703                         encoded_value,
1704                         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]
1705                 );
1706         }
1707
1708         #[test]
1709         fn encoding_channel_reestablish_with_secret() {
1710                 let public_key = {
1711                         let secp_ctx = Secp256k1::new();
1712                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1713                 };
1714
1715                 let cr = msgs::ChannelReestablish {
1716                         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],
1717                         next_local_commitment_number: 3,
1718                         next_remote_commitment_number: 4,
1719                         data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1720                 };
1721
1722                 let encoded_value = cr.encode();
1723                 assert_eq!(
1724                         encoded_value,
1725                         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]
1726                 );
1727         }
1728 }