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