impl more message encodings
[rust-lightning] / src / ln / msgs.rs
1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use bitcoin::util::uint::Uint256;
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::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 }
19 #[derive(Debug)]
20 pub enum DecodeError {
21         /// Unknown realm byte in an OnionHopData packet
22         UnknownRealmByte,
23         /// Failed to decode a public key (ie it's invalid)
24         BadPublicKey,
25         /// Failed to decode a signature (ie it's invalid)
26         BadSignature,
27         /// Buffer not of right length (either too short or too long)
28         WrongLength,
29         /// node_announcement included more than one address of a given type!
30         ExtraAddressesPerType,
31 }
32 pub trait MsgDecodable: Sized {
33         fn decode(v: &[u8]) -> Result<Self, DecodeError>;
34 }
35
36 /// Tracks localfeatures which are only in init messages
37 #[derive(Clone, PartialEq)]
38 pub struct LocalFeatures {
39         flags: Vec<u8>,
40 }
41
42 impl LocalFeatures {
43         pub fn new() -> LocalFeatures {
44                 LocalFeatures {
45                         flags: Vec::new(),
46                 }
47         }
48
49         pub fn supports_data_loss_protect(&self) -> bool {
50                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
51         }
52         pub fn requires_data_loss_protect(&self) -> bool {
53                 self.flags.len() > 0 && (self.flags[0] & 1) != 0
54         }
55
56         pub fn supports_initial_routing_sync(&self) -> bool {
57                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
58         }
59
60         pub fn supports_upfront_shutdown_script(&self) -> bool {
61                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
62         }
63         pub fn requires_upfront_shutdown_script(&self) -> bool {
64                 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
65         }
66
67         pub fn requires_unknown_bits(&self) -> bool {
68                 for (idx, &byte) in self.flags.iter().enumerate() {
69                         if idx != 0 && (byte & 0x55) != 0 {
70                                 return true;
71                         } else if idx == 0 && (byte & 0x14) != 0 {
72                                 return true;
73                         }
74                 }
75                 return false;
76         }
77
78         pub fn supports_unknown_bits(&self) -> bool {
79                 for (idx, &byte) in self.flags.iter().enumerate() {
80                         if idx != 0 && byte != 0 {
81                                 return true;
82                         } else if idx == 0 && (byte & 0xc4) != 0 {
83                                 return true;
84                         }
85                 }
86                 return false;
87         }
88 }
89
90 /// Tracks globalfeatures which are in init messages and routing announcements
91 #[derive(Clone, PartialEq)]
92 pub struct GlobalFeatures {
93         flags: Vec<u8>,
94 }
95
96 impl GlobalFeatures {
97         pub fn new() -> GlobalFeatures {
98                 GlobalFeatures {
99                         flags: Vec::new(),
100                 }
101         }
102
103         pub fn requires_unknown_bits(&self) -> bool {
104                 for &byte in self.flags.iter() {
105                         if (byte & 0x55) != 0 {
106                                 return true;
107                         }
108                 }
109                 return false;
110         }
111
112         pub fn supports_unknown_bits(&self) -> bool {
113                 for &byte in self.flags.iter() {
114                         if byte != 0 {
115                                 return true;
116                         }
117                 }
118                 return false;
119         }
120 }
121
122 pub struct Init {
123         pub global_features: GlobalFeatures,
124         pub local_features: LocalFeatures,
125 }
126
127 pub struct OpenChannel {
128         pub chain_hash: Sha256dHash,
129         pub temporary_channel_id: Uint256,
130         pub funding_satoshis: u64,
131         pub push_msat: u64,
132         pub dust_limit_satoshis: u64,
133         pub max_htlc_value_in_flight_msat: u64,
134         pub channel_reserve_satoshis: u64,
135         pub htlc_minimum_msat: u64,
136         pub feerate_per_kw: u32,
137         pub to_self_delay: u16,
138         pub max_accepted_htlcs: u16,
139         pub funding_pubkey: PublicKey,
140         pub revocation_basepoint: PublicKey,
141         pub payment_basepoint: PublicKey,
142         pub delayed_payment_basepoint: PublicKey,
143         pub htlc_basepoint: PublicKey,
144         pub first_per_commitment_point: PublicKey,
145         pub channel_flags: u8,
146         pub shutdown_scriptpubkey: Option<Script>,
147 }
148
149 pub struct AcceptChannel {
150         pub temporary_channel_id: Uint256,
151         pub dust_limit_satoshis: u64,
152         pub max_htlc_value_in_flight_msat: u64,
153         pub channel_reserve_satoshis: u64,
154         pub htlc_minimum_msat: u64,
155         pub minimum_depth: u32,
156         pub to_self_delay: u16,
157         pub max_accepted_htlcs: u16,
158         pub funding_pubkey: PublicKey,
159         pub revocation_basepoint: PublicKey,
160         pub payment_basepoint: PublicKey,
161         pub delayed_payment_basepoint: PublicKey,
162         pub htlc_basepoint: PublicKey,
163         pub first_per_commitment_point: PublicKey,
164         pub shutdown_scriptpubkey: Option<Script>,
165 }
166
167 pub struct FundingCreated {
168         pub temporary_channel_id: Uint256,
169         pub funding_txid: Sha256dHash,
170         pub funding_output_index: u16,
171         pub signature: Signature,
172 }
173
174 pub struct FundingSigned {
175         pub channel_id: Uint256,
176         pub signature: Signature,
177 }
178
179 pub struct FundingLocked {
180         pub channel_id: Uint256,
181         pub next_per_commitment_point: PublicKey,
182 }
183
184 pub struct Shutdown {
185         pub channel_id: Uint256,
186         pub scriptpubkey: Script,
187 }
188
189 pub struct ClosingSigned {
190         pub channel_id: Uint256,
191         pub fee_satoshis: u64,
192         pub signature: Signature,
193 }
194
195 #[derive(Clone)]
196 pub struct UpdateAddHTLC {
197         pub channel_id: Uint256,
198         pub htlc_id: u64,
199         pub amount_msat: u64,
200         pub payment_hash: [u8; 32],
201         pub cltv_expiry: u32,
202         pub onion_routing_packet: OnionPacket,
203 }
204
205 #[derive(Clone)]
206 pub struct UpdateFulfillHTLC {
207         pub channel_id: Uint256,
208         pub htlc_id: u64,
209         pub payment_preimage: [u8; 32],
210 }
211
212 #[derive(Clone)]
213 pub struct UpdateFailHTLC {
214         pub channel_id: Uint256,
215         pub htlc_id: u64,
216         pub reason: OnionErrorPacket,
217 }
218
219 #[derive(Clone)]
220 pub struct UpdateFailMalformedHTLC {
221         pub channel_id: Uint256,
222         pub htlc_id: u64,
223         pub sha256_of_onion: [u8; 32],
224         pub failure_code: u16,
225 }
226
227 #[derive(Clone)]
228 pub struct CommitmentSigned {
229         pub channel_id: Uint256,
230         pub signature: Signature,
231         pub htlc_signatures: Vec<Signature>,
232 }
233
234 pub struct RevokeAndACK {
235         pub channel_id: Uint256,
236         pub per_commitment_secret: [u8; 32],
237         pub next_per_commitment_point: PublicKey,
238 }
239
240 pub struct UpdateFee {
241         pub channel_id: Uint256,
242         pub feerate_per_kw: u32,
243 }
244
245 pub struct ChannelReestablish {
246         pub channel_id: Uint256,
247         pub next_local_commitment_number: u64,
248         pub next_remote_commitment_number: u64,
249         pub your_last_per_commitment_secret: Option<[u8; 32]>,
250         pub my_current_per_commitment_point: PublicKey,
251 }
252
253 #[derive(Clone)]
254 pub struct AnnouncementSignatures {
255         pub channel_id: Uint256,
256         pub short_channel_id: u64,
257         pub node_signature: Signature,
258         pub bitcoin_signature: Signature,
259 }
260
261 #[derive(Clone)]
262 pub enum NetAddress {
263         IPv4 {
264                 addr: [u8; 4],
265                 port: u16,
266         },
267         IPv6 {
268                 addr: [u8; 16],
269                 port: u16,
270         },
271         OnionV2 {
272                 addr: [u8; 10],
273                 port: u16,
274         },
275         OnionV3 {
276                 ed25519_pubkey: [u8; 32],
277                 checksum: u16,
278                 version: u8,
279                 port: u16,
280         },
281 }
282 impl NetAddress {
283         fn get_id(&self) -> u8 {
284                 match self {
285                         &NetAddress::IPv4 {..} => { 1 },
286                         &NetAddress::IPv6 {..} => { 2 },
287                         &NetAddress::OnionV2 {..} => { 3 },
288                         &NetAddress::OnionV3 {..} => { 4 },
289                 }
290         }
291 }
292
293 pub struct UnsignedNodeAnnouncement {
294         pub features: GlobalFeatures,
295         pub timestamp: u32,
296         pub node_id: PublicKey,
297         pub rgb: [u8; 3],
298         pub alias: [u8; 32],
299         /// List of addresses on which this node is reachable. Note that you may only have up to one
300         /// address of each type, if you have more, they may be silently discarded or we may panic!
301         pub addresses: Vec<NetAddress>,
302 }
303 pub struct NodeAnnouncement {
304         pub signature: Signature,
305         pub contents: UnsignedNodeAnnouncement,
306 }
307
308 #[derive(PartialEq, Clone)]
309 pub struct UnsignedChannelAnnouncement {
310         pub features: GlobalFeatures,
311         pub chain_hash: Sha256dHash,
312         pub short_channel_id: u64,
313         pub node_id_1: PublicKey,
314         pub node_id_2: PublicKey,
315         pub bitcoin_key_1: PublicKey,
316         pub bitcoin_key_2: PublicKey,
317 }
318 #[derive(PartialEq, Clone)]
319 pub struct ChannelAnnouncement {
320         pub node_signature_1: Signature,
321         pub node_signature_2: Signature,
322         pub bitcoin_signature_1: Signature,
323         pub bitcoin_signature_2: Signature,
324         pub contents: UnsignedChannelAnnouncement,
325 }
326
327 #[derive(PartialEq, Clone)]
328 pub struct UnsignedChannelUpdate {
329         pub chain_hash: Sha256dHash,
330         pub short_channel_id: u64,
331         pub timestamp: u32,
332         pub flags: u16,
333         pub cltv_expiry_delta: u16,
334         pub htlc_minimum_msat: u64,
335         pub fee_base_msat: u32,
336         pub fee_proportional_millionths: u32,
337 }
338 #[derive(PartialEq, Clone)]
339 pub struct ChannelUpdate {
340         pub signature: Signature,
341         pub contents: UnsignedChannelUpdate,
342 }
343
344 /// Used to put an error message in a HandleError
345 pub enum ErrorAction {
346         /// Indicates an inbound HTLC add resulted in a failure, and the UpdateFailHTLC provided in msg
347         /// should be sent back to the sender.
348         UpdateFailHTLC {
349                 msg: UpdateFailHTLC
350         },
351         /// The peer took some action which made us think they were useless. Disconnect them.
352         DisconnectPeer {},
353 }
354
355 pub struct HandleError { //TODO: rename me
356         pub err: &'static str,
357         pub msg: Option<ErrorAction>, //TODO: Make this required and rename it
358 }
359
360 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
361 /// transaction updates if they were pending.
362 pub struct CommitmentUpdate {
363         pub update_add_htlcs: Vec<UpdateAddHTLC>,
364         pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
365         pub update_fail_htlcs: Vec<UpdateFailHTLC>,
366         pub commitment_signed: CommitmentSigned,
367 }
368
369 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
370 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
371 /// paralell when the two calls have the same their_node_id.
372 pub trait ChannelMessageHandler : events::EventsProvider {
373         //Channel init:
374         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
375         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
376         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
377         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
378         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
379
380         // Channl close:
381         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
382         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
383
384         // HTLC handling:
385         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
386         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
387         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
388         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
389         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
390         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
391
392         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
393
394         // Channel-to-announce:
395         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
396
397         // Informational:
398         /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
399         /// is believed to be possible in the future (eg they're sending us messages we don't
400         /// understand or indicate they require unknown feature bits), no_connection_possible is set
401         /// and any outstanding channels should be failed.
402         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
403 }
404
405 pub trait RoutingMessageHandler {
406         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
407         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
408         /// or returning an Err otherwise.
409         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
410         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
411 }
412
413 pub struct OnionRealm0HopData {
414         pub short_channel_id: u64,
415         pub amt_to_forward: u64,
416         pub outgoing_cltv_value: u32,
417         // 12 bytes of 0-padding
418 }
419
420 pub struct OnionHopData {
421         pub realm: u8,
422         pub data: OnionRealm0HopData,
423         pub hmac: [u8; 32],
424 }
425 unsafe impl internal_traits::NoDealloc for OnionHopData{}
426
427 #[derive(Clone)]
428 pub struct OnionPacket {
429         pub version: u8,
430         pub public_key: PublicKey,
431         pub hop_data: [u8; 20*65],
432         pub hmac: [u8; 32],
433 }
434
435 pub struct DecodedOnionErrorPacket {
436         pub hmac: [u8; 32],
437         pub failuremsg: Vec<u8>,
438         pub pad: Vec<u8>,
439 }
440
441 #[derive(Clone)]
442 pub struct OnionErrorPacket {
443         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
444         // (TODO) We limit it in decode to much lower...
445         pub data: Vec<u8>,
446 }
447
448 impl Error for DecodeError {
449         fn description(&self) -> &str {
450                 match *self {
451                         DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
452                         DecodeError::BadPublicKey => "Invalid public key in packet",
453                         DecodeError::BadSignature => "Invalid signature in packet",
454                         DecodeError::WrongLength => "Data was wrong length for packet",
455                         DecodeError::ExtraAddressesPerType => "More than one address of a single type",
456                 }
457         }
458 }
459 impl fmt::Display for DecodeError {
460         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
461                 f.write_str(self.description())
462         }
463 }
464
465 impl fmt::Debug for HandleError {
466         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
467                 f.write_str(self.err)
468         }
469 }
470
471 macro_rules! secp_pubkey {
472         ( $ctx: expr, $slice: expr ) => {
473                 match PublicKey::from_slice($ctx, $slice) {
474                         Ok(key) => key,
475                         Err(_) => return Err(DecodeError::BadPublicKey)
476                 }
477         };
478 }
479
480 macro_rules! secp_signature {
481         ( $ctx: expr, $slice: expr ) => {
482                 match Signature::from_compact($ctx, $slice) {
483                         Ok(sig) => sig,
484                         Err(_) => return Err(DecodeError::BadSignature)
485                 }
486         };
487 }
488
489 impl MsgDecodable for LocalFeatures {
490         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
491                 if v.len() < 3 { return Err(DecodeError::WrongLength); }
492                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
493                 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
494                 let mut flags = Vec::with_capacity(len);
495                 flags.extend_from_slice(&v[2..2 + len]);
496                 Ok(Self {
497                         flags: flags
498                 })
499         }
500 }
501 impl MsgEncodable for LocalFeatures {
502         fn encode(&self) -> Vec<u8> {
503                 let mut res = Vec::with_capacity(self.flags.len() + 2);
504                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
505                 res.extend_from_slice(&self.flags[..]);
506                 res
507         }
508         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
509 }
510
511 impl MsgDecodable for GlobalFeatures {
512         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
513                 if v.len() < 3 { return Err(DecodeError::WrongLength); }
514                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
515                 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
516                 let mut flags = Vec::with_capacity(len);
517                 flags.extend_from_slice(&v[2..2 + len]);
518                 Ok(Self {
519                         flags: flags
520                 })
521         }
522 }
523 impl MsgEncodable for GlobalFeatures {
524         fn encode(&self) -> Vec<u8> {
525                 let mut res = Vec::with_capacity(self.flags.len() + 2);
526                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
527                 res.extend_from_slice(&self.flags[..]);
528                 res
529         }
530         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
531 }
532
533 impl MsgDecodable for Init {
534         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
535                 let global_features = GlobalFeatures::decode(v)?;
536                 if v.len() < global_features.flags.len() + 4 {
537                         return Err(DecodeError::WrongLength);
538                 }
539                 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
540                 Ok(Self {
541                         global_features: global_features,
542                         local_features: local_features,
543                 })
544         }
545 }
546 impl MsgEncodable for Init {
547         fn encode(&self) -> Vec<u8> {
548                 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
549                 res.extend_from_slice(&self.global_features.encode()[..]);
550                 res.extend_from_slice(&self.local_features.encode()[..]);
551                 res
552         }
553 }
554
555 impl MsgDecodable for OpenChannel {
556         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
557                 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
558                         return Err(DecodeError::WrongLength);
559                 }
560                 let ctx = Secp256k1::without_caps();
561
562                 let mut shutdown_scriptpubkey = None;
563                 if v.len() >= 321 {
564                         let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
565                         if v.len() < 321+len {
566                                 return Err(DecodeError::WrongLength);
567                         }
568                         shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
569                 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
570                         return Err(DecodeError::WrongLength);
571                 }
572
573                 Ok(OpenChannel {
574                         chain_hash: deserialize(&v[0..32]).unwrap(),
575                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
576                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
577                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
578                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
579                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
580                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
581                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
582                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
583                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
584                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
585                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
586                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
587                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
588                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
589                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
590                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
591                         channel_flags: v[318],
592                         shutdown_scriptpubkey: shutdown_scriptpubkey
593                 })
594         }
595 }
596 impl MsgEncodable for OpenChannel {
597         fn encode(&self) -> Vec<u8> {
598                 unimplemented!();
599         }
600 }
601
602 impl MsgDecodable for AcceptChannel {
603         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
604                 if v.len() < 32+4*8+4+2*2+6*33 {
605                         return Err(DecodeError::WrongLength);
606                 }
607                 let ctx = Secp256k1::without_caps();
608
609                 let mut shutdown_scriptpubkey = None;
610                 if v.len() >= 272 {
611                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
612                         if v.len() < 272+len {
613                                 return Err(DecodeError::WrongLength);
614                         }
615                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
616                 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
617                         return Err(DecodeError::WrongLength);
618                 }
619
620                 Ok(Self {
621                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
622                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
623                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
624                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
625                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
626                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
627                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
628                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
629                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
630                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
631                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
632                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
633                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
634                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
635                         shutdown_scriptpubkey: shutdown_scriptpubkey
636                 })
637         }
638 }
639 impl MsgEncodable for AcceptChannel {
640         fn encode(&self) -> Vec<u8> {
641                 let mut res = match &self.shutdown_scriptpubkey {
642                         &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
643                         &None => Vec::with_capacity(270),
644                 };
645                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
646                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
647                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
648                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
649                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
650                 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
651                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
652                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
653                 res.extend_from_slice(&self.funding_pubkey.serialize());
654                 res.extend_from_slice(&self.revocation_basepoint.serialize());
655                 res.extend_from_slice(&self.payment_basepoint.serialize());
656                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
657                 res.extend_from_slice(&self.htlc_basepoint.serialize());
658                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
659                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
660                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
661                         res.extend_from_slice(&script[..]);
662                 }
663                 res
664         }
665 }
666
667 impl MsgDecodable for FundingCreated {
668         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
669                 if v.len() < 32+32+2+64 {
670                         return Err(DecodeError::WrongLength);
671                 }
672                 let ctx = Secp256k1::without_caps();
673                 Ok(Self {
674                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
675                         funding_txid: deserialize(&v[32..64]).unwrap(),
676                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
677                         signature: secp_signature!(&ctx, &v[66..130]),
678                 })
679         }
680 }
681 impl MsgEncodable for FundingCreated {
682         fn encode(&self) -> Vec<u8> {
683                 let mut res = Vec::with_capacity(32+32+2+64);
684                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
685                 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
686                 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
687                 let secp_ctx = Secp256k1::without_caps();
688                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
689                 res
690         }
691 }
692
693 impl MsgDecodable for FundingSigned {
694         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
695                 if v.len() < 32+64 {
696                         return Err(DecodeError::WrongLength);
697                 }
698                 let ctx = Secp256k1::without_caps();
699                 Ok(Self {
700                         channel_id: deserialize(&v[0..32]).unwrap(),
701                         signature: secp_signature!(&ctx, &v[32..96]),
702                 })
703         }
704 }
705 impl MsgEncodable for FundingSigned {
706         fn encode(&self) -> Vec<u8> {
707                 unimplemented!();
708         }
709 }
710
711 impl MsgDecodable for FundingLocked {
712         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
713                 if v.len() < 32+33 {
714                         return Err(DecodeError::WrongLength);
715                 }
716                 let ctx = Secp256k1::without_caps();
717                 Ok(Self {
718                         channel_id: deserialize(&v[0..32]).unwrap(),
719                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
720                 })
721         }
722 }
723 impl MsgEncodable for FundingLocked {
724         fn encode(&self) -> Vec<u8> {
725                 let mut res = Vec::with_capacity(32+33);
726                 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
727                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
728                 res
729         }
730 }
731
732 impl MsgDecodable for Shutdown {
733         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
734                 if v.len() < 32 + 2 {
735                         return Err(DecodeError::WrongLength);
736                 }
737                 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
738                 if v.len() < 32 + 2 + scriptlen {
739                         return Err(DecodeError::WrongLength);
740                 }
741                 Ok(Self {
742                         channel_id: deserialize(&v[0..32]).unwrap(),
743                         scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
744                 })
745         }
746 }
747 impl MsgEncodable for Shutdown {
748         fn encode(&self) -> Vec<u8> {
749                 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
750                 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
751                 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
752                 res.extend_from_slice(&self.scriptpubkey[..]);
753                 res
754         }
755 }
756
757 impl MsgDecodable for ClosingSigned {
758         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
759                 if v.len() < 32 + 8 + 64 {
760                         return Err(DecodeError::WrongLength);
761                 }
762                 let secp_ctx = Secp256k1::without_caps();
763                 Ok(Self {
764                         channel_id: deserialize(&v[0..32]).unwrap(),
765                         fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
766                         signature: secp_signature!(&secp_ctx, &v[40..104]),
767                 })
768         }
769 }
770 impl MsgEncodable for ClosingSigned {
771         fn encode(&self) -> Vec<u8> {
772                 let mut res = Vec::with_capacity(32+8+64);
773                 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
774                 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
775                 let secp_ctx = Secp256k1::without_caps();
776                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
777                 res
778         }
779 }
780
781 impl MsgDecodable for UpdateAddHTLC {
782         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
783                 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
784                         return Err(DecodeError::WrongLength);
785                 }
786                 let mut payment_hash = [0; 32];
787                 payment_hash.copy_from_slice(&v[48..80]);
788                 Ok(Self{
789                         channel_id: deserialize(&v[0..32]).unwrap(),
790                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
791                         amount_msat: byte_utils::slice_to_be64(&v[40..48]),
792                         payment_hash,
793                         cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
794                         onion_routing_packet: OnionPacket::decode(&v[84..])?,
795                 })
796         }
797 }
798 impl MsgEncodable for UpdateAddHTLC {
799         fn encode(&self) -> Vec<u8> {
800                 unimplemented!();
801         }
802 }
803
804 impl MsgDecodable for UpdateFulfillHTLC {
805         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
806                 if v.len() < 32+8+32 {
807                         return Err(DecodeError::WrongLength);
808                 }
809                 let mut payment_preimage = [0; 32];
810                 payment_preimage.copy_from_slice(&v[40..72]);
811                 Ok(Self{
812                         channel_id: deserialize(&v[0..32]).unwrap(),
813                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
814                         payment_preimage,
815                 })
816         }
817 }
818 impl MsgEncodable for UpdateFulfillHTLC {
819         fn encode(&self) -> Vec<u8> {
820                 unimplemented!();
821         }
822 }
823
824 impl MsgDecodable for UpdateFailHTLC {
825         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
826                 if v.len() < 32+8 {
827                         return Err(DecodeError::WrongLength);
828                 }
829                 Ok(Self{
830                         channel_id: deserialize(&v[0..32]).unwrap(),
831                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
832                         reason: OnionErrorPacket::decode(&v[40..])?,
833                 })
834         }
835 }
836 impl MsgEncodable for UpdateFailHTLC {
837         fn encode(&self) -> Vec<u8> {
838                 unimplemented!();
839         }
840 }
841
842 impl MsgDecodable for UpdateFailMalformedHTLC {
843         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
844                 if v.len() < 32+8+32+2 {
845                         return Err(DecodeError::WrongLength);
846                 }
847                 let mut sha256_of_onion = [0; 32];
848                 sha256_of_onion.copy_from_slice(&v[40..72]);
849                 Ok(Self{
850                         channel_id: deserialize(&v[0..32]).unwrap(),
851                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
852                         sha256_of_onion,
853                         failure_code: byte_utils::slice_to_be16(&v[72..74]),
854                 })
855         }
856 }
857 impl MsgEncodable for UpdateFailMalformedHTLC {
858         fn encode(&self) -> Vec<u8> {
859                 unimplemented!();
860         }
861 }
862
863 impl MsgDecodable for CommitmentSigned {
864         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
865                 if v.len() < 32+64+2 {
866                         return Err(DecodeError::WrongLength);
867                 }
868                 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
869                 if v.len() < 32+64+2+htlcs*64 {
870                         return Err(DecodeError::WrongLength);
871                 }
872                 let mut htlc_signatures = Vec::with_capacity(htlcs);
873                 let secp_ctx = Secp256k1::without_caps();
874                 for i in 0..htlcs {
875                         htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
876                 }
877                 Ok(Self {
878                         channel_id: deserialize(&v[0..32]).unwrap(),
879                         signature: secp_signature!(&secp_ctx, &v[32..96]),
880                         htlc_signatures,
881                 })
882         }
883 }
884 impl MsgEncodable for CommitmentSigned {
885         fn encode(&self) -> Vec<u8> {
886                 unimplemented!();
887         }
888 }
889
890 impl MsgDecodable for RevokeAndACK {
891         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
892                 if v.len() < 32+32+33 {
893                         return Err(DecodeError::WrongLength);
894                 }
895                 let mut per_commitment_secret = [0; 32];
896                 per_commitment_secret.copy_from_slice(&v[32..64]);
897                 let secp_ctx = Secp256k1::without_caps();
898                 Ok(Self {
899                         channel_id: deserialize(&v[0..32]).unwrap(),
900                         per_commitment_secret,
901                         next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
902                 })
903         }
904 }
905 impl MsgEncodable for RevokeAndACK {
906         fn encode(&self) -> Vec<u8> {
907                 unimplemented!();
908         }
909 }
910
911 impl MsgDecodable for UpdateFee {
912         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
913                 if v.len() < 32+4 {
914                         return Err(DecodeError::WrongLength);
915                 }
916                 Ok(Self {
917                         channel_id: deserialize(&v[0..32]).unwrap(),
918                         feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
919                 })
920         }
921 }
922 impl MsgEncodable for UpdateFee {
923         fn encode(&self) -> Vec<u8> {
924                 unimplemented!();
925         }
926 }
927
928 impl MsgDecodable for ChannelReestablish {
929         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
930                 unimplemented!();
931         }
932 }
933 impl MsgEncodable for ChannelReestablish {
934         fn encode(&self) -> Vec<u8> {
935                 unimplemented!();
936         }
937 }
938
939 impl MsgDecodable for AnnouncementSignatures {
940         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
941                 if v.len() < 32+8+64*2 {
942                         return Err(DecodeError::WrongLength);
943                 }
944                 let secp_ctx = Secp256k1::without_caps();
945                 Ok(Self {
946                         channel_id: deserialize(&v[0..32]).unwrap(),
947                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
948                         node_signature: secp_signature!(&secp_ctx, &v[40..104]),
949                         bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
950                 })
951         }
952 }
953 impl MsgEncodable for AnnouncementSignatures {
954         fn encode(&self) -> Vec<u8> {
955                 let mut res = Vec::with_capacity(32+8+64*2);
956                 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
957                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
958                 let secp_ctx = Secp256k1::without_caps();
959                 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
960                 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
961                 res
962         }
963 }
964
965 impl MsgDecodable for UnsignedNodeAnnouncement {
966         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
967                 let features = GlobalFeatures::decode(&v[..])?;
968                 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
969                         return Err(DecodeError::WrongLength);
970                 }
971                 let start = features.encoded_len();
972
973                 let mut rgb = [0; 3];
974                 rgb.copy_from_slice(&v[start + 37..start + 40]);
975
976                 let mut alias = [0; 32];
977                 alias.copy_from_slice(&v[start + 40..start + 72]);
978
979                 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
980                 if v.len() < start + 74 + addrlen {
981                         return Err(DecodeError::WrongLength);
982                 }
983
984                 let mut addresses = Vec::with_capacity(4);
985                 let mut read_pos = start + 74;
986                 loop {
987                         if v.len() <= read_pos { break; }
988                         match v[read_pos] {
989                                 0 => { read_pos += 1; },
990                                 1 => {
991                                         if v.len() < read_pos + 1 + 6 {
992                                                 return Err(DecodeError::WrongLength);
993                                         }
994                                         if addresses.len() > 0 {
995                                                 return Err(DecodeError::ExtraAddressesPerType);
996                                         }
997                                         let mut addr = [0; 4];
998                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
999                                         addresses.push(NetAddress::IPv4 {
1000                                                 addr,
1001                                                 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1002                                         });
1003                                         read_pos += 1 + 6;
1004                                 },
1005                                 2 => {
1006                                         if v.len() < read_pos + 1 + 18 {
1007                                                 return Err(DecodeError::WrongLength);
1008                                         }
1009                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1010                                                 return Err(DecodeError::ExtraAddressesPerType);
1011                                         }
1012                                         let mut addr = [0; 16];
1013                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1014                                         addresses.push(NetAddress::IPv6 {
1015                                                 addr,
1016                                                 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1017                                         });
1018                                         read_pos += 1 + 18;
1019                                 },
1020                                 3 => {
1021                                         if v.len() < read_pos + 1 + 12 {
1022                                                 return Err(DecodeError::WrongLength);
1023                                         }
1024                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1025                                                 return Err(DecodeError::ExtraAddressesPerType);
1026                                         }
1027                                         let mut addr = [0; 10];
1028                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1029                                         addresses.push(NetAddress::OnionV2 {
1030                                                 addr,
1031                                                 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1032                                         });
1033                                         read_pos += 1 + 12;
1034                                 },
1035                                 4 => {
1036                                         if v.len() < read_pos + 1 + 37 {
1037                                                 return Err(DecodeError::WrongLength);
1038                                         }
1039                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1040                                                 return Err(DecodeError::ExtraAddressesPerType);
1041                                         }
1042                                         let mut ed25519_pubkey = [0; 32];
1043                                         ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1044                                         addresses.push(NetAddress::OnionV3 {
1045                                                 ed25519_pubkey,
1046                                                 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1047                                                 version: v[read_pos + 35],
1048                                                 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1049                                         });
1050                                         read_pos += 1 + 37;
1051                                 },
1052                                 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1053                         }
1054                 }
1055
1056                 let secp_ctx = Secp256k1::without_caps();
1057                 Ok(Self {
1058                         features,
1059                         timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1060                         node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1061                         rgb,
1062                         alias,
1063                         addresses,
1064                 })
1065         }
1066 }
1067 impl MsgEncodable for UnsignedNodeAnnouncement {
1068         fn encode(&self) -> Vec<u8> {
1069                 let features = self.features.encode();
1070                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1071                 res.extend_from_slice(&features[..]);
1072                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1073                 res.extend_from_slice(&self.node_id.serialize());
1074                 res.extend_from_slice(&self.rgb);
1075                 res.extend_from_slice(&self.alias);
1076                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1077                 let mut addrs_to_encode = self.addresses.clone();
1078                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1079                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1080                 for addr in addrs_to_encode.iter() {
1081                         match addr {
1082                                 &NetAddress::IPv4{addr, port} => {
1083                                         addr_slice.push(1);
1084                                         addr_slice.extend_from_slice(&addr);
1085                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1086                                 },
1087                                 &NetAddress::IPv6{addr, port} => {
1088                                         addr_slice.push(2);
1089                                         addr_slice.extend_from_slice(&addr);
1090                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1091                                 },
1092                                 &NetAddress::OnionV2{addr, port} => {
1093                                         addr_slice.push(3);
1094                                         addr_slice.extend_from_slice(&addr);
1095                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1096                                 },
1097                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1098                                         addr_slice.push(4);
1099                                         addr_slice.extend_from_slice(&ed25519_pubkey);
1100                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1101                                         addr_slice.push(version);
1102                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1103                                 },
1104                         }
1105                 }
1106                 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1107                 res.extend_from_slice(&addr_slice[..]);
1108                 res
1109         }
1110 }
1111
1112 impl MsgDecodable for NodeAnnouncement {
1113         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1114                 if v.len() < 64 {
1115                         return Err(DecodeError::WrongLength);
1116                 }
1117                 let secp_ctx = Secp256k1::without_caps();
1118                 Ok(Self {
1119                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1120                         contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1121                 })
1122         }
1123 }
1124 impl MsgEncodable for NodeAnnouncement {
1125         fn encode(&self) -> Vec<u8> {
1126                 unimplemented!();
1127         }
1128 }
1129
1130 impl MsgDecodable for UnsignedChannelAnnouncement {
1131         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1132                 let features = GlobalFeatures::decode(&v[..])?;
1133                 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1134                         return Err(DecodeError::WrongLength);
1135                 }
1136                 let start = features.encoded_len();
1137                 let secp_ctx = Secp256k1::without_caps();
1138                 Ok(Self {
1139                         features,
1140                         chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1141                         short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1142                         node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1143                         node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1144                         bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1145                         bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1146                 })
1147         }
1148 }
1149 impl MsgEncodable for UnsignedChannelAnnouncement {
1150         fn encode(&self) -> Vec<u8> {
1151                 let features = self.features.encode();
1152                 let mut res = Vec::with_capacity(172 + features.len());
1153                 res.extend_from_slice(&features[..]);
1154                 res.extend_from_slice(&self.chain_hash[..]);
1155                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1156                 res.extend_from_slice(&self.node_id_1.serialize());
1157                 res.extend_from_slice(&self.node_id_2.serialize());
1158                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1159                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1160                 res
1161         }
1162 }
1163
1164 impl MsgDecodable for ChannelAnnouncement {
1165         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1166                 if v.len() < 64*4 {
1167                         return Err(DecodeError::WrongLength);
1168                 }
1169                 let secp_ctx = Secp256k1::without_caps();
1170                 Ok(Self {
1171                         node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1172                         node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1173                         bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1174                         bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1175                         contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1176                 })
1177         }
1178 }
1179 impl MsgEncodable for ChannelAnnouncement {
1180         fn encode(&self) -> Vec<u8> {
1181                 unimplemented!();
1182         }
1183 }
1184
1185 impl MsgDecodable for UnsignedChannelUpdate {
1186         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1187                 if v.len() < 32+8+4+2+2+8+4+4 {
1188                         return Err(DecodeError::WrongLength);
1189                 }
1190                 Ok(Self {
1191                         chain_hash: deserialize(&v[0..32]).unwrap(),
1192                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1193                         timestamp: byte_utils::slice_to_be32(&v[40..44]),
1194                         flags: byte_utils::slice_to_be16(&v[44..46]),
1195                         cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1196                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1197                         fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1198                         fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1199                 })
1200         }
1201 }
1202 impl MsgEncodable for UnsignedChannelUpdate {
1203         fn encode(&self) -> Vec<u8> {
1204                 let mut res = Vec::with_capacity(64);
1205                 res.extend_from_slice(&self.chain_hash[..]);
1206                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1207                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1208                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1209                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1210                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1211                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1212                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1213                 res
1214         }
1215 }
1216
1217 impl MsgDecodable for ChannelUpdate {
1218         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1219                 if v.len() < 128 {
1220                         return Err(DecodeError::WrongLength);
1221                 }
1222                 let secp_ctx = Secp256k1::without_caps();
1223                 Ok(Self {
1224                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1225                         contents: UnsignedChannelUpdate::decode(&v[64..])?,
1226                 })
1227         }
1228 }
1229 impl MsgEncodable for ChannelUpdate {
1230         fn encode(&self) -> Vec<u8> {
1231                 let mut res = Vec::with_capacity(128);
1232                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1233                 res.extend_from_slice(&self.contents.encode()[..]);
1234                 res
1235         }
1236 }
1237
1238 impl MsgDecodable for OnionRealm0HopData {
1239         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1240                 if v.len() < 32 {
1241                         return Err(DecodeError::WrongLength);
1242                 }
1243                 Ok(OnionRealm0HopData {
1244                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1245                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1246                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1247                 })
1248         }
1249 }
1250 impl MsgEncodable for OnionRealm0HopData {
1251         fn encode(&self) -> Vec<u8> {
1252                 let mut res = Vec::with_capacity(32);
1253                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1254                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1255                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1256                 res.resize(32, 0);
1257                 res
1258         }
1259 }
1260
1261 impl MsgDecodable for OnionHopData {
1262         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1263                 if v.len() < 65 {
1264                         return Err(DecodeError::WrongLength);
1265                 }
1266                 let realm = v[0];
1267                 if realm != 0 {
1268                         return Err(DecodeError::UnknownRealmByte);
1269                 }
1270                 let mut hmac = [0; 32];
1271                 hmac[..].copy_from_slice(&v[33..65]);
1272                 Ok(OnionHopData {
1273                         realm: realm,
1274                         data: OnionRealm0HopData::decode(&v[1..33])?,
1275                         hmac: hmac,
1276                 })
1277         }
1278 }
1279 impl MsgEncodable for OnionHopData {
1280         fn encode(&self) -> Vec<u8> {
1281                 let mut res = Vec::with_capacity(65);
1282                 res.push(self.realm);
1283                 res.extend_from_slice(&self.data.encode()[..]);
1284                 res.extend_from_slice(&self.hmac);
1285                 res
1286         }
1287 }
1288
1289 impl MsgDecodable for OnionPacket {
1290         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1291                 if v.len() < 1+33+20*65+32 {
1292                         return Err(DecodeError::WrongLength);
1293                 }
1294                 let mut hop_data = [0; 20*65];
1295                 hop_data.copy_from_slice(&v[34..1334]);
1296                 let mut hmac = [0; 32];
1297                 hmac.copy_from_slice(&v[1334..1366]);
1298                 let secp_ctx = Secp256k1::without_caps();
1299                 Ok(Self {
1300                         version: v[0],
1301                         public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1302                         hop_data,
1303                         hmac,
1304                 })
1305         }
1306 }
1307 impl MsgEncodable for OnionPacket {
1308         fn encode(&self) -> Vec<u8> {
1309                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1310                 res.push(self.version);
1311                 res.extend_from_slice(&self.public_key.serialize());
1312                 res.extend_from_slice(&self.hop_data);
1313                 res.extend_from_slice(&self.hmac);
1314                 res
1315         }
1316 }
1317
1318 impl MsgDecodable for DecodedOnionErrorPacket {
1319         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1320                 unimplemented!();
1321         }
1322 }
1323 impl MsgEncodable for DecodedOnionErrorPacket {
1324         fn encode(&self) -> Vec<u8> {
1325                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1326                 res.extend_from_slice(&self.hmac);
1327                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1328                 res.extend_from_slice(&self.failuremsg);
1329                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1330                 res.extend_from_slice(&self.pad);
1331                 res
1332         }
1333 }
1334
1335 impl MsgDecodable for OnionErrorPacket {
1336         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1337                 if v.len() < 2 {
1338                         return Err(DecodeError::WrongLength);
1339                 }
1340                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1341                 if v.len() < 2 + len {
1342                         return Err(DecodeError::WrongLength);
1343                 }
1344                 Ok(Self {
1345                         data: v[2..len+2].to_vec(),
1346                 })
1347         }
1348 }
1349 impl MsgEncodable for OnionErrorPacket {
1350         fn encode(&self) -> Vec<u8> {
1351                 unimplemented!();
1352         }
1353 }
1354