3c56aa120ec43fb974c25c80c099411bd1f6c66e
[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;
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 }
17 #[derive(Debug)]
18 pub enum DecodeError {
19         /// Unknown realm byte in an OnionHopData packet
20         UnknownRealmByte,
21         /// Failed to decode a public key (ie it's invalid)
22         BadPublicKey,
23         /// Failed to decode a signature (ie it's invalid)
24         BadSignature,
25         /// Buffer not of right length (either too short or too long)
26         WrongLength,
27 }
28 pub trait MsgDecodable: Sized {
29         fn decode(v: &[u8]) -> Result<Self, DecodeError>;
30 }
31
32 /// Tracks localfeatures which are only in init messages
33 #[derive(Clone, PartialEq)]
34 pub struct LocalFeatures {
35         flags: Vec<u8>,
36 }
37
38 impl LocalFeatures {
39         pub fn new() -> LocalFeatures {
40                 LocalFeatures {
41                         flags: Vec::new(),
42                 }
43         }
44
45         pub fn supports_data_loss_protect(&self) -> bool {
46                 self.flags.len() > 0 && (self.flags[0] & 3) != 0
47         }
48         pub fn requires_data_loss_protect(&self) -> bool {
49                 self.flags.len() > 0 && (self.flags[0] & 1) != 0
50         }
51
52         pub fn supports_initial_routing_sync(&self) -> bool {
53                 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
54         }
55
56         pub fn supports_upfront_shutdown_script(&self) -> bool {
57                 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
58         }
59         pub fn requires_upfront_shutdown_script(&self) -> bool {
60                 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
61         }
62
63         pub fn requires_unknown_bits(&self) -> bool {
64                 for (idx, &byte) in self.flags.iter().enumerate() {
65                         if idx != 0 && (byte & 0x55) != 0 {
66                                 return true;
67                         } else if idx == 0 && (byte & 0x14) != 0 {
68                                 return true;
69                         }
70                 }
71                 return false;
72         }
73
74         pub fn supports_unknown_bits(&self) -> bool {
75                 for (idx, &byte) in self.flags.iter().enumerate() {
76                         if idx != 0 && byte != 0 {
77                                 return true;
78                         } else if idx == 0 && (byte & 0xc4) != 0 {
79                                 return true;
80                         }
81                 }
82                 return false;
83         }
84 }
85
86 /// Tracks globalfeatures which are in init messages and routing announcements
87 #[derive(Clone, PartialEq)]
88 pub struct GlobalFeatures {
89         flags: Vec<u8>,
90 }
91
92 impl GlobalFeatures {
93         pub fn new() -> GlobalFeatures {
94                 GlobalFeatures {
95                         flags: Vec::new(),
96                 }
97         }
98
99         pub fn requires_unknown_bits(&self) -> bool {
100                 for &byte in self.flags.iter() {
101                         if (byte & 0x55) != 0 {
102                                 return true;
103                         }
104                 }
105                 return false;
106         }
107
108         pub fn supports_unknown_bits(&self) -> bool {
109                 for &byte in self.flags.iter() {
110                         if byte != 0 {
111                                 return true;
112                         }
113                 }
114                 return false;
115         }
116 }
117
118 pub struct Init {
119         pub global_features: GlobalFeatures,
120         pub local_features: LocalFeatures,
121 }
122
123 pub struct OpenChannel {
124         pub chain_hash: Sha256dHash,
125         pub temporary_channel_id: Uint256,
126         pub funding_satoshis: u64,
127         pub push_msat: u64,
128         pub dust_limit_satoshis: u64,
129         pub max_htlc_value_in_flight_msat: u64,
130         pub channel_reserve_satoshis: u64,
131         pub htlc_minimum_msat: u64,
132         pub feerate_per_kw: u32,
133         pub to_self_delay: u16,
134         pub max_accepted_htlcs: u16,
135         pub funding_pubkey: PublicKey,
136         pub revocation_basepoint: PublicKey,
137         pub payment_basepoint: PublicKey,
138         pub delayed_payment_basepoint: PublicKey,
139         pub htlc_basepoint: PublicKey,
140         pub first_per_commitment_point: PublicKey,
141         pub channel_flags: u8,
142         pub shutdown_scriptpubkey: Option<Script>,
143 }
144
145 pub struct AcceptChannel {
146         pub temporary_channel_id: Uint256,
147         pub dust_limit_satoshis: u64,
148         pub max_htlc_value_in_flight_msat: u64,
149         pub channel_reserve_satoshis: u64,
150         pub htlc_minimum_msat: u64,
151         pub minimum_depth: u32,
152         pub to_self_delay: u16,
153         pub max_accepted_htlcs: u16,
154         pub funding_pubkey: PublicKey,
155         pub revocation_basepoint: PublicKey,
156         pub payment_basepoint: PublicKey,
157         pub delayed_payment_basepoint: PublicKey,
158         pub htlc_basepoint: PublicKey,
159         pub first_per_commitment_point: PublicKey,
160         pub shutdown_scriptpubkey: Option<Script>,
161 }
162
163 pub struct FundingCreated {
164         pub temporary_channel_id: Uint256,
165         pub funding_txid: Sha256dHash,
166         pub funding_output_index: u16,
167         pub signature: Signature,
168 }
169
170 pub struct FundingSigned {
171         pub channel_id: Uint256,
172         pub signature: Signature,
173 }
174
175 pub struct FundingLocked {
176         pub channel_id: Uint256,
177         pub next_per_commitment_point: PublicKey,
178 }
179
180 pub struct Shutdown {
181         pub channel_id: Uint256,
182         pub scriptpubkey: Script,
183 }
184
185 pub struct ClosingSigned {
186         pub channel_id: Uint256,
187         pub fee_satoshis: u64,
188         pub signature: Signature,
189 }
190
191 #[derive(Clone)]
192 pub struct UpdateAddHTLC {
193         pub channel_id: Uint256,
194         pub htlc_id: u64,
195         pub amount_msat: u64,
196         pub payment_hash: [u8; 32],
197         pub cltv_expiry: u32,
198         pub onion_routing_packet: OnionPacket,
199 }
200
201 #[derive(Clone)]
202 pub struct UpdateFulfillHTLC {
203         pub channel_id: Uint256,
204         pub htlc_id: u64,
205         pub payment_preimage: [u8; 32],
206 }
207
208 pub struct UpdateFailHTLC {
209         pub channel_id: Uint256,
210         pub htlc_id: u64,
211         pub reason: OnionErrorPacket,
212 }
213
214 pub struct UpdateFailMalformedHTLC {
215         pub channel_id: Uint256,
216         pub htlc_id: u64,
217         pub sha256_of_onion: [u8; 32],
218         pub failure_code: u16,
219 }
220
221 #[derive(Clone)]
222 pub struct CommitmentSigned {
223         pub channel_id: Uint256,
224         pub signature: Signature,
225         pub htlc_signatures: Vec<Signature>,
226 }
227
228 pub struct RevokeAndACK {
229         pub channel_id: Uint256,
230         pub per_commitment_secret: [u8; 32],
231         pub next_per_commitment_point: PublicKey,
232 }
233
234 pub struct UpdateFee {
235         pub channel_id: Uint256,
236         pub feerate_per_kw: u32,
237 }
238
239 pub struct ChannelReestablish {
240         pub channel_id: Uint256,
241         pub next_local_commitment_number: u64,
242         pub next_remote_commitment_number: u64,
243         pub your_last_per_commitment_secret: Option<[u8; 32]>,
244         pub my_current_per_commitment_point: PublicKey,
245 }
246
247 #[derive(Clone)]
248 pub struct AnnouncementSignatures {
249         pub channel_id: Uint256,
250         pub short_channel_id: u64,
251         pub node_signature: Signature,
252         pub bitcoin_signature: Signature,
253 }
254
255 #[derive(Clone)]
256 pub enum NetAddress {
257         Dummy,
258         IPv4 {
259                 addr: [u8; 4],
260                 port: u16,
261         },
262         IPv6 {
263                 addr: [u8; 16],
264                 port: u16,
265         },
266         OnionV2 {
267                 addr: [u8; 10],
268                 port: u16,
269         },
270         OnionV3 {
271                 ed25519_pubkey: [u8; 32],
272                 checksum: u16,
273                 version: u8,
274                 //TODO: Do we need a port number here???
275         },
276 }
277
278 pub struct UnsignedNodeAnnouncement {
279         pub features: GlobalFeatures,
280         pub timestamp: u32,
281         pub node_id: PublicKey,
282         pub rgb: [u8; 3],
283         pub alias: [u8; 32],
284         pub addresses: Vec<NetAddress>,
285 }
286 pub struct NodeAnnouncement {
287         pub signature: Signature,
288         pub contents: UnsignedNodeAnnouncement,
289 }
290
291 #[derive(PartialEq, Clone)]
292 pub struct UnsignedChannelAnnouncement {
293         pub features: GlobalFeatures,
294         pub chain_hash: Sha256dHash,
295         pub short_channel_id: u64,
296         pub node_id_1: PublicKey,
297         pub node_id_2: PublicKey,
298         pub bitcoin_key_1: PublicKey,
299         pub bitcoin_key_2: PublicKey,
300 }
301 #[derive(PartialEq, Clone)]
302 pub struct ChannelAnnouncement {
303         pub node_signature_1: Signature,
304         pub node_signature_2: Signature,
305         pub bitcoin_signature_1: Signature,
306         pub bitcoin_signature_2: Signature,
307         pub contents: UnsignedChannelAnnouncement,
308 }
309
310 #[derive(PartialEq, Clone)]
311 pub struct UnsignedChannelUpdate {
312         pub chain_hash: Sha256dHash,
313         pub short_channel_id: u64,
314         pub timestamp: u32,
315         pub flags: u16,
316         pub cltv_expiry_delta: u16,
317         pub htlc_minimum_msat: u64,
318         pub fee_base_msat: u32,
319         pub fee_proportional_millionths: u32,
320 }
321 #[derive(PartialEq, Clone)]
322 pub struct ChannelUpdate {
323         pub signature: Signature,
324         pub contents: UnsignedChannelUpdate,
325 }
326
327 /// Used to put an error message in a HandleError
328 pub enum ErrorMessage {
329         UpdateFailHTLC {
330                 msg: UpdateFailHTLC
331         },
332         DisconnectPeer {},
333 }
334
335 pub struct HandleError { //TODO: rename me
336         pub err: &'static str,
337         pub msg: Option<ErrorMessage>, //TODO: Move into an Action enum and require it!
338 }
339
340 pub trait ChannelMessageHandler : events::EventsProvider {
341         //Channel init:
342         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
343         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
344         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
345         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
346         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
347
348         // Channl close:
349         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
350         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
351
352         // HTLC handling:
353         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
354         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
355         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
356         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
357         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<RevokeAndACK, HandleError>;
358         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
359
360         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
361
362         // Channel-to-announce:
363         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
364 }
365
366 pub trait RoutingMessageHandler {
367         fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
368         /// Handle a channel_announcement message, returning true if it should be forwarded on, false
369         /// or returning an Err otherwise.
370         fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
371         fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
372 }
373
374 pub struct OnionRealm0HopData {
375         pub short_channel_id: u64,
376         pub amt_to_forward: u64,
377         pub outgoing_cltv_value: u32,
378         // 12 bytes of 0-padding
379 }
380
381 pub struct OnionHopData {
382         pub realm: u8,
383         pub data: OnionRealm0HopData,
384         pub hmac: [u8; 32],
385 }
386 unsafe impl internal_traits::NoDealloc for OnionHopData{}
387
388 #[derive(Clone)]
389 pub struct OnionPacket {
390         pub version: u8,
391         pub public_key: PublicKey,
392         pub hop_data: [u8; 20*65],
393         pub hmac: [u8; 32],
394 }
395
396 pub struct DecodedOnionErrorPacket {
397         pub hmac: [u8; 32],
398         pub failuremsg: Vec<u8>,
399         pub pad: Vec<u8>,
400 }
401
402 pub struct OnionErrorPacket {
403         // This really should be a constant size slice, but the spec lets these things be up to 128KB?
404         // (TODO) We limit it in decode to much lower...
405         pub data: Vec<u8>,
406 }
407
408 impl Error for DecodeError {
409         fn description(&self) -> &str {
410                 match *self {
411                         DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
412                         DecodeError::BadPublicKey => "Invalid public key in packet",
413                         DecodeError::BadSignature => "Invalid signature in packet",
414                         DecodeError::WrongLength => "Data was wrong length for packet",
415                 }
416         }
417 }
418 impl fmt::Display for DecodeError {
419         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
420                 f.write_str(self.description())
421         }
422 }
423
424 impl fmt::Debug for HandleError {
425         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
426                 f.write_str(self.err)
427         }
428 }
429
430 macro_rules! secp_pubkey {
431         ( $ctx: expr, $slice: expr ) => {
432                 match PublicKey::from_slice($ctx, $slice) {
433                         Ok(key) => key,
434                         Err(_) => return Err(DecodeError::BadPublicKey)
435                 }
436         };
437 }
438
439 macro_rules! secp_signature {
440         ( $ctx: expr, $slice: expr ) => {
441                 match Signature::from_compact($ctx, $slice) {
442                         Ok(sig) => sig,
443                         Err(_) => return Err(DecodeError::BadSignature)
444                 }
445         };
446 }
447
448 impl MsgDecodable for LocalFeatures {
449         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
450                 if v.len() < 3 { return Err(DecodeError::WrongLength); }
451                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
452                 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
453                 let mut flags = Vec::with_capacity(len);
454                 flags.extend_from_slice(&v[2..]);
455                 Ok(Self {
456                         flags: flags
457                 })
458         }
459 }
460 impl MsgEncodable for LocalFeatures {
461         fn encode(&self) -> Vec<u8> {
462                 let mut res = Vec::with_capacity(self.flags.len() + 2);
463                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
464                 res.extend_from_slice(&self.flags[..]);
465                 res
466         }
467 }
468
469 impl MsgDecodable for GlobalFeatures {
470         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
471                 if v.len() < 3 { return Err(DecodeError::WrongLength); }
472                 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
473                 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
474                 let mut flags = Vec::with_capacity(len);
475                 flags.extend_from_slice(&v[2..]);
476                 Ok(Self {
477                         flags: flags
478                 })
479         }
480 }
481 impl MsgEncodable for GlobalFeatures {
482         fn encode(&self) -> Vec<u8> {
483                 let mut res = Vec::with_capacity(self.flags.len() + 2);
484                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
485                 res.extend_from_slice(&self.flags[..]);
486                 res
487         }
488 }
489
490 impl MsgDecodable for Init {
491         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
492                 let global_features = GlobalFeatures::decode(v)?;
493                 if v.len() < global_features.flags.len() + 4 {
494                         return Err(DecodeError::WrongLength);
495                 }
496                 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
497                 Ok(Self {
498                         global_features: global_features,
499                         local_features: local_features,
500                 })
501         }
502 }
503 impl MsgEncodable for Init {
504         fn encode(&self) -> Vec<u8> {
505                 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
506                 res.extend_from_slice(&self.global_features.encode()[..]);
507                 res.extend_from_slice(&self.local_features.encode()[..]);
508                 res
509         }
510 }
511
512 impl MsgDecodable for OpenChannel {
513         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
514                 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
515                         return Err(DecodeError::WrongLength);
516                 }
517                 let ctx = Secp256k1::without_caps();
518
519                 let mut shutdown_scriptpubkey = None;
520                 if v.len() >= 321 {
521                         let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
522                         if v.len() < 321+len {
523                                 return Err(DecodeError::WrongLength);
524                         }
525                         shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
526                 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
527                         return Err(DecodeError::WrongLength);
528                 }
529
530                 Ok(OpenChannel {
531                         chain_hash: deserialize(&v[0..32]).unwrap(),
532                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
533                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
534                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
535                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
536                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
537                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
538                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
539                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
540                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
541                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
542                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
543                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
544                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
545                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
546                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
547                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
548                         channel_flags: v[318],
549                         shutdown_scriptpubkey: shutdown_scriptpubkey
550                 })
551         }
552 }
553 impl MsgEncodable for OpenChannel {
554         fn encode(&self) -> Vec<u8> {
555                 unimplemented!();
556         }
557 }
558
559 impl MsgDecodable for AcceptChannel {
560         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
561                 if v.len() < 32+4*8+4+2*2+6*33 {
562                         return Err(DecodeError::WrongLength);
563                 }
564                 let ctx = Secp256k1::without_caps();
565
566                 let mut shutdown_scriptpubkey = None;
567                 if v.len() >= 272 {
568                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
569                         if v.len() < 272+len {
570                                 return Err(DecodeError::WrongLength);
571                         }
572                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
573                 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
574                         return Err(DecodeError::WrongLength);
575                 }
576
577                 Ok(Self {
578                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
579                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
580                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
581                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
582                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
583                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
584                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
585                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
586                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
587                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
588                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
589                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
590                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
591                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
592                         shutdown_scriptpubkey: shutdown_scriptpubkey
593                 })
594         }
595 }
596 impl MsgEncodable for AcceptChannel {
597         fn encode(&self) -> Vec<u8> {
598                 unimplemented!();
599         }
600 }
601
602 impl MsgDecodable for FundingCreated {
603         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
604                 if v.len() < 32+32+2+64 {
605                         return Err(DecodeError::WrongLength);
606                 }
607                 let ctx = Secp256k1::without_caps();
608                 Ok(Self {
609                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
610                         funding_txid: deserialize(&v[32..64]).unwrap(),
611                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
612                         signature: secp_signature!(&ctx, &v[66..130]),
613                 })
614         }
615 }
616 impl MsgEncodable for FundingCreated {
617         fn encode(&self) -> Vec<u8> {
618                 unimplemented!();
619         }
620 }
621
622 impl MsgDecodable for FundingSigned {
623         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
624                 if v.len() < 32+64 {
625                         return Err(DecodeError::WrongLength);
626                 }
627                 let ctx = Secp256k1::without_caps();
628                 Ok(Self {
629                         channel_id: deserialize(&v[0..32]).unwrap(),
630                         signature: secp_signature!(&ctx, &v[32..96]),
631                 })
632         }
633 }
634 impl MsgEncodable for FundingSigned {
635         fn encode(&self) -> Vec<u8> {
636                 unimplemented!();
637         }
638 }
639
640 impl MsgDecodable for FundingLocked {
641         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
642                 if v.len() < 32+33 {
643                         return Err(DecodeError::WrongLength);
644                 }
645                 let ctx = Secp256k1::without_caps();
646                 Ok(Self {
647                         channel_id: deserialize(&v[0..32]).unwrap(),
648                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
649                 })
650         }
651 }
652 impl MsgEncodable for FundingLocked {
653         fn encode(&self) -> Vec<u8> {
654                 unimplemented!();
655         }
656 }
657
658 impl MsgDecodable for Shutdown {
659         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
660                 unimplemented!();
661         }
662 }
663 impl MsgEncodable for Shutdown {
664         fn encode(&self) -> Vec<u8> {
665                 unimplemented!();
666         }
667 }
668
669 impl MsgDecodable for ClosingSigned {
670         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
671                 unimplemented!();
672         }
673 }
674 impl MsgEncodable for ClosingSigned {
675         fn encode(&self) -> Vec<u8> {
676                 unimplemented!();
677         }
678 }
679
680 impl MsgDecodable for UpdateAddHTLC {
681         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
682                 unimplemented!();
683         }
684 }
685 impl MsgEncodable for UpdateAddHTLC {
686         fn encode(&self) -> Vec<u8> {
687                 unimplemented!();
688         }
689 }
690
691 impl MsgDecodable for UpdateFulfillHTLC {
692         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
693                 unimplemented!();
694         }
695 }
696 impl MsgEncodable for UpdateFulfillHTLC {
697         fn encode(&self) -> Vec<u8> {
698                 unimplemented!();
699         }
700 }
701
702 impl MsgDecodable for UpdateFailHTLC {
703         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
704                 unimplemented!();
705         }
706 }
707 impl MsgEncodable for UpdateFailHTLC {
708         fn encode(&self) -> Vec<u8> {
709                 unimplemented!();
710         }
711 }
712
713 impl MsgDecodable for UpdateFailMalformedHTLC {
714         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
715                 unimplemented!();
716         }
717 }
718 impl MsgEncodable for UpdateFailMalformedHTLC {
719         fn encode(&self) -> Vec<u8> {
720                 unimplemented!();
721         }
722 }
723
724 impl MsgDecodable for CommitmentSigned {
725         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
726                 unimplemented!();
727         }
728 }
729 impl MsgEncodable for CommitmentSigned {
730         fn encode(&self) -> Vec<u8> {
731                 unimplemented!();
732         }
733 }
734
735 impl MsgDecodable for RevokeAndACK {
736         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
737                 unimplemented!();
738         }
739 }
740 impl MsgEncodable for RevokeAndACK {
741         fn encode(&self) -> Vec<u8> {
742                 unimplemented!();
743         }
744 }
745
746 impl MsgDecodable for UpdateFee {
747         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
748                 unimplemented!();
749         }
750 }
751 impl MsgEncodable for UpdateFee {
752         fn encode(&self) -> Vec<u8> {
753                 unimplemented!();
754         }
755 }
756
757 impl MsgDecodable for ChannelReestablish {
758         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
759                 unimplemented!();
760         }
761 }
762 impl MsgEncodable for ChannelReestablish {
763         fn encode(&self) -> Vec<u8> {
764                 unimplemented!();
765         }
766 }
767
768 impl MsgDecodable for AnnouncementSignatures {
769         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
770                 unimplemented!();
771         }
772 }
773 impl MsgEncodable for AnnouncementSignatures {
774         fn encode(&self) -> Vec<u8> {
775                 unimplemented!();
776         }
777 }
778
779 impl MsgDecodable for UnsignedNodeAnnouncement {
780         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
781                 unimplemented!();
782         }
783 }
784 impl MsgEncodable for UnsignedNodeAnnouncement {
785         fn encode(&self) -> Vec<u8> {
786                 let features = self.features.encode();
787                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
788                 res.extend_from_slice(&features[..]);
789                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
790                 res.extend_from_slice(&self.node_id.serialize());
791                 res.extend_from_slice(&self.rgb);
792                 res.extend_from_slice(&self.alias);
793                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
794                 for addr in self.addresses.iter() {
795                         match addr {
796                                 &NetAddress::Dummy => {},
797                                 &NetAddress::IPv4{addr, port} => {
798                                         addr_slice.extend_from_slice(&addr);
799                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
800                                 },
801                                 &NetAddress::IPv6{addr, port} => {
802                                         addr_slice.extend_from_slice(&addr);
803                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
804                                 },
805                                 &NetAddress::OnionV2{addr, port} => {
806                                         addr_slice.extend_from_slice(&addr);
807                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
808                                 },
809                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version} => {
810                                         addr_slice.extend_from_slice(&ed25519_pubkey);
811                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
812                                         addr_slice.push(version);
813                                 },
814                         }
815                 }
816                 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
817                 res.extend_from_slice(&addr_slice[..]);
818                 res
819         }
820 }
821
822 impl MsgDecodable for NodeAnnouncement {
823         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
824                 unimplemented!();
825         }
826 }
827 impl MsgEncodable for NodeAnnouncement {
828         fn encode(&self) -> Vec<u8> {
829                 unimplemented!();
830         }
831 }
832
833 impl MsgDecodable for UnsignedChannelAnnouncement {
834         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
835                 unimplemented!();
836         }
837 }
838 impl MsgEncodable for UnsignedChannelAnnouncement {
839         fn encode(&self) -> Vec<u8> {
840                 let features = self.features.encode();
841                 let mut res = Vec::with_capacity(172 + features.len());
842                 res.extend_from_slice(&features[..]);
843                 res.extend_from_slice(&self.chain_hash[..]);
844                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
845                 res.extend_from_slice(&self.node_id_1.serialize());
846                 res.extend_from_slice(&self.node_id_2.serialize());
847                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
848                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
849                 res
850         }
851 }
852
853 impl MsgDecodable for ChannelAnnouncement {
854         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
855                 unimplemented!();
856         }
857 }
858 impl MsgEncodable for ChannelAnnouncement {
859         fn encode(&self) -> Vec<u8> {
860                 unimplemented!();
861         }
862 }
863
864 impl MsgDecodable for UnsignedChannelUpdate {
865         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
866                 unimplemented!();
867         }
868 }
869 impl MsgEncodable for UnsignedChannelUpdate {
870         fn encode(&self) -> Vec<u8> {
871                 let mut res = Vec::with_capacity(64);
872                 res.extend_from_slice(&self.chain_hash[..]);
873                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
874                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
875                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
876                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
877                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
878                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
879                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
880                 res
881         }
882 }
883
884 impl MsgDecodable for ChannelUpdate {
885         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
886                 unimplemented!();
887         }
888 }
889 impl MsgEncodable for ChannelUpdate {
890         fn encode(&self) -> Vec<u8> {
891                 let mut res = Vec::with_capacity(128);
892                 //TODO: Should avoid creating a new secp ctx just for a serialize call :(
893                 res.extend_from_slice(&self.signature.serialize_der(&Secp256k1::new())[..]); //TODO: Need in non-der form! (probably elsewhere too)
894                 res.extend_from_slice(&self.contents.encode()[..]);
895                 res
896         }
897 }
898
899 impl MsgDecodable for OnionRealm0HopData {
900         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
901                 if v.len() < 32 {
902                         return Err(DecodeError::WrongLength);
903                 }
904                 Ok(OnionRealm0HopData {
905                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
906                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
907                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
908                 })
909         }
910 }
911 impl MsgEncodable for OnionRealm0HopData {
912         fn encode(&self) -> Vec<u8> {
913                 let mut res = Vec::with_capacity(32);
914                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
915                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
916                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
917                 res.resize(32, 0);
918                 res
919         }
920 }
921
922 impl MsgDecodable for OnionHopData {
923         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
924                 if v.len() < 65 {
925                         return Err(DecodeError::WrongLength);
926                 }
927                 let realm = v[0];
928                 if realm != 0 {
929                         return Err(DecodeError::UnknownRealmByte);
930                 }
931                 let mut hmac = [0; 32];
932                 hmac[..].copy_from_slice(&v[33..65]);
933                 Ok(OnionHopData {
934                         realm: realm,
935                         data: OnionRealm0HopData::decode(&v[1..33])?,
936                         hmac: hmac,
937                 })
938         }
939 }
940 impl MsgEncodable for OnionHopData {
941         fn encode(&self) -> Vec<u8> {
942                 let mut res = Vec::with_capacity(65);
943                 res.push(self.realm);
944                 res.extend_from_slice(&self.data.encode()[..]);
945                 res.extend_from_slice(&self.hmac);
946                 res
947         }
948 }
949
950 impl MsgDecodable for OnionPacket {
951         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
952                 unimplemented!();
953         }
954 }
955 impl MsgEncodable for OnionPacket {
956         fn encode(&self) -> Vec<u8> {
957                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
958                 res.push(self.version);
959                 res.extend_from_slice(&self.public_key.serialize());
960                 res.extend_from_slice(&self.hop_data);
961                 res.extend_from_slice(&self.hmac);
962                 res
963         }
964 }
965
966 impl MsgDecodable for DecodedOnionErrorPacket {
967         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
968                 unimplemented!();
969         }
970 }
971 impl MsgEncodable for DecodedOnionErrorPacket {
972         fn encode(&self) -> Vec<u8> {
973                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
974                 res.extend_from_slice(&self.hmac);
975                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
976                 res.extend_from_slice(&self.failuremsg);
977                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
978                 res.extend_from_slice(&self.pad);
979                 res
980         }
981 }
982
983 impl MsgDecodable for OnionErrorPacket {
984         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
985                 unimplemented!();
986         }
987 }
988 impl MsgEncodable for OnionErrorPacket {
989         fn encode(&self) -> Vec<u8> {
990                 unimplemented!();
991         }
992 }
993