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 global_features.flags.len() + 4 <= v.len() {
494 return Err(DecodeError::WrongLength);
496 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
497 if global_features.flags.len() + local_features.flags.len() + 4 != v.len() {
498 return Err(DecodeError::WrongLength);
501 global_features: global_features,
502 local_features: local_features,
506 impl MsgEncodable for Init {
507 fn encode(&self) -> Vec<u8> {
508 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
509 res.extend_from_slice(&self.global_features.encode()[..]);
510 res.extend_from_slice(&self.local_features.encode()[..]);
515 impl MsgDecodable for OpenChannel {
516 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
517 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
518 return Err(DecodeError::WrongLength);
520 let ctx = Secp256k1::without_caps();
522 let mut shutdown_scriptpubkey = None;
524 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
525 if v.len() != 321+len {
526 return Err(DecodeError::WrongLength);
528 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
529 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 {
530 return Err(DecodeError::WrongLength);
534 chain_hash: deserialize(&v[0..32]).unwrap(),
535 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
536 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
537 push_msat: byte_utils::slice_to_be64(&v[72..80]),
538 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
539 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
540 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
541 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
542 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
543 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
544 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
545 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
546 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
547 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
548 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
549 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
550 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
551 channel_flags: v[318],
552 shutdown_scriptpubkey: shutdown_scriptpubkey
556 impl MsgEncodable for OpenChannel {
557 fn encode(&self) -> Vec<u8> {
562 impl MsgDecodable for AcceptChannel {
563 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
564 if v.len() < 32+4*8+4+2*2+6*33 {
565 return Err(DecodeError::WrongLength);
567 let ctx = Secp256k1::without_caps();
569 let mut shutdown_scriptpubkey = None;
571 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
572 if v.len() != 272+len {
573 return Err(DecodeError::WrongLength);
575 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
576 } else if v.len() != 32+4*8+4+2*2+6*33 {
577 return Err(DecodeError::WrongLength);
581 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
582 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
583 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
584 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
585 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
586 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
587 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
588 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
589 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
590 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
591 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
592 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
593 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
594 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
595 shutdown_scriptpubkey: shutdown_scriptpubkey
599 impl MsgEncodable for AcceptChannel {
600 fn encode(&self) -> Vec<u8> {
605 impl MsgDecodable for FundingCreated {
606 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
607 if v.len() != 32+32+2+64 {
608 return Err(DecodeError::WrongLength);
610 let ctx = Secp256k1::without_caps();
612 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
613 funding_txid: deserialize(&v[32..64]).unwrap(),
614 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
615 signature: secp_signature!(&ctx, &v[66..130]),
619 impl MsgEncodable for FundingCreated {
620 fn encode(&self) -> Vec<u8> {
625 impl MsgDecodable for FundingSigned {
626 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
627 if v.len() != 32+64 {
628 return Err(DecodeError::WrongLength);
630 let ctx = Secp256k1::without_caps();
632 channel_id: deserialize(&v[0..32]).unwrap(),
633 signature: secp_signature!(&ctx, &v[32..96]),
637 impl MsgEncodable for FundingSigned {
638 fn encode(&self) -> Vec<u8> {
643 impl MsgDecodable for FundingLocked {
644 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
645 if v.len() != 32+33 {
646 return Err(DecodeError::WrongLength);
648 let ctx = Secp256k1::without_caps();
650 channel_id: deserialize(&v[0..32]).unwrap(),
651 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
655 impl MsgEncodable for FundingLocked {
656 fn encode(&self) -> Vec<u8> {
661 impl MsgDecodable for Shutdown {
662 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
666 impl MsgEncodable for Shutdown {
667 fn encode(&self) -> Vec<u8> {
672 impl MsgDecodable for ClosingSigned {
673 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
677 impl MsgEncodable for ClosingSigned {
678 fn encode(&self) -> Vec<u8> {
683 impl MsgDecodable for UpdateAddHTLC {
684 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
688 impl MsgEncodable for UpdateAddHTLC {
689 fn encode(&self) -> Vec<u8> {
694 impl MsgDecodable for UpdateFulfillHTLC {
695 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
699 impl MsgEncodable for UpdateFulfillHTLC {
700 fn encode(&self) -> Vec<u8> {
705 impl MsgDecodable for UpdateFailHTLC {
706 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
710 impl MsgEncodable for UpdateFailHTLC {
711 fn encode(&self) -> Vec<u8> {
716 impl MsgDecodable for UpdateFailMalformedHTLC {
717 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
721 impl MsgEncodable for UpdateFailMalformedHTLC {
722 fn encode(&self) -> Vec<u8> {
727 impl MsgDecodable for CommitmentSigned {
728 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
732 impl MsgEncodable for CommitmentSigned {
733 fn encode(&self) -> Vec<u8> {
738 impl MsgDecodable for RevokeAndACK {
739 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
743 impl MsgEncodable for RevokeAndACK {
744 fn encode(&self) -> Vec<u8> {
749 impl MsgDecodable for UpdateFee {
750 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
754 impl MsgEncodable for UpdateFee {
755 fn encode(&self) -> Vec<u8> {
760 impl MsgDecodable for ChannelReestablish {
761 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
765 impl MsgEncodable for ChannelReestablish {
766 fn encode(&self) -> Vec<u8> {
771 impl MsgDecodable for AnnouncementSignatures {
772 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
776 impl MsgEncodable for AnnouncementSignatures {
777 fn encode(&self) -> Vec<u8> {
782 impl MsgDecodable for UnsignedNodeAnnouncement {
783 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
787 impl MsgEncodable for UnsignedNodeAnnouncement {
788 fn encode(&self) -> Vec<u8> {
789 let features = self.features.encode();
790 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
791 res.extend_from_slice(&features[..]);
792 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
793 res.extend_from_slice(&self.node_id.serialize());
794 res.extend_from_slice(&self.rgb);
795 res.extend_from_slice(&self.alias);
796 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
797 for addr in self.addresses.iter() {
799 &NetAddress::Dummy => {},
800 &NetAddress::IPv4{addr, port} => {
801 addr_slice.extend_from_slice(&addr);
802 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
804 &NetAddress::IPv6{addr, port} => {
805 addr_slice.extend_from_slice(&addr);
806 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
808 &NetAddress::OnionV2{addr, port} => {
809 addr_slice.extend_from_slice(&addr);
810 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
812 &NetAddress::OnionV3{ed25519_pubkey, checksum, version} => {
813 addr_slice.extend_from_slice(&ed25519_pubkey);
814 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
815 addr_slice.push(version);
819 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
820 res.extend_from_slice(&addr_slice[..]);
825 impl MsgDecodable for NodeAnnouncement {
826 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
830 impl MsgEncodable for NodeAnnouncement {
831 fn encode(&self) -> Vec<u8> {
836 impl MsgDecodable for UnsignedChannelAnnouncement {
837 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
841 impl MsgEncodable for UnsignedChannelAnnouncement {
842 fn encode(&self) -> Vec<u8> {
843 let features = self.features.encode();
844 let mut res = Vec::with_capacity(172 + features.len());
845 res.extend_from_slice(&features[..]);
846 res.extend_from_slice(&self.chain_hash[..]);
847 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
848 res.extend_from_slice(&self.node_id_1.serialize());
849 res.extend_from_slice(&self.node_id_2.serialize());
850 res.extend_from_slice(&self.bitcoin_key_1.serialize());
851 res.extend_from_slice(&self.bitcoin_key_2.serialize());
856 impl MsgDecodable for ChannelAnnouncement {
857 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
861 impl MsgEncodable for ChannelAnnouncement {
862 fn encode(&self) -> Vec<u8> {
867 impl MsgDecodable for UnsignedChannelUpdate {
868 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
872 impl MsgEncodable for UnsignedChannelUpdate {
873 fn encode(&self) -> Vec<u8> {
874 let mut res = Vec::with_capacity(64);
875 res.extend_from_slice(&self.chain_hash[..]);
876 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
877 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
878 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
879 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
880 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
881 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
882 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
887 impl MsgDecodable for ChannelUpdate {
888 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
892 impl MsgEncodable for ChannelUpdate {
893 fn encode(&self) -> Vec<u8> {
894 let mut res = Vec::with_capacity(128);
895 //TODO: Should avoid creating a new secp ctx just for a serialize call :(
896 res.extend_from_slice(&self.signature.serialize_der(&Secp256k1::new())[..]); //TODO: Need in non-der form! (probably elsewhere too)
897 res.extend_from_slice(&self.contents.encode()[..]);
902 impl MsgDecodable for OnionRealm0HopData {
903 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
905 return Err(DecodeError::WrongLength);
907 Ok(OnionRealm0HopData {
908 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
909 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
910 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
914 impl MsgEncodable for OnionRealm0HopData {
915 fn encode(&self) -> Vec<u8> {
916 let mut res = Vec::with_capacity(32);
917 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
918 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
919 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
925 impl MsgDecodable for OnionHopData {
926 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
928 return Err(DecodeError::WrongLength);
932 return Err(DecodeError::UnknownRealmByte);
934 let mut hmac = [0; 32];
935 hmac[..].copy_from_slice(&v[33..65]);
938 data: OnionRealm0HopData::decode(&v[1..33])?,
943 impl MsgEncodable for OnionHopData {
944 fn encode(&self) -> Vec<u8> {
945 let mut res = Vec::with_capacity(65);
946 res.push(self.realm);
947 res.extend_from_slice(&self.data.encode()[..]);
948 res.extend_from_slice(&self.hmac);
953 impl MsgDecodable for OnionPacket {
954 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
958 impl MsgEncodable for OnionPacket {
959 fn encode(&self) -> Vec<u8> {
960 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
961 res.push(self.version);
962 res.extend_from_slice(&self.public_key.serialize());
963 res.extend_from_slice(&self.hop_data);
964 res.extend_from_slice(&self.hmac);
969 impl MsgDecodable for DecodedOnionErrorPacket {
970 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
974 impl MsgEncodable for DecodedOnionErrorPacket {
975 fn encode(&self) -> Vec<u8> {
976 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
977 res.extend_from_slice(&self.hmac);
978 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
979 res.extend_from_slice(&self.failuremsg);
980 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
981 res.extend_from_slice(&self.pad);
986 impl MsgDecodable for OnionErrorPacket {
987 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
991 impl MsgEncodable for OnionErrorPacket {
992 fn encode(&self) -> Vec<u8> {