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