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