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