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