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