Impl a few more msg deserializations, fix a channel panic!() bug
[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 global_features.flags.len() + 4 <= v.len() {
494                         return Err(DecodeError::WrongLength);
495                 }
496                 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
497                 if global_features.flags.len() + local_features.flags.len() + 4 != v.len() {
498                         return Err(DecodeError::WrongLength);
499                 }
500                 Ok(Self {
501                         global_features: global_features,
502                         local_features: local_features,
503                 })
504         }
505 }
506 impl MsgEncodable for Init {
507         fn encode(&self) -> Vec<u8> {
508                 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
509                 res.extend_from_slice(&self.global_features.encode()[..]);
510                 res.extend_from_slice(&self.local_features.encode()[..]);
511                 res
512         }
513 }
514
515 impl MsgDecodable for OpenChannel {
516         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
517                 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
518                         return Err(DecodeError::WrongLength);
519                 }
520                 let ctx = Secp256k1::without_caps();
521
522                 let mut shutdown_scriptpubkey = None;
523                 if v.len() >= 321 {
524                         let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
525                         if v.len() != 321+len {
526                                 return Err(DecodeError::WrongLength);
527                         }
528                         shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
529                 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 {
530                         return Err(DecodeError::WrongLength);
531                 }
532
533                 Ok(OpenChannel {
534                         chain_hash: deserialize(&v[0..32]).unwrap(),
535                         temporary_channel_id: deserialize(&v[32..64]).unwrap(),
536                         funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
537                         push_msat: byte_utils::slice_to_be64(&v[72..80]),
538                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
539                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
540                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
541                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
542                         feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
543                         to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
544                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
545                         funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
546                         revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
547                         payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
548                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
549                         htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
550                         first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
551                         channel_flags: v[318],
552                         shutdown_scriptpubkey: shutdown_scriptpubkey
553                 })
554         }
555 }
556 impl MsgEncodable for OpenChannel {
557         fn encode(&self) -> Vec<u8> {
558                 unimplemented!();
559         }
560 }
561
562 impl MsgDecodable for AcceptChannel {
563         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
564                 if v.len() < 32+4*8+4+2*2+6*33 {
565                         return Err(DecodeError::WrongLength);
566                 }
567                 let ctx = Secp256k1::without_caps();
568
569                 let mut shutdown_scriptpubkey = None;
570                 if v.len() >= 272 {
571                         let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
572                         if v.len() != 272+len {
573                                 return Err(DecodeError::WrongLength);
574                         }
575                         shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
576                 } else if v.len() != 32+4*8+4+2*2+6*33 {
577                         return Err(DecodeError::WrongLength);
578                 }
579
580                 Ok(Self {
581                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
582                         dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
583                         max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
584                         channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
585                         htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
586                         minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
587                         to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
588                         max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
589                         funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
590                         revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
591                         payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
592                         delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
593                         htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
594                         first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
595                         shutdown_scriptpubkey: shutdown_scriptpubkey
596                 })
597         }
598 }
599 impl MsgEncodable for AcceptChannel {
600         fn encode(&self) -> Vec<u8> {
601                 unimplemented!();
602         }
603 }
604
605 impl MsgDecodable for FundingCreated {
606         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
607                 if v.len() != 32+32+2+64 {
608                         return Err(DecodeError::WrongLength);
609                 }
610                 let ctx = Secp256k1::without_caps();
611                 Ok(Self {
612                         temporary_channel_id: deserialize(&v[0..32]).unwrap(),
613                         funding_txid: deserialize(&v[32..64]).unwrap(),
614                         funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
615                         signature: secp_signature!(&ctx, &v[66..130]),
616                 })
617         }
618 }
619 impl MsgEncodable for FundingCreated {
620         fn encode(&self) -> Vec<u8> {
621                 unimplemented!();
622         }
623 }
624
625 impl MsgDecodable for FundingSigned {
626         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
627                 if v.len() != 32+64 {
628                         return Err(DecodeError::WrongLength);
629                 }
630                 let ctx = Secp256k1::without_caps();
631                 Ok(Self {
632                         channel_id: deserialize(&v[0..32]).unwrap(),
633                         signature: secp_signature!(&ctx, &v[32..96]),
634                 })
635         }
636 }
637 impl MsgEncodable for FundingSigned {
638         fn encode(&self) -> Vec<u8> {
639                 unimplemented!();
640         }
641 }
642
643 impl MsgDecodable for FundingLocked {
644         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
645                 if v.len() != 32+33 {
646                         return Err(DecodeError::WrongLength);
647                 }
648                 let ctx = Secp256k1::without_caps();
649                 Ok(Self {
650                         channel_id: deserialize(&v[0..32]).unwrap(),
651                         next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
652                 })
653         }
654 }
655 impl MsgEncodable for FundingLocked {
656         fn encode(&self) -> Vec<u8> {
657                 unimplemented!();
658         }
659 }
660
661 impl MsgDecodable for Shutdown {
662         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
663                 unimplemented!();
664         }
665 }
666 impl MsgEncodable for Shutdown {
667         fn encode(&self) -> Vec<u8> {
668                 unimplemented!();
669         }
670 }
671
672 impl MsgDecodable for ClosingSigned {
673         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
674                 unimplemented!();
675         }
676 }
677 impl MsgEncodable for ClosingSigned {
678         fn encode(&self) -> Vec<u8> {
679                 unimplemented!();
680         }
681 }
682
683 impl MsgDecodable for UpdateAddHTLC {
684         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
685                 unimplemented!();
686         }
687 }
688 impl MsgEncodable for UpdateAddHTLC {
689         fn encode(&self) -> Vec<u8> {
690                 unimplemented!();
691         }
692 }
693
694 impl MsgDecodable for UpdateFulfillHTLC {
695         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
696                 unimplemented!();
697         }
698 }
699 impl MsgEncodable for UpdateFulfillHTLC {
700         fn encode(&self) -> Vec<u8> {
701                 unimplemented!();
702         }
703 }
704
705 impl MsgDecodable for UpdateFailHTLC {
706         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
707                 unimplemented!();
708         }
709 }
710 impl MsgEncodable for UpdateFailHTLC {
711         fn encode(&self) -> Vec<u8> {
712                 unimplemented!();
713         }
714 }
715
716 impl MsgDecodable for UpdateFailMalformedHTLC {
717         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
718                 unimplemented!();
719         }
720 }
721 impl MsgEncodable for UpdateFailMalformedHTLC {
722         fn encode(&self) -> Vec<u8> {
723                 unimplemented!();
724         }
725 }
726
727 impl MsgDecodable for CommitmentSigned {
728         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
729                 unimplemented!();
730         }
731 }
732 impl MsgEncodable for CommitmentSigned {
733         fn encode(&self) -> Vec<u8> {
734                 unimplemented!();
735         }
736 }
737
738 impl MsgDecodable for RevokeAndACK {
739         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
740                 unimplemented!();
741         }
742 }
743 impl MsgEncodable for RevokeAndACK {
744         fn encode(&self) -> Vec<u8> {
745                 unimplemented!();
746         }
747 }
748
749 impl MsgDecodable for UpdateFee {
750         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
751                 unimplemented!();
752         }
753 }
754 impl MsgEncodable for UpdateFee {
755         fn encode(&self) -> Vec<u8> {
756                 unimplemented!();
757         }
758 }
759
760 impl MsgDecodable for ChannelReestablish {
761         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
762                 unimplemented!();
763         }
764 }
765 impl MsgEncodable for ChannelReestablish {
766         fn encode(&self) -> Vec<u8> {
767                 unimplemented!();
768         }
769 }
770
771 impl MsgDecodable for AnnouncementSignatures {
772         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
773                 unimplemented!();
774         }
775 }
776 impl MsgEncodable for AnnouncementSignatures {
777         fn encode(&self) -> Vec<u8> {
778                 unimplemented!();
779         }
780 }
781
782 impl MsgDecodable for UnsignedNodeAnnouncement {
783         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
784                 unimplemented!();
785         }
786 }
787 impl MsgEncodable for UnsignedNodeAnnouncement {
788         fn encode(&self) -> Vec<u8> {
789                 let features = self.features.encode();
790                 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
791                 res.extend_from_slice(&features[..]);
792                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
793                 res.extend_from_slice(&self.node_id.serialize());
794                 res.extend_from_slice(&self.rgb);
795                 res.extend_from_slice(&self.alias);
796                 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
797                 for addr in self.addresses.iter() {
798                         match addr {
799                                 &NetAddress::Dummy => {},
800                                 &NetAddress::IPv4{addr, port} => {
801                                         addr_slice.extend_from_slice(&addr);
802                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
803                                 },
804                                 &NetAddress::IPv6{addr, port} => {
805                                         addr_slice.extend_from_slice(&addr);
806                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
807                                 },
808                                 &NetAddress::OnionV2{addr, port} => {
809                                         addr_slice.extend_from_slice(&addr);
810                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
811                                 },
812                                 &NetAddress::OnionV3{ed25519_pubkey, checksum, version} => {
813                                         addr_slice.extend_from_slice(&ed25519_pubkey);
814                                         addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
815                                         addr_slice.push(version);
816                                 },
817                         }
818                 }
819                 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
820                 res.extend_from_slice(&addr_slice[..]);
821                 res
822         }
823 }
824
825 impl MsgDecodable for NodeAnnouncement {
826         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
827                 unimplemented!();
828         }
829 }
830 impl MsgEncodable for NodeAnnouncement {
831         fn encode(&self) -> Vec<u8> {
832                 unimplemented!();
833         }
834 }
835
836 impl MsgDecodable for UnsignedChannelAnnouncement {
837         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
838                 unimplemented!();
839         }
840 }
841 impl MsgEncodable for UnsignedChannelAnnouncement {
842         fn encode(&self) -> Vec<u8> {
843                 let features = self.features.encode();
844                 let mut res = Vec::with_capacity(172 + features.len());
845                 res.extend_from_slice(&features[..]);
846                 res.extend_from_slice(&self.chain_hash[..]);
847                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
848                 res.extend_from_slice(&self.node_id_1.serialize());
849                 res.extend_from_slice(&self.node_id_2.serialize());
850                 res.extend_from_slice(&self.bitcoin_key_1.serialize());
851                 res.extend_from_slice(&self.bitcoin_key_2.serialize());
852                 res
853         }
854 }
855
856 impl MsgDecodable for ChannelAnnouncement {
857         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
858                 unimplemented!();
859         }
860 }
861 impl MsgEncodable for ChannelAnnouncement {
862         fn encode(&self) -> Vec<u8> {
863                 unimplemented!();
864         }
865 }
866
867 impl MsgDecodable for UnsignedChannelUpdate {
868         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
869                 unimplemented!();
870         }
871 }
872 impl MsgEncodable for UnsignedChannelUpdate {
873         fn encode(&self) -> Vec<u8> {
874                 let mut res = Vec::with_capacity(64);
875                 res.extend_from_slice(&self.chain_hash[..]);
876                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
877                 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
878                 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
879                 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
880                 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
881                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
882                 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
883                 res
884         }
885 }
886
887 impl MsgDecodable for ChannelUpdate {
888         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
889                 unimplemented!();
890         }
891 }
892 impl MsgEncodable for ChannelUpdate {
893         fn encode(&self) -> Vec<u8> {
894                 let mut res = Vec::with_capacity(128);
895                 //TODO: Should avoid creating a new secp ctx just for a serialize call :(
896                 res.extend_from_slice(&self.signature.serialize_der(&Secp256k1::new())[..]); //TODO: Need in non-der form! (probably elsewhere too)
897                 res.extend_from_slice(&self.contents.encode()[..]);
898                 res
899         }
900 }
901
902 impl MsgDecodable for OnionRealm0HopData {
903         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
904                 if v.len() != 32 {
905                         return Err(DecodeError::WrongLength);
906                 }
907                 Ok(OnionRealm0HopData {
908                         short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
909                         amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
910                         outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
911                 })
912         }
913 }
914 impl MsgEncodable for OnionRealm0HopData {
915         fn encode(&self) -> Vec<u8> {
916                 let mut res = Vec::with_capacity(32);
917                 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
918                 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
919                 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
920                 res.resize(32, 0);
921                 res
922         }
923 }
924
925 impl MsgDecodable for OnionHopData {
926         fn decode(v: &[u8]) -> Result<Self, DecodeError> {
927                 if v.len() != 65 {
928                         return Err(DecodeError::WrongLength);
929                 }
930                 let realm = v[0];
931                 if realm != 0 {
932                         return Err(DecodeError::UnknownRealmByte);
933                 }
934                 let mut hmac = [0; 32];
935                 hmac[..].copy_from_slice(&v[33..65]);
936                 Ok(OnionHopData {
937                         realm: realm,
938                         data: OnionRealm0HopData::decode(&v[1..33])?,
939                         hmac: hmac,
940                 })
941         }
942 }
943 impl MsgEncodable for OnionHopData {
944         fn encode(&self) -> Vec<u8> {
945                 let mut res = Vec::with_capacity(65);
946                 res.push(self.realm);
947                 res.extend_from_slice(&self.data.encode()[..]);
948                 res.extend_from_slice(&self.hmac);
949                 res
950         }
951 }
952
953 impl MsgDecodable for OnionPacket {
954         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
955                 unimplemented!();
956         }
957 }
958 impl MsgEncodable for OnionPacket {
959         fn encode(&self) -> Vec<u8> {
960                 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
961                 res.push(self.version);
962                 res.extend_from_slice(&self.public_key.serialize());
963                 res.extend_from_slice(&self.hop_data);
964                 res.extend_from_slice(&self.hmac);
965                 res
966         }
967 }
968
969 impl MsgDecodable for DecodedOnionErrorPacket {
970         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
971                 unimplemented!();
972         }
973 }
974 impl MsgEncodable for DecodedOnionErrorPacket {
975         fn encode(&self) -> Vec<u8> {
976                 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
977                 res.extend_from_slice(&self.hmac);
978                 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
979                 res.extend_from_slice(&self.failuremsg);
980                 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
981                 res.extend_from_slice(&self.pad);
982                 res
983         }
984 }
985
986 impl MsgDecodable for OnionErrorPacket {
987         fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
988                 unimplemented!();
989         }
990 }
991 impl MsgEncodable for OnionErrorPacket {
992         fn encode(&self) -> Vec<u8> {
993                 unimplemented!();
994         }
995 }
996