Rename ErrorMessage
[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
386 pub trait RoutingMessageHandler {
387         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
388         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
389         /// or returning an Err otherwise.
390         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
391         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
392 }
393
394 pub struct OnionRealm0HopData {
395         pub short_channel_id: u64,
396         pub amt_to_forward: u64,
397         pub outgoing_cltv_value: u32,
398         // 12 bytes of 0-padding
399 }
400
401 pub struct OnionHopData {
402         pub realm: u8,
403         pub data: OnionRealm0HopData,
404         pub hmac: [u8; 32],
405 }
406 unsafe impl internal_traits::NoDealloc for OnionHopData{}
407
408 #[derive(Clone)]
409 pub struct OnionPacket {
410         pub version: u8,
411         pub public_key: PublicKey,
412         pub hop_data: [u8; 20*65],
413         pub hmac: [u8; 32],
414 }
415
416 pub struct DecodedOnionErrorPacket {
417         pub hmac: [u8; 32],
418         pub failuremsg: Vec<u8>,
419         pub pad: Vec<u8>,
420 }
421
422 #[derive(Clone)]
423 pub struct OnionErrorPacket {
424         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
425         // (TODO) We limit it in decode to much lower...
426         pub data: Vec<u8>,
427 }
428
429 impl Error for DecodeError {
430         fn description(&self) -> &str {
431                 match *self {
432                         DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
433                         DecodeError::BadPublicKey => "Invalid public key in packet",
434                         DecodeError::BadSignature => "Invalid signature in packet",
435                         DecodeError::WrongLength => "Data was wrong length for packet",
436                         DecodeError::ExtraAddressesPerType => "More than one address of a single type",
437                 }
438         }
439 }
440 impl fmt::Display for DecodeError {
441         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
442                 f.write_str(self.description())
443         }
444 }
445
446 impl fmt::Debug for HandleError {
447         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
448                 f.write_str(self.err)
449         }
450 }
451
452 macro_rules! secp_pubkey {
453         ( $ctx: expr, $slice: expr ) => {
454                 match PublicKey::from_slice($ctx, $slice) {
455                         Ok(key) => key,
456                         Err(_) => return Err(DecodeError::BadPublicKey)
457                 }
458         };
459 }
460
461 macro_rules! secp_signature {
462         ( $ctx: expr, $slice: expr ) => {
463                 match Signature::from_compact($ctx, $slice) {
464                         Ok(sig) => sig,
465                         Err(_) => return Err(DecodeError::BadSignature)
466                 }
467         };
468 }
469
470 impl MsgDecodable for LocalFeatures {
471         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
472                 if v.len() < 3 { return Err(DecodeError::WrongLength); }
473                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
474                 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
475                 let mut flags = Vec::with_capacity(len);
476                 flags.extend_from_slice(&v[2..2 + len]);
477                 Ok(Self {
478                         flags: flags
479                 })
480         }
481 }
482 impl MsgEncodable for LocalFeatures {
483         fn encode(&self) -> Vec<u8> {
484                 let mut res = Vec::with_capacity(self.flags.len() + 2);
485                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
486                 res.extend_from_slice(&self.flags[..]);
487                 res
488         }
489         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
490 }
491
492 impl MsgDecodable for GlobalFeatures {
493         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
494                 if v.len() < 3 { return Err(DecodeError::WrongLength); }
495                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
496                 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
497                 let mut flags = Vec::with_capacity(len);
498                 flags.extend_from_slice(&v[2..2 + len]);
499                 Ok(Self {
500                         flags: flags
501                 })
502         }
503 }
504 impl MsgEncodable for GlobalFeatures {
505         fn encode(&self) -> Vec<u8> {
506                 let mut res = Vec::with_capacity(self.flags.len() + 2);
507                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
508                 res.extend_from_slice(&self.flags[..]);
509                 res
510         }
511         fn encoded_len(&self) -> usize { self.flags.len() + 2 }
512 }
513
514 impl MsgDecodable for Init {
515         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
516                 let global_features = GlobalFeatures::decode(v)?;
517                 if v.len() < global_features.flags.len() + 4 {
518                         return Err(DecodeError::WrongLength);
519                 }
520                 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
521                 Ok(Self {
522                         global_features: global_features,
523                         local_features: local_features,
524                 })
525         }
526 }
527 impl MsgEncodable for Init {
528         fn encode(&self) -> Vec<u8> {
529                 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
530                 res.extend_from_slice(&self.global_features.encode()[..]);
531                 res.extend_from_slice(&self.local_features.encode()[..]);
532                 res
533         }
534 }
535
536 impl MsgDecodable for OpenChannel {
537         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
538                 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
539                         return Err(DecodeError::WrongLength);
540                 }
541                 let ctx = Secp256k1::without_caps();
542
543                 let mut shutdown_scriptpubkey = None;
544                 if v.len() >= 321 {
545                         let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
546                         if v.len() < 321+len {
547                                 return Err(DecodeError::WrongLength);
548                         }
549                         shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
550                 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
551                         return Err(DecodeError::WrongLength);
552                 }
553
554                 Ok(OpenChannel {
555                         chain_hash: deserialize(&v[0..32]).unwrap(),
556                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
557                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
558                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
559                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
560                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
561                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
562                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
563                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
564                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
565                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
566                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
567                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
568                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
569                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
570                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
571                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
572                         channel_flags: v[318],
573                         shutdown_scriptpubkey: shutdown_scriptpubkey
574                 })
575         }
576 }
577 impl MsgEncodable for OpenChannel {
578         fn encode(&self) -> Vec<u8> {
579                 unimplemented!();
580         }
581 }
582
583 impl MsgDecodable for AcceptChannel {
584         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
585                 if v.len() < 32+4*8+4+2*2+6*33 {
586                         return Err(DecodeError::WrongLength);
587                 }
588                 let ctx = Secp256k1::without_caps();
589
590                 let mut shutdown_scriptpubkey = None;
591                 if v.len() >= 272 {
592                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
593                         if v.len() < 272+len {
594                                 return Err(DecodeError::WrongLength);
595                         }
596                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
597                 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
598                         return Err(DecodeError::WrongLength);
599                 }
600
601                 Ok(Self {
602                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
603                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
604                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
605                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
606                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
607                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
608                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
609                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
610                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
611                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
612                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
613                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
614                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
615                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
616                         shutdown_scriptpubkey: shutdown_scriptpubkey
617                 })
618         }
619 }
620 impl MsgEncodable for AcceptChannel {
621         fn encode(&self) -> Vec<u8> {
622                 let mut res = match &self.shutdown_scriptpubkey {
623                         &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
624                         &None => Vec::with_capacity(270),
625                 };
626                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
627                 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
628                 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
629                 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
630                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
631                 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
632                 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
633                 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
634                 res.extend_from_slice(&self.funding_pubkey.serialize());
635                 res.extend_from_slice(&self.revocation_basepoint.serialize());
636                 res.extend_from_slice(&self.payment_basepoint.serialize());
637                 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
638                 res.extend_from_slice(&self.htlc_basepoint.serialize());
639                 res.extend_from_slice(&self.first_per_commitment_point.serialize());
640                 if let &Some(ref script) = &self.shutdown_scriptpubkey {
641                         res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
642                         res.extend_from_slice(&script[..]);
643                 }
644                 res
645         }
646 }
647
648 impl MsgDecodable for FundingCreated {
649         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
650                 if v.len() < 32+32+2+64 {
651                         return Err(DecodeError::WrongLength);
652                 }
653                 let ctx = Secp256k1::without_caps();
654                 Ok(Self {
655                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
656                         funding_txid: deserialize(&v[32..64]).unwrap(),
657                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
658                         signature: secp_signature!(&ctx, &v[66..130]),
659                 })
660         }
661 }
662 impl MsgEncodable for FundingCreated {
663         fn encode(&self) -> Vec<u8> {
664                 let mut res = Vec::with_capacity(32+32+2+64);
665                 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
666                 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
667                 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
668                 let secp_ctx = Secp256k1::without_caps();
669                 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
670                 res
671         }
672 }
673
674 impl MsgDecodable for FundingSigned {
675         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
676                 if v.len() < 32+64 {
677                         return Err(DecodeError::WrongLength);
678                 }
679                 let ctx = Secp256k1::without_caps();
680                 Ok(Self {
681                         channel_id: deserialize(&v[0..32]).unwrap(),
682                         signature: secp_signature!(&ctx, &v[32..96]),
683                 })
684         }
685 }
686 impl MsgEncodable for FundingSigned {
687         fn encode(&self) -> Vec<u8> {
688                 unimplemented!();
689         }
690 }
691
692 impl MsgDecodable for FundingLocked {
693         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
694                 if v.len() < 32+33 {
695                         return Err(DecodeError::WrongLength);
696                 }
697                 let ctx = Secp256k1::without_caps();
698                 Ok(Self {
699                         channel_id: deserialize(&v[0..32]).unwrap(),
700                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
701                 })
702         }
703 }
704 impl MsgEncodable for FundingLocked {
705         fn encode(&self) -> Vec<u8> {
706                 let mut res = Vec::with_capacity(32+33);
707                 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
708                 res.extend_from_slice(&self.next_per_commitment_point.serialize());
709                 res
710         }
711 }
712
713 impl MsgDecodable for Shutdown {
714         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
715                 if v.len() < 32 + 2 {
716                         return Err(DecodeError::WrongLength);
717                 }
718                 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
719                 if v.len() < 32 + 2 + scriptlen {
720                         return Err(DecodeError::WrongLength);
721                 }
722                 Ok(Self {
723                         channel_id: deserialize(&v[0..32]).unwrap(),
724                         scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
725                 })
726         }
727 }
728 impl MsgEncodable for Shutdown {
729         fn encode(&self) -> Vec<u8> {
730                 unimplemented!();
731         }
732 }
733
734 impl MsgDecodable for ClosingSigned {
735         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
736                 if v.len() < 32 + 8 + 64 {
737                         return Err(DecodeError::WrongLength);
738                 }
739                 let secp_ctx = Secp256k1::without_caps();
740                 Ok(Self {
741                         channel_id: deserialize(&v[0..32]).unwrap(),
742                         fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
743                         signature: secp_signature!(&secp_ctx, &v[40..104]),
744                 })
745         }
746 }
747 impl MsgEncodable for ClosingSigned {
748         fn encode(&self) -> Vec<u8> {
749                 unimplemented!();
750         }
751 }
752
753 impl MsgDecodable for UpdateAddHTLC {
754         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
755                 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
756                         return Err(DecodeError::WrongLength);
757                 }
758                 let mut payment_hash = [0; 32];
759                 payment_hash.copy_from_slice(&v[48..80]);
760                 Ok(Self{
761                         channel_id: deserialize(&v[0..32]).unwrap(),
762                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
763                         amount_msat: byte_utils::slice_to_be64(&v[40..48]),
764                         payment_hash,
765                         cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
766                         onion_routing_packet: OnionPacket::decode(&v[84..])?,
767                 })
768         }
769 }
770 impl MsgEncodable for UpdateAddHTLC {
771         fn encode(&self) -> Vec<u8> {
772                 unimplemented!();
773         }
774 }
775
776 impl MsgDecodable for UpdateFulfillHTLC {
777         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
778                 if v.len() < 32+8+32 {
779                         return Err(DecodeError::WrongLength);
780                 }
781                 let mut payment_preimage = [0; 32];
782                 payment_preimage.copy_from_slice(&v[40..72]);
783                 Ok(Self{
784                         channel_id: deserialize(&v[0..32]).unwrap(),
785                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
786                         payment_preimage,
787                 })
788         }
789 }
790 impl MsgEncodable for UpdateFulfillHTLC {
791         fn encode(&self) -> Vec<u8> {
792                 unimplemented!();
793         }
794 }
795
796 impl MsgDecodable for UpdateFailHTLC {
797         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
798                 if v.len() < 32+8 {
799                         return Err(DecodeError::WrongLength);
800                 }
801                 Ok(Self{
802                         channel_id: deserialize(&v[0..32]).unwrap(),
803                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
804                         reason: OnionErrorPacket::decode(&v[40..])?,
805                 })
806         }
807 }
808 impl MsgEncodable for UpdateFailHTLC {
809         fn encode(&self) -> Vec<u8> {
810                 unimplemented!();
811         }
812 }
813
814 impl MsgDecodable for UpdateFailMalformedHTLC {
815         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
816                 if v.len() < 32+8+32+2 {
817                         return Err(DecodeError::WrongLength);
818                 }
819                 let mut sha256_of_onion = [0; 32];
820                 sha256_of_onion.copy_from_slice(&v[40..72]);
821                 Ok(Self{
822                         channel_id: deserialize(&v[0..32]).unwrap(),
823                         htlc_id: byte_utils::slice_to_be64(&v[32..40]),
824                         sha256_of_onion,
825                         failure_code: byte_utils::slice_to_be16(&v[72..74]),
826                 })
827         }
828 }
829 impl MsgEncodable for UpdateFailMalformedHTLC {
830         fn encode(&self) -> Vec<u8> {
831                 unimplemented!();
832         }
833 }
834
835 impl MsgDecodable for CommitmentSigned {
836         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
837                 if v.len() < 32+64+2 {
838                         return Err(DecodeError::WrongLength);
839                 }
840                 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
841                 if v.len() < 32+64+2+htlcs*64 {
842                         return Err(DecodeError::WrongLength);
843                 }
844                 let mut htlc_signatures = Vec::with_capacity(htlcs);
845                 let secp_ctx = Secp256k1::without_caps();
846                 for i in 0..htlcs {
847                         htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
848                 }
849                 Ok(Self {
850                         channel_id: deserialize(&v[0..32]).unwrap(),
851                         signature: secp_signature!(&secp_ctx, &v[32..96]),
852                         htlc_signatures,
853                 })
854         }
855 }
856 impl MsgEncodable for CommitmentSigned {
857         fn encode(&self) -> Vec<u8> {
858                 unimplemented!();
859         }
860 }
861
862 impl MsgDecodable for RevokeAndACK {
863         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
864                 if v.len() < 32+32+33 {
865                         return Err(DecodeError::WrongLength);
866                 }
867                 let mut per_commitment_secret = [0; 32];
868                 per_commitment_secret.copy_from_slice(&v[32..64]);
869                 let secp_ctx = Secp256k1::without_caps();
870                 Ok(Self {
871                         channel_id: deserialize(&v[0..32]).unwrap(),
872                         per_commitment_secret,
873                         next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
874                 })
875         }
876 }
877 impl MsgEncodable for RevokeAndACK {
878         fn encode(&self) -> Vec<u8> {
879                 unimplemented!();
880         }
881 }
882
883 impl MsgDecodable for UpdateFee {
884         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
885                 if v.len() < 32+4 {
886                         return Err(DecodeError::WrongLength);
887                 }
888                 Ok(Self {
889                         channel_id: deserialize(&v[0..32]).unwrap(),
890                         feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
891                 })
892         }
893 }
894 impl MsgEncodable for UpdateFee {
895         fn encode(&self) -> Vec<u8> {
896                 unimplemented!();
897         }
898 }
899
900 impl MsgDecodable for ChannelReestablish {
901         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
902                 unimplemented!();
903         }
904 }
905 impl MsgEncodable for ChannelReestablish {
906         fn encode(&self) -> Vec<u8> {
907                 unimplemented!();
908         }
909 }
910
911 impl MsgDecodable for AnnouncementSignatures {
912         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
913                 if v.len() < 32+8+64*2 {
914                         return Err(DecodeError::WrongLength);
915                 }
916                 let secp_ctx = Secp256k1::without_caps();
917                 Ok(Self {
918                         channel_id: deserialize(&v[0..32]).unwrap(),
919                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
920                         node_signature: secp_signature!(&secp_ctx, &v[40..104]),
921                         bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
922                 })
923         }
924 }
925 impl MsgEncodable for AnnouncementSignatures {
926         fn encode(&self) -> Vec<u8> {
927                 let mut res = Vec::with_capacity(32+8+64*2);
928                 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
929                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
930                 let secp_ctx = Secp256k1::without_caps();
931                 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
932                 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
933                 res
934         }
935 }
936
937 impl MsgDecodable for UnsignedNodeAnnouncement {
938         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
939                 let features = GlobalFeatures::decode(&v[..])?;
940                 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
941                         return Err(DecodeError::WrongLength);
942                 }
943                 let start = features.encoded_len();
944
945                 let mut rgb = [0; 3];
946                 rgb.copy_from_slice(&v[start + 37..start + 40]);
947
948                 let mut alias = [0; 32];
949                 alias.copy_from_slice(&v[start + 40..start + 72]);
950
951                 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
952                 if v.len() < start + 74 + addrlen {
953                         return Err(DecodeError::WrongLength);
954                 }
955
956                 let mut addresses = Vec::with_capacity(4);
957                 let mut read_pos = start + 74;
958                 loop {
959                         if v.len() <= read_pos { break; }
960                         match v[read_pos] {
961                                 0 => { read_pos += 1; },
962                                 1 => {
963                                         if v.len() < read_pos + 1 + 6 {
964                                                 return Err(DecodeError::WrongLength);
965                                         }
966                                         if addresses.len() > 0 {
967                                                 return Err(DecodeError::ExtraAddressesPerType);
968                                         }
969                                         let mut addr = [0; 4];
970                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
971                                         addresses.push(NetAddress::IPv4 {
972                                                 addr,
973                                                 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
974                                         });
975                                         read_pos += 1 + 6;
976                                 },
977                                 2 => {
978                                         if v.len() < read_pos + 1 + 18 {
979                                                 return Err(DecodeError::WrongLength);
980                                         }
981                                         if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
982                                                 return Err(DecodeError::ExtraAddressesPerType);
983                                         }
984                                         let mut addr = [0; 16];
985                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
986                                         addresses.push(NetAddress::IPv6 {
987                                                 addr,
988                                                 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
989                                         });
990                                         read_pos += 1 + 18;
991                                 },
992                                 3 => {
993                                         if v.len() < read_pos + 1 + 12 {
994                                                 return Err(DecodeError::WrongLength);
995                                         }
996                                         if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
997                                                 return Err(DecodeError::ExtraAddressesPerType);
998                                         }
999                                         let mut addr = [0; 10];
1000                                         addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1001                                         addresses.push(NetAddress::OnionV2 {
1002                                                 addr,
1003                                                 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1004                                         });
1005                                         read_pos += 1 + 12;
1006                                 },
1007                                 4 => {
1008                                         if v.len() < read_pos + 1 + 37 {
1009                                                 return Err(DecodeError::WrongLength);
1010                                         }
1011                                         if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1012                                                 return Err(DecodeError::ExtraAddressesPerType);
1013                                         }
1014                                         let mut ed25519_pubkey = [0; 32];
1015                                         ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1016                                         addresses.push(NetAddress::OnionV3 {
1017                                                 ed25519_pubkey,
1018                                                 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1019                                                 version: v[read_pos + 35],
1020                                                 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1021                                         });
1022                                         read_pos += 1 + 37;
1023                                 },
1024                                 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1025                         }
1026                 }
1027
1028                 let secp_ctx = Secp256k1::without_caps();
1029                 Ok(Self {
1030                         features,
1031                         timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1032                         node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1033                         rgb,
1034                         alias,
1035                         addresses,
1036                 })
1037         }
1038 }
1039 impl MsgEncodable for UnsignedNodeAnnouncement {
1040         fn encode(&self) -> Vec<u8> {
1041                 let features = self.features.encode();
1042                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1043                 res.extend_from_slice(&features[..]);
1044                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1045                 res.extend_from_slice(&self.node_id.serialize());
1046                 res.extend_from_slice(&self.rgb);
1047                 res.extend_from_slice(&self.alias);
1048                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1049                 let mut addrs_to_encode = self.addresses.clone();
1050                 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1051                 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1052                 for addr in addrs_to_encode.iter() {
1053                         match addr {
1054                                 &NetAddress::IPv4{addr, port} => {
1055                                         addr_slice.push(1);
1056                                         addr_slice.extend_from_slice(&addr);
1057                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1058                                 },
1059                                 &NetAddress::IPv6{addr, port} => {
1060                                         addr_slice.push(2);
1061                                         addr_slice.extend_from_slice(&addr);
1062                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1063                                 },
1064                                 &NetAddress::OnionV2{addr, port} => {
1065                                         addr_slice.push(3);
1066                                         addr_slice.extend_from_slice(&addr);
1067                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1068                                 },
1069                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1070                                         addr_slice.push(4);
1071                                         addr_slice.extend_from_slice(&ed25519_pubkey);
1072                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1073                                         addr_slice.push(version);
1074                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1075                                 },
1076                         }
1077                 }
1078                 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1079                 res.extend_from_slice(&addr_slice[..]);
1080                 res
1081         }
1082 }
1083
1084 impl MsgDecodable for NodeAnnouncement {
1085         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1086                 if v.len() < 64 {
1087                         return Err(DecodeError::WrongLength);
1088                 }
1089                 let secp_ctx = Secp256k1::without_caps();
1090                 Ok(Self {
1091                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1092                         contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1093                 })
1094         }
1095 }
1096 impl MsgEncodable for NodeAnnouncement {
1097         fn encode(&self) -> Vec<u8> {
1098                 unimplemented!();
1099         }
1100 }
1101
1102 impl MsgDecodable for UnsignedChannelAnnouncement {
1103         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1104                 let features = GlobalFeatures::decode(&v[..])?;
1105                 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1106                         return Err(DecodeError::WrongLength);
1107                 }
1108                 let start = features.encoded_len();
1109                 let secp_ctx = Secp256k1::without_caps();
1110                 Ok(Self {
1111                         features,
1112                         chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1113                         short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1114                         node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1115                         node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1116                         bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1117                         bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1118                 })
1119         }
1120 }
1121 impl MsgEncodable for UnsignedChannelAnnouncement {
1122         fn encode(&self) -> Vec<u8> {
1123                 let features = self.features.encode();
1124                 let mut res = Vec::with_capacity(172 + features.len());
1125                 res.extend_from_slice(&features[..]);
1126                 res.extend_from_slice(&self.chain_hash[..]);
1127                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1128                 res.extend_from_slice(&self.node_id_1.serialize());
1129                 res.extend_from_slice(&self.node_id_2.serialize());
1130                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1131                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1132                 res
1133         }
1134 }
1135
1136 impl MsgDecodable for ChannelAnnouncement {
1137         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1138                 if v.len() < 64*4 {
1139                         return Err(DecodeError::WrongLength);
1140                 }
1141                 let secp_ctx = Secp256k1::without_caps();
1142                 Ok(Self {
1143                         node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1144                         node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1145                         bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1146                         bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1147                         contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1148                 })
1149         }
1150 }
1151 impl MsgEncodable for ChannelAnnouncement {
1152         fn encode(&self) -> Vec<u8> {
1153                 unimplemented!();
1154         }
1155 }
1156
1157 impl MsgDecodable for UnsignedChannelUpdate {
1158         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1159                 if v.len() < 32+8+4+2+2+8+4+4 {
1160                         return Err(DecodeError::WrongLength);
1161                 }
1162                 Ok(Self {
1163                         chain_hash: deserialize(&v[0..32]).unwrap(),
1164                         short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1165                         timestamp: byte_utils::slice_to_be32(&v[40..44]),
1166                         flags: byte_utils::slice_to_be16(&v[44..46]),
1167                         cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1168                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1169                         fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1170                         fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1171                 })
1172         }
1173 }
1174 impl MsgEncodable for UnsignedChannelUpdate {
1175         fn encode(&self) -> Vec<u8> {
1176                 let mut res = Vec::with_capacity(64);
1177                 res.extend_from_slice(&self.chain_hash[..]);
1178                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1179                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1180                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1181                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1182                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1183                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1184                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1185                 res
1186         }
1187 }
1188
1189 impl MsgDecodable for ChannelUpdate {
1190         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1191                 if v.len() < 128 {
1192                         return Err(DecodeError::WrongLength);
1193                 }
1194                 let secp_ctx = Secp256k1::without_caps();
1195                 Ok(Self {
1196                         signature: secp_signature!(&secp_ctx, &v[0..64]),
1197                         contents: UnsignedChannelUpdate::decode(&v[64..])?,
1198                 })
1199         }
1200 }
1201 impl MsgEncodable for ChannelUpdate {
1202         fn encode(&self) -> Vec<u8> {
1203                 let mut res = Vec::with_capacity(128);
1204                 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1205                 res.extend_from_slice(&self.contents.encode()[..]);
1206                 res
1207         }
1208 }
1209
1210 impl MsgDecodable for OnionRealm0HopData {
1211         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1212                 if v.len() < 32 {
1213                         return Err(DecodeError::WrongLength);
1214                 }
1215                 Ok(OnionRealm0HopData {
1216                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1217                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1218                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1219                 })
1220         }
1221 }
1222 impl MsgEncodable for OnionRealm0HopData {
1223         fn encode(&self) -> Vec<u8> {
1224                 let mut res = Vec::with_capacity(32);
1225                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1226                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1227                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1228                 res.resize(32, 0);
1229                 res
1230         }
1231 }
1232
1233 impl MsgDecodable for OnionHopData {
1234         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1235                 if v.len() < 65 {
1236                         return Err(DecodeError::WrongLength);
1237                 }
1238                 let realm = v[0];
1239                 if realm != 0 {
1240                         return Err(DecodeError::UnknownRealmByte);
1241                 }
1242                 let mut hmac = [0; 32];
1243                 hmac[..].copy_from_slice(&v[33..65]);
1244                 Ok(OnionHopData {
1245                         realm: realm,
1246                         data: OnionRealm0HopData::decode(&v[1..33])?,
1247                         hmac: hmac,
1248                 })
1249         }
1250 }
1251 impl MsgEncodable for OnionHopData {
1252         fn encode(&self) -> Vec<u8> {
1253                 let mut res = Vec::with_capacity(65);
1254                 res.push(self.realm);
1255                 res.extend_from_slice(&self.data.encode()[..]);
1256                 res.extend_from_slice(&self.hmac);
1257                 res
1258         }
1259 }
1260
1261 impl MsgDecodable for OnionPacket {
1262         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1263                 if v.len() < 1+33+20*65+32 {
1264                         return Err(DecodeError::WrongLength);
1265                 }
1266                 let mut hop_data = [0; 20*65];
1267                 hop_data.copy_from_slice(&v[34..1334]);
1268                 let mut hmac = [0; 32];
1269                 hmac.copy_from_slice(&v[1334..1366]);
1270                 let secp_ctx = Secp256k1::without_caps();
1271                 Ok(Self {
1272                         version: v[0],
1273                         public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1274                         hop_data,
1275                         hmac,
1276                 })
1277         }
1278 }
1279 impl MsgEncodable for OnionPacket {
1280         fn encode(&self) -> Vec<u8> {
1281                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1282                 res.push(self.version);
1283                 res.extend_from_slice(&self.public_key.serialize());
1284                 res.extend_from_slice(&self.hop_data);
1285                 res.extend_from_slice(&self.hmac);
1286                 res
1287         }
1288 }
1289
1290 impl MsgDecodable for DecodedOnionErrorPacket {
1291         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1292                 unimplemented!();
1293         }
1294 }
1295 impl MsgEncodable for DecodedOnionErrorPacket {
1296         fn encode(&self) -> Vec<u8> {
1297                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1298                 res.extend_from_slice(&self.hmac);
1299                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1300                 res.extend_from_slice(&self.failuremsg);
1301                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1302                 res.extend_from_slice(&self.pad);
1303                 res
1304         }
1305 }
1306
1307 impl MsgDecodable for OnionErrorPacket {
1308         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1309                 if v.len() < 2 {
1310                         return Err(DecodeError::WrongLength);
1311                 }
1312                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1313                 if v.len() < 2 + len {
1314                         return Err(DecodeError::WrongLength);
1315                 }
1316                 Ok(Self {
1317                         data: v[2..len+2].to_vec(),
1318                 })
1319         }
1320 }
1321 impl MsgEncodable for OnionErrorPacket {
1322         fn encode(&self) -> Vec<u8> {
1323                 unimplemented!();
1324         }
1325 }
1326