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