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;
10 use std::result::Result;
12 use util::{byte_utils, internal_traits, events};
14 pub trait MsgEncodable {
15 fn encode(&self) -> Vec<u8>;
18 pub enum DecodeError {
19 /// Unknown realm byte in an OnionHopData packet
21 /// Failed to decode a public key (ie it's invalid)
23 /// Failed to decode a signature (ie it's invalid)
25 /// Buffer not of right length (either too short or too long)
28 pub trait MsgDecodable: Sized {
29 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
32 /// Tracks localfeatures which are only in init messages
33 #[derive(Clone, PartialEq)]
34 pub struct LocalFeatures {
39 pub fn new() -> LocalFeatures {
45 pub fn supports_data_loss_protect(&self) -> bool {
46 self.flags.len() > 0 && (self.flags[0] & 3) != 0
48 pub fn requires_data_loss_protect(&self) -> bool {
49 self.flags.len() > 0 && (self.flags[0] & 1) != 0
52 pub fn supports_initial_routing_sync(&self) -> bool {
53 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
56 pub fn supports_upfront_shutdown_script(&self) -> bool {
57 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
59 pub fn requires_upfront_shutdown_script(&self) -> bool {
60 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
63 pub fn requires_unknown_bits(&self) -> bool {
64 for (idx, &byte) in self.flags.iter().enumerate() {
65 if idx != 0 && (byte & 0x55) != 0 {
67 } else if idx == 0 && (byte & 0x14) != 0 {
74 pub fn supports_unknown_bits(&self) -> bool {
75 for (idx, &byte) in self.flags.iter().enumerate() {
76 if idx != 0 && byte != 0 {
78 } else if idx == 0 && (byte & 0xc4) != 0 {
86 /// Tracks globalfeatures which are in init messages and routing announcements
87 #[derive(Clone, PartialEq)]
88 pub struct GlobalFeatures {
93 pub fn new() -> GlobalFeatures {
99 pub fn requires_unknown_bits(&self) -> bool {
100 for &byte in self.flags.iter() {
101 if (byte & 0x55) != 0 {
108 pub fn supports_unknown_bits(&self) -> bool {
109 for &byte in self.flags.iter() {
119 pub global_features: GlobalFeatures,
120 pub local_features: LocalFeatures,
123 pub struct OpenChannel {
124 pub chain_hash: Sha256dHash,
125 pub temporary_channel_id: Uint256,
126 pub funding_satoshis: 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>,
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>,
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,
170 pub struct FundingSigned {
171 pub channel_id: Uint256,
172 pub signature: Signature,
175 pub struct FundingLocked {
176 pub channel_id: Uint256,
177 pub next_per_commitment_point: PublicKey,
180 pub struct Shutdown {
181 pub channel_id: Uint256,
182 pub scriptpubkey: Script,
185 pub struct ClosingSigned {
186 pub channel_id: Uint256,
187 pub fee_satoshis: u64,
188 pub signature: Signature,
192 pub struct UpdateAddHTLC {
193 pub channel_id: Uint256,
195 pub amount_msat: u64,
196 pub payment_hash: [u8; 32],
197 pub cltv_expiry: u32,
198 pub onion_routing_packet: OnionPacket,
202 pub struct UpdateFulfillHTLC {
203 pub channel_id: Uint256,
205 pub payment_preimage: [u8; 32],
208 pub struct UpdateFailHTLC {
209 pub channel_id: Uint256,
211 pub reason: OnionErrorPacket,
214 pub struct UpdateFailMalformedHTLC {
215 pub channel_id: Uint256,
217 pub sha256_of_onion: [u8; 32],
218 pub failure_code: u16,
222 pub struct CommitmentSigned {
223 pub channel_id: Uint256,
224 pub signature: Signature,
225 pub htlc_signatures: Vec<Signature>,
228 pub struct RevokeAndACK {
229 pub channel_id: Uint256,
230 pub per_commitment_secret: [u8; 32],
231 pub next_per_commitment_point: PublicKey,
234 pub struct UpdateFee {
235 pub channel_id: Uint256,
236 pub feerate_per_kw: u32,
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,
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,
256 pub enum NetAddress {
271 ed25519_pubkey: [u8; 32],
274 //TODO: Do we need a port number here???
278 pub struct UnsignedNodeAnnouncement {
279 pub features: GlobalFeatures,
281 pub node_id: PublicKey,
284 pub addresses: Vec<NetAddress>,
286 pub struct NodeAnnouncement {
287 pub signature: Signature,
288 pub contents: UnsignedNodeAnnouncement,
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,
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,
310 #[derive(PartialEq, Clone)]
311 pub struct UnsignedChannelUpdate {
312 pub chain_hash: Sha256dHash,
313 pub short_channel_id: u64,
316 pub cltv_expiry_delta: u16,
317 pub htlc_minimum_msat: u64,
318 pub fee_base_msat: u32,
319 pub fee_proportional_millionths: u32,
321 #[derive(PartialEq, Clone)]
322 pub struct ChannelUpdate {
323 pub signature: Signature,
324 pub contents: UnsignedChannelUpdate,
327 /// Used to put an error message in a HandleError
328 pub enum ErrorMessage {
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!
340 pub trait ChannelMessageHandler : events::EventsProvider {
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>;
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>;
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>;
360 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
362 // Channel-to-announce:
363 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
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>;
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
381 pub struct OnionHopData {
383 pub data: OnionRealm0HopData,
386 unsafe impl internal_traits::NoDealloc for OnionHopData{}
389 pub struct OnionPacket {
391 pub public_key: PublicKey,
392 pub hop_data: [u8; 20*65],
396 pub struct DecodedOnionErrorPacket {
398 pub failuremsg: Vec<u8>,
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...
408 impl Error for DecodeError {
409 fn description(&self) -> &str {
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",
418 impl fmt::Display for DecodeError {
419 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
420 f.write_str(self.description())
424 impl fmt::Debug for HandleError {
425 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
426 f.write_str(self.err)
430 macro_rules! secp_pubkey {
431 ( $ctx: expr, $slice: expr ) => {
432 match PublicKey::from_slice($ctx, $slice) {
434 Err(_) => return Err(DecodeError::BadPublicKey)
439 macro_rules! secp_signature {
440 ( $ctx: expr, $slice: expr ) => {
441 match Signature::from_compact($ctx, $slice) {
443 Err(_) => return Err(DecodeError::BadSignature)
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..]);
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[..]);
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..]);
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[..]);
490 impl MsgDecodable for Init {
491 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
492 let global_features = GlobalFeatures::decode(v)?;
493 if v.len() < global_features.flags.len() + 4 {
494 return Err(DecodeError::WrongLength);
496 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
498 global_features: global_features,
499 local_features: local_features,
503 impl MsgEncodable for Init {
504 fn encode(&self) -> Vec<u8> {
505 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
506 res.extend_from_slice(&self.global_features.encode()[..]);
507 res.extend_from_slice(&self.local_features.encode()[..]);
512 impl MsgDecodable for OpenChannel {
513 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
514 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
515 return Err(DecodeError::WrongLength);
517 let ctx = Secp256k1::without_caps();
519 let mut shutdown_scriptpubkey = None;
521 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
522 if v.len() < 321+len {
523 return Err(DecodeError::WrongLength);
525 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
526 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
527 return Err(DecodeError::WrongLength);
531 chain_hash: deserialize(&v[0..32]).unwrap(),
532 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
533 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
534 push_msat: byte_utils::slice_to_be64(&v[72..80]),
535 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
536 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
537 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
538 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
539 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
540 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
541 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
542 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
543 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
544 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
545 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
546 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
547 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
548 channel_flags: v[318],
549 shutdown_scriptpubkey: shutdown_scriptpubkey
553 impl MsgEncodable for OpenChannel {
554 fn encode(&self) -> Vec<u8> {
559 impl MsgDecodable for AcceptChannel {
560 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
561 if v.len() < 32+4*8+4+2*2+6*33 {
562 return Err(DecodeError::WrongLength);
564 let ctx = Secp256k1::without_caps();
566 let mut shutdown_scriptpubkey = None;
568 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
569 if v.len() < 272+len {
570 return Err(DecodeError::WrongLength);
572 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
573 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
574 return Err(DecodeError::WrongLength);
578 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
579 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
580 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
581 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
582 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
583 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
584 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
585 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
586 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
587 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
588 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
589 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
590 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
591 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
592 shutdown_scriptpubkey: shutdown_scriptpubkey
596 impl MsgEncodable for AcceptChannel {
597 fn encode(&self) -> Vec<u8> {
602 impl MsgDecodable for FundingCreated {
603 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
604 if v.len() < 32+32+2+64 {
605 return Err(DecodeError::WrongLength);
607 let ctx = Secp256k1::without_caps();
609 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
610 funding_txid: deserialize(&v[32..64]).unwrap(),
611 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
612 signature: secp_signature!(&ctx, &v[66..130]),
616 impl MsgEncodable for FundingCreated {
617 fn encode(&self) -> Vec<u8> {
622 impl MsgDecodable for FundingSigned {
623 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
625 return Err(DecodeError::WrongLength);
627 let ctx = Secp256k1::without_caps();
629 channel_id: deserialize(&v[0..32]).unwrap(),
630 signature: secp_signature!(&ctx, &v[32..96]),
634 impl MsgEncodable for FundingSigned {
635 fn encode(&self) -> Vec<u8> {
640 impl MsgDecodable for FundingLocked {
641 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
643 return Err(DecodeError::WrongLength);
645 let ctx = Secp256k1::without_caps();
647 channel_id: deserialize(&v[0..32]).unwrap(),
648 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
652 impl MsgEncodable for FundingLocked {
653 fn encode(&self) -> Vec<u8> {
658 impl MsgDecodable for Shutdown {
659 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
663 impl MsgEncodable for Shutdown {
664 fn encode(&self) -> Vec<u8> {
669 impl MsgDecodable for ClosingSigned {
670 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
674 impl MsgEncodable for ClosingSigned {
675 fn encode(&self) -> Vec<u8> {
680 impl MsgDecodable for UpdateAddHTLC {
681 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
685 impl MsgEncodable for UpdateAddHTLC {
686 fn encode(&self) -> Vec<u8> {
691 impl MsgDecodable for UpdateFulfillHTLC {
692 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
696 impl MsgEncodable for UpdateFulfillHTLC {
697 fn encode(&self) -> Vec<u8> {
702 impl MsgDecodable for UpdateFailHTLC {
703 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
707 impl MsgEncodable for UpdateFailHTLC {
708 fn encode(&self) -> Vec<u8> {
713 impl MsgDecodable for UpdateFailMalformedHTLC {
714 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
718 impl MsgEncodable for UpdateFailMalformedHTLC {
719 fn encode(&self) -> Vec<u8> {
724 impl MsgDecodable for CommitmentSigned {
725 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
729 impl MsgEncodable for CommitmentSigned {
730 fn encode(&self) -> Vec<u8> {
735 impl MsgDecodable for RevokeAndACK {
736 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
740 impl MsgEncodable for RevokeAndACK {
741 fn encode(&self) -> Vec<u8> {
746 impl MsgDecodable for UpdateFee {
747 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
751 impl MsgEncodable for UpdateFee {
752 fn encode(&self) -> Vec<u8> {
757 impl MsgDecodable for ChannelReestablish {
758 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
762 impl MsgEncodable for ChannelReestablish {
763 fn encode(&self) -> Vec<u8> {
768 impl MsgDecodable for AnnouncementSignatures {
769 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
773 impl MsgEncodable for AnnouncementSignatures {
774 fn encode(&self) -> Vec<u8> {
779 impl MsgDecodable for UnsignedNodeAnnouncement {
780 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
784 impl MsgEncodable for UnsignedNodeAnnouncement {
785 fn encode(&self) -> Vec<u8> {
786 let features = self.features.encode();
787 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
788 res.extend_from_slice(&features[..]);
789 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
790 res.extend_from_slice(&self.node_id.serialize());
791 res.extend_from_slice(&self.rgb);
792 res.extend_from_slice(&self.alias);
793 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
794 for addr in self.addresses.iter() {
796 &NetAddress::Dummy => {},
797 &NetAddress::IPv4{addr, port} => {
798 addr_slice.extend_from_slice(&addr);
799 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
801 &NetAddress::IPv6{addr, port} => {
802 addr_slice.extend_from_slice(&addr);
803 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
805 &NetAddress::OnionV2{addr, port} => {
806 addr_slice.extend_from_slice(&addr);
807 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
809 &NetAddress::OnionV3{ed25519_pubkey, checksum, version} => {
810 addr_slice.extend_from_slice(&ed25519_pubkey);
811 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
812 addr_slice.push(version);
816 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
817 res.extend_from_slice(&addr_slice[..]);
822 impl MsgDecodable for NodeAnnouncement {
823 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
827 impl MsgEncodable for NodeAnnouncement {
828 fn encode(&self) -> Vec<u8> {
833 impl MsgDecodable for UnsignedChannelAnnouncement {
834 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
838 impl MsgEncodable for UnsignedChannelAnnouncement {
839 fn encode(&self) -> Vec<u8> {
840 let features = self.features.encode();
841 let mut res = Vec::with_capacity(172 + features.len());
842 res.extend_from_slice(&features[..]);
843 res.extend_from_slice(&self.chain_hash[..]);
844 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
845 res.extend_from_slice(&self.node_id_1.serialize());
846 res.extend_from_slice(&self.node_id_2.serialize());
847 res.extend_from_slice(&self.bitcoin_key_1.serialize());
848 res.extend_from_slice(&self.bitcoin_key_2.serialize());
853 impl MsgDecodable for ChannelAnnouncement {
854 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
858 impl MsgEncodable for ChannelAnnouncement {
859 fn encode(&self) -> Vec<u8> {
864 impl MsgDecodable for UnsignedChannelUpdate {
865 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
869 impl MsgEncodable for UnsignedChannelUpdate {
870 fn encode(&self) -> Vec<u8> {
871 let mut res = Vec::with_capacity(64);
872 res.extend_from_slice(&self.chain_hash[..]);
873 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
874 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
875 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
876 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
877 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
878 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
879 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
884 impl MsgDecodable for ChannelUpdate {
885 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
889 impl MsgEncodable for ChannelUpdate {
890 fn encode(&self) -> Vec<u8> {
891 let mut res = Vec::with_capacity(128);
892 //TODO: Should avoid creating a new secp ctx just for a serialize call :(
893 res.extend_from_slice(&self.signature.serialize_der(&Secp256k1::new())[..]); //TODO: Need in non-der form! (probably elsewhere too)
894 res.extend_from_slice(&self.contents.encode()[..]);
899 impl MsgDecodable for OnionRealm0HopData {
900 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
902 return Err(DecodeError::WrongLength);
904 Ok(OnionRealm0HopData {
905 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
906 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
907 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
911 impl MsgEncodable for OnionRealm0HopData {
912 fn encode(&self) -> Vec<u8> {
913 let mut res = Vec::with_capacity(32);
914 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
915 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
916 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
922 impl MsgDecodable for OnionHopData {
923 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
925 return Err(DecodeError::WrongLength);
929 return Err(DecodeError::UnknownRealmByte);
931 let mut hmac = [0; 32];
932 hmac[..].copy_from_slice(&v[33..65]);
935 data: OnionRealm0HopData::decode(&v[1..33])?,
940 impl MsgEncodable for OnionHopData {
941 fn encode(&self) -> Vec<u8> {
942 let mut res = Vec::with_capacity(65);
943 res.push(self.realm);
944 res.extend_from_slice(&self.data.encode()[..]);
945 res.extend_from_slice(&self.hmac);
950 impl MsgDecodable for OnionPacket {
951 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
955 impl MsgEncodable for OnionPacket {
956 fn encode(&self) -> Vec<u8> {
957 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
958 res.push(self.version);
959 res.extend_from_slice(&self.public_key.serialize());
960 res.extend_from_slice(&self.hop_data);
961 res.extend_from_slice(&self.hmac);
966 impl MsgDecodable for DecodedOnionErrorPacket {
967 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
971 impl MsgEncodable for DecodedOnionErrorPacket {
972 fn encode(&self) -> Vec<u8> {
973 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
974 res.extend_from_slice(&self.hmac);
975 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
976 res.extend_from_slice(&self.failuremsg);
977 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
978 res.extend_from_slice(&self.pad);
983 impl MsgDecodable for OnionErrorPacket {
984 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
988 impl MsgEncodable for OnionErrorPacket {
989 fn encode(&self) -> Vec<u8> {