1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::{deserialize,serialize};
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>;
17 fn encoded_len(&self) -> usize { self.encode().len() }
19 fn encode_with_len(&self) -> Vec<u8> {
20 let enc = self.encode();
21 let mut res = Vec::with_capacity(enc.len() + 2);
22 res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
23 res.extend_from_slice(&enc);
28 pub enum DecodeError {
29 /// Unknown realm byte in an OnionHopData packet
31 /// Unknown feature mandating we fail to parse message
32 UnknownRequiredFeature,
33 /// Failed to decode a public key (ie it's invalid)
35 /// Failed to decode a signature (ie it's invalid)
37 /// Value expected to be text wasn't decodable as text
41 /// node_announcement included more than one address of a given type!
42 ExtraAddressesPerType,
43 /// A length descriptor in the packet didn't describe the later data correctly
44 /// (currently only generated in node_announcement)
47 pub trait MsgDecodable: Sized {
48 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
51 /// Tracks localfeatures which are only in init messages
52 #[derive(Clone, PartialEq)]
53 pub struct LocalFeatures {
58 pub fn new() -> LocalFeatures {
64 pub fn supports_data_loss_protect(&self) -> bool {
65 self.flags.len() > 0 && (self.flags[0] & 3) != 0
67 pub fn requires_data_loss_protect(&self) -> bool {
68 self.flags.len() > 0 && (self.flags[0] & 1) != 0
71 pub fn initial_routing_sync(&self) -> bool {
72 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
74 pub fn set_initial_routing_sync(&mut self) {
75 if self.flags.len() == 0 {
76 self.flags.resize(1, 1 << 3);
78 self.flags[0] |= 1 << 3;
82 pub fn supports_upfront_shutdown_script(&self) -> bool {
83 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
85 pub fn requires_upfront_shutdown_script(&self) -> bool {
86 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
89 pub fn requires_unknown_bits(&self) -> bool {
90 for (idx, &byte) in self.flags.iter().enumerate() {
91 if idx != 0 && (byte & 0x55) != 0 {
93 } else if idx == 0 && (byte & 0x14) != 0 {
100 pub fn supports_unknown_bits(&self) -> bool {
101 for (idx, &byte) in self.flags.iter().enumerate() {
102 if idx != 0 && byte != 0 {
104 } else if idx == 0 && (byte & 0xc4) != 0 {
112 /// Tracks globalfeatures which are in init messages and routing announcements
113 #[derive(Clone, PartialEq)]
114 pub struct GlobalFeatures {
118 impl GlobalFeatures {
119 pub fn new() -> GlobalFeatures {
125 pub fn requires_unknown_bits(&self) -> bool {
126 for &byte in self.flags.iter() {
127 if (byte & 0x55) != 0 {
134 pub fn supports_unknown_bits(&self) -> bool {
135 for &byte in self.flags.iter() {
145 pub global_features: GlobalFeatures,
146 pub local_features: LocalFeatures,
149 pub struct ErrorMessage {
150 pub channel_id: [u8; 32],
163 pub struct OpenChannel {
164 pub chain_hash: Sha256dHash,
165 pub temporary_channel_id: [u8; 32],
166 pub funding_satoshis: u64,
168 pub dust_limit_satoshis: u64,
169 pub max_htlc_value_in_flight_msat: u64,
170 pub channel_reserve_satoshis: u64,
171 pub htlc_minimum_msat: u64,
172 pub feerate_per_kw: u32,
173 pub to_self_delay: u16,
174 pub max_accepted_htlcs: u16,
175 pub funding_pubkey: PublicKey,
176 pub revocation_basepoint: PublicKey,
177 pub payment_basepoint: PublicKey,
178 pub delayed_payment_basepoint: PublicKey,
179 pub htlc_basepoint: PublicKey,
180 pub first_per_commitment_point: PublicKey,
181 pub channel_flags: u8,
182 pub shutdown_scriptpubkey: Option<Script>,
185 pub struct AcceptChannel {
186 pub temporary_channel_id: [u8; 32],
187 pub dust_limit_satoshis: u64,
188 pub max_htlc_value_in_flight_msat: u64,
189 pub channel_reserve_satoshis: u64,
190 pub htlc_minimum_msat: u64,
191 pub minimum_depth: u32,
192 pub to_self_delay: u16,
193 pub max_accepted_htlcs: u16,
194 pub funding_pubkey: PublicKey,
195 pub revocation_basepoint: PublicKey,
196 pub payment_basepoint: PublicKey,
197 pub delayed_payment_basepoint: PublicKey,
198 pub htlc_basepoint: PublicKey,
199 pub first_per_commitment_point: PublicKey,
200 pub shutdown_scriptpubkey: Option<Script>,
203 pub struct FundingCreated {
204 pub temporary_channel_id: [u8; 32],
205 pub funding_txid: Sha256dHash,
206 pub funding_output_index: u16,
207 pub signature: Signature,
210 pub struct FundingSigned {
211 pub channel_id: [u8; 32],
212 pub signature: Signature,
215 pub struct FundingLocked {
216 pub channel_id: [u8; 32],
217 pub next_per_commitment_point: PublicKey,
220 pub struct Shutdown {
221 pub channel_id: [u8; 32],
222 pub scriptpubkey: Script,
225 pub struct ClosingSigned {
226 pub channel_id: [u8; 32],
227 pub fee_satoshis: u64,
228 pub signature: Signature,
232 pub struct UpdateAddHTLC {
233 pub channel_id: [u8; 32],
235 pub amount_msat: u64,
236 pub payment_hash: [u8; 32],
237 pub cltv_expiry: u32,
238 pub onion_routing_packet: OnionPacket,
242 pub struct UpdateFulfillHTLC {
243 pub channel_id: [u8; 32],
245 pub payment_preimage: [u8; 32],
249 pub struct UpdateFailHTLC {
250 pub channel_id: [u8; 32],
252 pub reason: OnionErrorPacket,
256 pub struct UpdateFailMalformedHTLC {
257 pub channel_id: [u8; 32],
259 pub sha256_of_onion: [u8; 32],
260 pub failure_code: u16,
264 pub struct CommitmentSigned {
265 pub channel_id: [u8; 32],
266 pub signature: Signature,
267 pub htlc_signatures: Vec<Signature>,
270 pub struct RevokeAndACK {
271 pub channel_id: [u8; 32],
272 pub per_commitment_secret: [u8; 32],
273 pub next_per_commitment_point: PublicKey,
276 pub struct UpdateFee {
277 pub channel_id: [u8; 32],
278 pub feerate_per_kw: u32,
281 pub struct DataLossProtect {
282 pub your_last_per_commitment_secret: [u8; 32],
283 pub my_current_per_commitment_point: PublicKey,
286 pub struct ChannelReestablish {
287 pub channel_id: [u8; 32],
288 pub next_local_commitment_number: u64,
289 pub next_remote_commitment_number: u64,
290 pub data_loss_protect: Option<DataLossProtect>,
294 pub struct AnnouncementSignatures {
295 pub channel_id: [u8; 32],
296 pub short_channel_id: u64,
297 pub node_signature: Signature,
298 pub bitcoin_signature: Signature,
302 pub enum NetAddress {
316 ed25519_pubkey: [u8; 32],
323 fn get_id(&self) -> u8 {
325 &NetAddress::IPv4 {..} => { 1 },
326 &NetAddress::IPv6 {..} => { 2 },
327 &NetAddress::OnionV2 {..} => { 3 },
328 &NetAddress::OnionV3 {..} => { 4 },
333 pub struct UnsignedNodeAnnouncement {
334 pub features: GlobalFeatures,
336 pub node_id: PublicKey,
339 /// List of addresses on which this node is reachable. Note that you may only have up to one
340 /// address of each type, if you have more, they may be silently discarded or we may panic!
341 pub addresses: Vec<NetAddress>,
342 pub excess_address_data: Vec<u8>,
343 pub excess_data: Vec<u8>,
345 pub struct NodeAnnouncement {
346 pub signature: Signature,
347 pub contents: UnsignedNodeAnnouncement,
350 #[derive(PartialEq, Clone)]
351 pub struct UnsignedChannelAnnouncement {
352 pub features: GlobalFeatures,
353 pub chain_hash: Sha256dHash,
354 pub short_channel_id: u64,
355 pub node_id_1: PublicKey,
356 pub node_id_2: PublicKey,
357 pub bitcoin_key_1: PublicKey,
358 pub bitcoin_key_2: PublicKey,
359 pub excess_data: Vec<u8>,
361 #[derive(PartialEq, Clone)]
362 pub struct ChannelAnnouncement {
363 pub node_signature_1: Signature,
364 pub node_signature_2: Signature,
365 pub bitcoin_signature_1: Signature,
366 pub bitcoin_signature_2: Signature,
367 pub contents: UnsignedChannelAnnouncement,
370 #[derive(PartialEq, Clone)]
371 pub struct UnsignedChannelUpdate {
372 pub chain_hash: Sha256dHash,
373 pub short_channel_id: u64,
376 pub cltv_expiry_delta: u16,
377 pub htlc_minimum_msat: u64,
378 pub fee_base_msat: u32,
379 pub fee_proportional_millionths: u32,
380 pub excess_data: Vec<u8>,
382 #[derive(PartialEq, Clone)]
383 pub struct ChannelUpdate {
384 pub signature: Signature,
385 pub contents: UnsignedChannelUpdate,
388 /// Used to put an error message in a HandleError
389 pub enum ErrorAction {
390 /// The peer took some action which made us think they were useless. Disconnect them.
392 msg: Option<ErrorMessage>
394 /// The peer did something harmless that we weren't able to process, just log and ignore
396 /// The peer did something incorrect. Tell them.
402 pub struct HandleError { //TODO: rename me
403 pub err: &'static str,
404 pub action: Option<ErrorAction>, //TODO: Make this required
407 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
408 /// transaction updates if they were pending.
409 pub struct CommitmentUpdate {
410 pub update_add_htlcs: Vec<UpdateAddHTLC>,
411 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
412 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
413 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
414 pub commitment_signed: CommitmentSigned,
417 pub enum HTLCFailChannelUpdate {
418 ChannelUpdateMessage {
422 short_channel_id: u64,
426 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
427 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
428 /// paralell when the two calls have the same their_node_id.
429 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
431 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
432 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
433 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
434 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
435 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
438 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
439 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
442 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
443 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
444 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
445 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
446 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
447 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
449 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
451 // Channel-to-announce:
452 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
455 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
456 /// is believed to be possible in the future (eg they're sending us messages we don't
457 /// understand or indicate they require unknown feature bits), no_connection_possible is set
458 /// and any outstanding channels should be failed.
459 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
461 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
464 pub trait RoutingMessageHandler : Send + Sync {
465 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
466 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
467 /// or returning an Err otherwise.
468 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
469 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
470 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
473 pub struct OnionRealm0HopData {
474 pub short_channel_id: u64,
475 pub amt_to_forward: u64,
476 pub outgoing_cltv_value: u32,
477 // 12 bytes of 0-padding
480 pub struct OnionHopData {
482 pub data: OnionRealm0HopData,
485 unsafe impl internal_traits::NoDealloc for OnionHopData{}
488 pub struct OnionPacket {
490 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
491 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
492 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
493 pub public_key: Result<PublicKey, secp256k1::Error>,
494 pub hop_data: [u8; 20*65],
498 pub struct DecodedOnionErrorPacket {
500 pub failuremsg: Vec<u8>,
505 pub struct OnionErrorPacket {
506 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
507 // (TODO) We limit it in decode to much lower...
511 impl Error for DecodeError {
512 fn description(&self) -> &str {
514 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
515 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
516 DecodeError::BadPublicKey => "Invalid public key in packet",
517 DecodeError::BadSignature => "Invalid signature in packet",
518 DecodeError::BadText => "Invalid text in packet",
519 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
520 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
521 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
525 impl fmt::Display for DecodeError {
526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527 f.write_str(self.description())
531 impl fmt::Debug for HandleError {
532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
533 f.write_str(self.err)
537 macro_rules! secp_pubkey {
538 ( $ctx: expr, $slice: expr ) => {
539 match PublicKey::from_slice($ctx, $slice) {
541 Err(_) => return Err(DecodeError::BadPublicKey)
546 macro_rules! secp_signature {
547 ( $ctx: expr, $slice: expr ) => {
548 match Signature::from_compact($ctx, $slice) {
550 Err(_) => return Err(DecodeError::BadSignature)
555 impl MsgDecodable for LocalFeatures {
556 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
557 if v.len() < 2 { return Err(DecodeError::ShortRead); }
558 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
559 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
560 let mut flags = Vec::with_capacity(len);
561 flags.extend_from_slice(&v[2..2 + len]);
567 impl MsgEncodable for LocalFeatures {
568 fn encode(&self) -> Vec<u8> {
569 let mut res = Vec::with_capacity(self.flags.len() + 2);
570 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
571 res.extend_from_slice(&self.flags[..]);
574 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
577 impl MsgDecodable for GlobalFeatures {
578 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
579 if v.len() < 2 { return Err(DecodeError::ShortRead); }
580 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
581 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
582 let mut flags = Vec::with_capacity(len);
583 flags.extend_from_slice(&v[2..2 + len]);
589 impl MsgEncodable for GlobalFeatures {
590 fn encode(&self) -> Vec<u8> {
591 let mut res = Vec::with_capacity(self.flags.len() + 2);
592 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
593 res.extend_from_slice(&self.flags[..]);
596 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
599 impl MsgDecodable for Init {
600 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
601 let global_features = GlobalFeatures::decode(v)?;
602 if v.len() < global_features.flags.len() + 4 {
603 return Err(DecodeError::ShortRead);
605 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
607 global_features: global_features,
608 local_features: local_features,
612 impl MsgEncodable for Init {
613 fn encode(&self) -> Vec<u8> {
614 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
615 res.extend_from_slice(&self.global_features.encode()[..]);
616 res.extend_from_slice(&self.local_features.encode()[..]);
621 impl MsgDecodable for Ping {
622 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
624 return Err(DecodeError::ShortRead);
626 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
627 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
628 if v.len() < 4 + byteslen as usize {
629 return Err(DecodeError::ShortRead);
637 impl MsgEncodable for Ping {
638 fn encode(&self) -> Vec<u8> {
639 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
640 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
641 res.resize(2 + self.byteslen as usize, 0);
646 impl MsgDecodable for Pong {
647 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
649 return Err(DecodeError::ShortRead);
651 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
652 if v.len() < 2 + byteslen as usize {
653 return Err(DecodeError::ShortRead);
660 impl MsgEncodable for Pong {
661 fn encode(&self) -> Vec<u8> {
662 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
663 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
664 res.resize(2 + self.byteslen as usize, 0);
669 impl MsgDecodable for OpenChannel {
670 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
671 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
672 return Err(DecodeError::ShortRead);
674 let ctx = Secp256k1::without_caps();
676 let mut shutdown_scriptpubkey = None;
678 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
679 if v.len() < 321+len {
680 return Err(DecodeError::ShortRead);
682 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
684 let mut temp_channel_id = [0; 32];
685 temp_channel_id[..].copy_from_slice(&v[32..64]);
687 chain_hash: deserialize(&v[0..32]).unwrap(),
688 temporary_channel_id: temp_channel_id,
689 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
690 push_msat: byte_utils::slice_to_be64(&v[72..80]),
691 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
692 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
693 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
694 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
695 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
696 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
697 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
698 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
699 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
700 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
701 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
702 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
703 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
704 channel_flags: v[318],
705 shutdown_scriptpubkey: shutdown_scriptpubkey
709 impl MsgEncodable for OpenChannel {
710 fn encode(&self) -> Vec<u8> {
711 let mut res = match &self.shutdown_scriptpubkey {
712 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
713 &None => Vec::with_capacity(319),
715 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
716 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
717 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
718 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
719 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
720 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
721 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
722 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
723 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
724 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
725 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
726 res.extend_from_slice(&self.funding_pubkey.serialize());
727 res.extend_from_slice(&self.revocation_basepoint.serialize());
728 res.extend_from_slice(&self.payment_basepoint.serialize());
729 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
730 res.extend_from_slice(&self.htlc_basepoint.serialize());
731 res.extend_from_slice(&self.first_per_commitment_point.serialize());
732 res.push(self.channel_flags);
733 if let &Some(ref script) = &self.shutdown_scriptpubkey {
734 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
735 res.extend_from_slice(&script[..]);
741 impl MsgDecodable for AcceptChannel {
742 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
743 if v.len() < 32+4*8+4+2*2+6*33 {
744 return Err(DecodeError::ShortRead);
746 let ctx = Secp256k1::without_caps();
748 let mut shutdown_scriptpubkey = None;
750 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
751 if v.len() < 272+len {
752 return Err(DecodeError::ShortRead);
754 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
757 let mut temporary_channel_id = [0; 32];
758 temporary_channel_id[..].copy_from_slice(&v[0..32]);
760 temporary_channel_id,
761 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
762 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
763 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
764 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
765 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
766 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
767 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
768 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
769 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
770 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
771 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
772 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
773 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
774 shutdown_scriptpubkey: shutdown_scriptpubkey
778 impl MsgEncodable for AcceptChannel {
779 fn encode(&self) -> Vec<u8> {
780 let mut res = match &self.shutdown_scriptpubkey {
781 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
782 &None => Vec::with_capacity(270),
784 res.extend_from_slice(&self.temporary_channel_id);
785 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
786 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
787 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
788 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
789 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
790 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
791 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
792 res.extend_from_slice(&self.funding_pubkey.serialize());
793 res.extend_from_slice(&self.revocation_basepoint.serialize());
794 res.extend_from_slice(&self.payment_basepoint.serialize());
795 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
796 res.extend_from_slice(&self.htlc_basepoint.serialize());
797 res.extend_from_slice(&self.first_per_commitment_point.serialize());
798 if let &Some(ref script) = &self.shutdown_scriptpubkey {
799 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
800 res.extend_from_slice(&script[..]);
806 impl MsgDecodable for FundingCreated {
807 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
808 if v.len() < 32+32+2+64 {
809 return Err(DecodeError::ShortRead);
811 let ctx = Secp256k1::without_caps();
812 let mut temporary_channel_id = [0; 32];
813 temporary_channel_id[..].copy_from_slice(&v[0..32]);
815 temporary_channel_id,
816 funding_txid: deserialize(&v[32..64]).unwrap(),
817 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
818 signature: secp_signature!(&ctx, &v[66..130]),
822 impl MsgEncodable for FundingCreated {
823 fn encode(&self) -> Vec<u8> {
824 let mut res = Vec::with_capacity(32+32+2+64);
825 res.extend_from_slice(&self.temporary_channel_id);
826 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
827 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
828 let secp_ctx = Secp256k1::without_caps();
829 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
834 impl MsgDecodable for FundingSigned {
835 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
837 return Err(DecodeError::ShortRead);
839 let ctx = Secp256k1::without_caps();
840 let mut channel_id = [0; 32];
841 channel_id[..].copy_from_slice(&v[0..32]);
844 signature: secp_signature!(&ctx, &v[32..96]),
848 impl MsgEncodable for FundingSigned {
849 fn encode(&self) -> Vec<u8> {
850 let mut res = Vec::with_capacity(32+64);
851 res.extend_from_slice(&self.channel_id);
852 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
857 impl MsgDecodable for FundingLocked {
858 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
860 return Err(DecodeError::ShortRead);
862 let ctx = Secp256k1::without_caps();
863 let mut channel_id = [0; 32];
864 channel_id[..].copy_from_slice(&v[0..32]);
867 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
871 impl MsgEncodable for FundingLocked {
872 fn encode(&self) -> Vec<u8> {
873 let mut res = Vec::with_capacity(32+33);
874 res.extend_from_slice(&self.channel_id);
875 res.extend_from_slice(&self.next_per_commitment_point.serialize());
880 impl MsgDecodable for Shutdown {
881 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
882 if v.len() < 32 + 2 {
883 return Err(DecodeError::ShortRead);
885 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
886 if v.len() < 32 + 2 + scriptlen {
887 return Err(DecodeError::ShortRead);
889 let mut channel_id = [0; 32];
890 channel_id[..].copy_from_slice(&v[0..32]);
893 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
897 impl MsgEncodable for Shutdown {
898 fn encode(&self) -> Vec<u8> {
899 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
900 res.extend_from_slice(&self.channel_id);
901 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
902 res.extend_from_slice(&self.scriptpubkey[..]);
907 impl MsgDecodable for ClosingSigned {
908 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
909 if v.len() < 32 + 8 + 64 {
910 return Err(DecodeError::ShortRead);
912 let secp_ctx = Secp256k1::without_caps();
913 let mut channel_id = [0; 32];
914 channel_id[..].copy_from_slice(&v[0..32]);
917 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
918 signature: secp_signature!(&secp_ctx, &v[40..104]),
922 impl MsgEncodable for ClosingSigned {
923 fn encode(&self) -> Vec<u8> {
924 let mut res = Vec::with_capacity(32+8+64);
925 res.extend_from_slice(&self.channel_id);
926 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
927 let secp_ctx = Secp256k1::without_caps();
928 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
933 impl MsgDecodable for UpdateAddHTLC {
934 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
935 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
936 return Err(DecodeError::ShortRead);
938 let mut channel_id = [0; 32];
939 channel_id[..].copy_from_slice(&v[0..32]);
940 let mut payment_hash = [0; 32];
941 payment_hash.copy_from_slice(&v[48..80]);
944 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
945 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
947 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
948 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
952 impl MsgEncodable for UpdateAddHTLC {
953 fn encode(&self) -> Vec<u8> {
954 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
955 res.extend_from_slice(&self.channel_id);
956 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
957 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
958 res.extend_from_slice(&self.payment_hash);
959 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
960 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
965 impl MsgDecodable for UpdateFulfillHTLC {
966 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
967 if v.len() < 32+8+32 {
968 return Err(DecodeError::ShortRead);
970 let mut channel_id = [0; 32];
971 channel_id[..].copy_from_slice(&v[0..32]);
972 let mut payment_preimage = [0; 32];
973 payment_preimage.copy_from_slice(&v[40..72]);
976 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
981 impl MsgEncodable for UpdateFulfillHTLC {
982 fn encode(&self) -> Vec<u8> {
983 let mut res = Vec::with_capacity(32+8+32);
984 res.extend_from_slice(&self.channel_id);
985 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
986 res.extend_from_slice(&self.payment_preimage);
991 impl MsgDecodable for UpdateFailHTLC {
992 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
994 return Err(DecodeError::ShortRead);
996 let mut channel_id = [0; 32];
997 channel_id[..].copy_from_slice(&v[0..32]);
1000 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1001 reason: OnionErrorPacket::decode(&v[40..])?,
1005 impl MsgEncodable for UpdateFailHTLC {
1006 fn encode(&self) -> Vec<u8> {
1007 let reason = self.reason.encode();
1008 let mut res = Vec::with_capacity(32+8+reason.len());
1009 res.extend_from_slice(&self.channel_id);
1010 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1011 res.extend_from_slice(&reason[..]);
1016 impl MsgDecodable for UpdateFailMalformedHTLC {
1017 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1018 if v.len() < 32+8+32+2 {
1019 return Err(DecodeError::ShortRead);
1021 let mut channel_id = [0; 32];
1022 channel_id[..].copy_from_slice(&v[0..32]);
1023 let mut sha256_of_onion = [0; 32];
1024 sha256_of_onion.copy_from_slice(&v[40..72]);
1027 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1029 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1033 impl MsgEncodable for UpdateFailMalformedHTLC {
1034 fn encode(&self) -> Vec<u8> {
1035 let mut res = Vec::with_capacity(32+8+32+2);
1036 res.extend_from_slice(&self.channel_id);
1037 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1038 res.extend_from_slice(&self.sha256_of_onion);
1039 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1044 impl MsgDecodable for CommitmentSigned {
1045 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1046 if v.len() < 32+64+2 {
1047 return Err(DecodeError::ShortRead);
1049 let mut channel_id = [0; 32];
1050 channel_id[..].copy_from_slice(&v[0..32]);
1052 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1053 if v.len() < 32+64+2+htlcs*64 {
1054 return Err(DecodeError::ShortRead);
1056 let mut htlc_signatures = Vec::with_capacity(htlcs);
1057 let secp_ctx = Secp256k1::without_caps();
1059 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1063 signature: secp_signature!(&secp_ctx, &v[32..96]),
1068 impl MsgEncodable for CommitmentSigned {
1069 fn encode(&self) -> Vec<u8> {
1070 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1071 res.extend_from_slice(&self.channel_id);
1072 let secp_ctx = Secp256k1::without_caps();
1073 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1074 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1075 for i in 0..self.htlc_signatures.len() {
1076 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1082 impl MsgDecodable for RevokeAndACK {
1083 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1084 if v.len() < 32+32+33 {
1085 return Err(DecodeError::ShortRead);
1087 let mut channel_id = [0; 32];
1088 channel_id[..].copy_from_slice(&v[0..32]);
1089 let mut per_commitment_secret = [0; 32];
1090 per_commitment_secret.copy_from_slice(&v[32..64]);
1091 let secp_ctx = Secp256k1::without_caps();
1094 per_commitment_secret,
1095 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1099 impl MsgEncodable for RevokeAndACK {
1100 fn encode(&self) -> Vec<u8> {
1101 let mut res = Vec::with_capacity(32+32+33);
1102 res.extend_from_slice(&self.channel_id);
1103 res.extend_from_slice(&self.per_commitment_secret);
1104 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1109 impl MsgDecodable for UpdateFee {
1110 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1112 return Err(DecodeError::ShortRead);
1114 let mut channel_id = [0; 32];
1115 channel_id[..].copy_from_slice(&v[0..32]);
1118 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1122 impl MsgEncodable for UpdateFee {
1123 fn encode(&self) -> Vec<u8> {
1124 let mut res = Vec::with_capacity(32+4);
1125 res.extend_from_slice(&self.channel_id);
1126 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1131 impl MsgDecodable for ChannelReestablish {
1132 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1133 if v.len() < 32+2*8 {
1134 return Err(DecodeError::ShortRead);
1137 let data_loss_protect = if v.len() > 32+2*8 {
1138 if v.len() < 32+2*8 + 33+32 {
1139 return Err(DecodeError::ShortRead);
1141 let mut inner_array = [0; 32];
1142 inner_array.copy_from_slice(&v[48..48+32]);
1143 Some(DataLossProtect {
1144 your_last_per_commitment_secret: inner_array,
1145 my_current_per_commitment_point: secp_pubkey!(&Secp256k1::without_caps(), &v[48+32..48+32+33]),
1150 channel_id: deserialize(&v[0..32]).unwrap(),
1151 next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1152 next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1153 data_loss_protect: data_loss_protect,
1157 impl MsgEncodable for ChannelReestablish {
1158 fn encode(&self) -> Vec<u8> {
1159 let mut res = Vec::with_capacity(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
1161 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1162 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1163 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1165 if let &Some(ref data_loss_protect) = &self.data_loss_protect {
1166 res.extend_from_slice(&data_loss_protect.your_last_per_commitment_secret[..]);
1167 res.extend_from_slice(&data_loss_protect.my_current_per_commitment_point.serialize());
1173 impl MsgDecodable for AnnouncementSignatures {
1174 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1175 if v.len() < 32+8+64*2 {
1176 return Err(DecodeError::ShortRead);
1178 let secp_ctx = Secp256k1::without_caps();
1179 let mut channel_id = [0; 32];
1180 channel_id[..].copy_from_slice(&v[0..32]);
1183 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1184 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1185 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1189 impl MsgEncodable for AnnouncementSignatures {
1190 fn encode(&self) -> Vec<u8> {
1191 let mut res = Vec::with_capacity(32+8+64*2);
1192 res.extend_from_slice(&self.channel_id);
1193 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1194 let secp_ctx = Secp256k1::without_caps();
1195 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1196 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1201 impl MsgDecodable for UnsignedNodeAnnouncement {
1202 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1203 let features = GlobalFeatures::decode(&v[..])?;
1204 if features.requires_unknown_bits() {
1205 return Err(DecodeError::UnknownRequiredFeature);
1208 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1209 return Err(DecodeError::ShortRead);
1211 let start = features.encoded_len();
1213 let mut rgb = [0; 3];
1214 rgb.copy_from_slice(&v[start + 37..start + 40]);
1216 let mut alias = [0; 32];
1217 alias.copy_from_slice(&v[start + 40..start + 72]);
1219 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1220 if v.len() < start + 74 + addrlen {
1221 return Err(DecodeError::ShortRead);
1223 let addr_read_limit = start + 74 + addrlen;
1225 let mut addresses = Vec::with_capacity(4);
1226 let mut read_pos = start + 74;
1228 if addr_read_limit <= read_pos { break; }
1231 if addresses.len() > 0 {
1232 return Err(DecodeError::ExtraAddressesPerType);
1234 if addr_read_limit < read_pos + 1 + 6 {
1235 return Err(DecodeError::BadLengthDescriptor);
1237 let mut addr = [0; 4];
1238 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1239 addresses.push(NetAddress::IPv4 {
1241 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1246 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1247 return Err(DecodeError::ExtraAddressesPerType);
1249 if addr_read_limit < read_pos + 1 + 18 {
1250 return Err(DecodeError::BadLengthDescriptor);
1252 let mut addr = [0; 16];
1253 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1254 addresses.push(NetAddress::IPv6 {
1256 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1261 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1262 return Err(DecodeError::ExtraAddressesPerType);
1264 if addr_read_limit < read_pos + 1 + 12 {
1265 return Err(DecodeError::BadLengthDescriptor);
1267 let mut addr = [0; 10];
1268 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1269 addresses.push(NetAddress::OnionV2 {
1271 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1276 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1277 return Err(DecodeError::ExtraAddressesPerType);
1279 if addr_read_limit < read_pos + 1 + 37 {
1280 return Err(DecodeError::BadLengthDescriptor);
1282 let mut ed25519_pubkey = [0; 32];
1283 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1284 addresses.push(NetAddress::OnionV3 {
1286 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1287 version: v[read_pos + 35],
1288 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1292 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1296 let excess_address_data = if read_pos < addr_read_limit {
1297 let mut excess_address_data = Vec::with_capacity(addr_read_limit - read_pos);
1298 excess_address_data.extend_from_slice(&v[read_pos..addr_read_limit]);
1300 } else { Vec::new() };
1302 let mut excess_data = Vec::with_capacity(v.len() - addr_read_limit);
1303 excess_data.extend_from_slice(&v[addr_read_limit..]);
1305 let secp_ctx = Secp256k1::without_caps();
1308 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1309 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1313 excess_address_data,
1318 impl MsgEncodable for UnsignedNodeAnnouncement {
1319 fn encode(&self) -> Vec<u8> {
1320 let features = self.features.encode();
1321 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len()*7 + self.excess_address_data.len() + self.excess_data.len());
1322 res.extend_from_slice(&features[..]);
1323 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1324 res.extend_from_slice(&self.node_id.serialize());
1325 res.extend_from_slice(&self.rgb);
1326 res.extend_from_slice(&self.alias);
1327 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1328 let mut addrs_to_encode = self.addresses.clone();
1329 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1330 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1331 for addr in addrs_to_encode.iter() {
1333 &NetAddress::IPv4{addr, port} => {
1335 addr_slice.extend_from_slice(&addr);
1336 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1338 &NetAddress::IPv6{addr, port} => {
1340 addr_slice.extend_from_slice(&addr);
1341 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1343 &NetAddress::OnionV2{addr, port} => {
1345 addr_slice.extend_from_slice(&addr);
1346 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1348 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1350 addr_slice.extend_from_slice(&ed25519_pubkey);
1351 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1352 addr_slice.push(version);
1353 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1357 res.extend_from_slice(&byte_utils::be16_to_array((addr_slice.len() + self.excess_address_data.len()) as u16));
1358 res.extend_from_slice(&addr_slice[..]);
1359 res.extend_from_slice(&self.excess_address_data[..]);
1360 res.extend_from_slice(&self.excess_data[..]);
1365 impl MsgDecodable for NodeAnnouncement {
1366 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1368 return Err(DecodeError::ShortRead);
1370 let secp_ctx = Secp256k1::without_caps();
1372 signature: secp_signature!(&secp_ctx, &v[0..64]),
1373 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1377 impl MsgEncodable for NodeAnnouncement {
1378 fn encode(&self) -> Vec<u8> {
1379 let contents = self.contents.encode();
1380 let mut res = Vec::with_capacity(64 + contents.len());
1381 let secp_ctx = Secp256k1::without_caps();
1382 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1383 res.extend_from_slice(&contents);
1388 impl MsgDecodable for UnsignedChannelAnnouncement {
1389 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1390 let features = GlobalFeatures::decode(&v[..])?;
1391 if features.requires_unknown_bits() {
1392 return Err(DecodeError::UnknownRequiredFeature);
1394 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1395 return Err(DecodeError::ShortRead);
1397 let start = features.encoded_len();
1398 let secp_ctx = Secp256k1::without_caps();
1399 let mut excess_data = Vec::with_capacity(v.len() - start - 172);
1400 excess_data.extend_from_slice(&v[start + 172..]);
1403 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1404 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1405 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1406 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1407 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1408 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1413 impl MsgEncodable for UnsignedChannelAnnouncement {
1414 fn encode(&self) -> Vec<u8> {
1415 let features = self.features.encode();
1416 let mut res = Vec::with_capacity(172 + features.len() + self.excess_data.len());
1417 res.extend_from_slice(&features[..]);
1418 res.extend_from_slice(&self.chain_hash[..]);
1419 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1420 res.extend_from_slice(&self.node_id_1.serialize());
1421 res.extend_from_slice(&self.node_id_2.serialize());
1422 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1423 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1424 res.extend_from_slice(&self.excess_data[..]);
1429 impl MsgDecodable for ChannelAnnouncement {
1430 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1432 return Err(DecodeError::ShortRead);
1434 let secp_ctx = Secp256k1::without_caps();
1436 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1437 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1438 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1439 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1440 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1444 impl MsgEncodable for ChannelAnnouncement {
1445 fn encode(&self) -> Vec<u8> {
1446 let secp_ctx = Secp256k1::without_caps();
1447 let contents = self.contents.encode();
1448 let mut res = Vec::with_capacity(64 + contents.len());
1449 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1450 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1451 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1452 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1453 res.extend_from_slice(&contents);
1458 impl MsgDecodable for UnsignedChannelUpdate {
1459 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1460 if v.len() < 32+8+4+2+2+8+4+4 {
1461 return Err(DecodeError::ShortRead);
1463 let mut excess_data = Vec::with_capacity(v.len() - 64);
1464 excess_data.extend_from_slice(&v[64..]);
1466 chain_hash: deserialize(&v[0..32]).unwrap(),
1467 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1468 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1469 flags: byte_utils::slice_to_be16(&v[44..46]),
1470 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1471 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1472 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1473 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1478 impl MsgEncodable for UnsignedChannelUpdate {
1479 fn encode(&self) -> Vec<u8> {
1480 let mut res = Vec::with_capacity(64 + self.excess_data.len());
1481 res.extend_from_slice(&self.chain_hash[..]);
1482 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1483 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1484 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1485 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1486 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1487 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1488 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1489 res.extend_from_slice(&self.excess_data[..]);
1494 impl MsgDecodable for ChannelUpdate {
1495 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1497 return Err(DecodeError::ShortRead);
1499 let secp_ctx = Secp256k1::without_caps();
1501 signature: secp_signature!(&secp_ctx, &v[0..64]),
1502 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1506 impl MsgEncodable for ChannelUpdate {
1507 fn encode(&self) -> Vec<u8> {
1508 let mut res = Vec::with_capacity(128);
1509 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1510 res.extend_from_slice(&self.contents.encode()[..]);
1515 impl MsgDecodable for OnionRealm0HopData {
1516 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1518 return Err(DecodeError::ShortRead);
1520 Ok(OnionRealm0HopData {
1521 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1522 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1523 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1527 impl MsgEncodable for OnionRealm0HopData {
1528 fn encode(&self) -> Vec<u8> {
1529 let mut res = Vec::with_capacity(32);
1530 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1531 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1532 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1538 impl MsgDecodable for OnionHopData {
1539 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1541 return Err(DecodeError::ShortRead);
1545 return Err(DecodeError::UnknownRealmByte);
1547 let mut hmac = [0; 32];
1548 hmac[..].copy_from_slice(&v[33..65]);
1551 data: OnionRealm0HopData::decode(&v[1..33])?,
1556 impl MsgEncodable for OnionHopData {
1557 fn encode(&self) -> Vec<u8> {
1558 let mut res = Vec::with_capacity(65);
1559 res.push(self.realm);
1560 res.extend_from_slice(&self.data.encode()[..]);
1561 res.extend_from_slice(&self.hmac);
1566 impl MsgDecodable for OnionPacket {
1567 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1568 if v.len() < 1+33+20*65+32 {
1569 return Err(DecodeError::ShortRead);
1571 let mut hop_data = [0; 20*65];
1572 hop_data.copy_from_slice(&v[34..1334]);
1573 let mut hmac = [0; 32];
1574 hmac.copy_from_slice(&v[1334..1366]);
1575 let secp_ctx = Secp256k1::without_caps();
1578 public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1584 impl MsgEncodable for OnionPacket {
1585 fn encode(&self) -> Vec<u8> {
1586 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1587 res.push(self.version);
1588 match self.public_key {
1589 Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1590 Err(_) => res.extend_from_slice(&[0; 33]),
1592 res.extend_from_slice(&self.hop_data);
1593 res.extend_from_slice(&self.hmac);
1598 impl MsgDecodable for DecodedOnionErrorPacket {
1599 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1600 if v.len() < 32 + 4 {
1601 return Err(DecodeError::ShortRead);
1603 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1604 if v.len() < 32 + 4 + failuremsg_len {
1605 return Err(DecodeError::ShortRead);
1607 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1608 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1609 return Err(DecodeError::ShortRead);
1612 let mut hmac = [0; 32];
1613 hmac.copy_from_slice(&v[0..32]);
1616 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1617 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1621 impl MsgEncodable for DecodedOnionErrorPacket {
1622 fn encode(&self) -> Vec<u8> {
1623 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1624 res.extend_from_slice(&self.hmac);
1625 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1626 res.extend_from_slice(&self.failuremsg);
1627 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1628 res.extend_from_slice(&self.pad);
1633 impl MsgDecodable for OnionErrorPacket {
1634 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1636 return Err(DecodeError::ShortRead);
1638 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1639 if v.len() < 2 + len {
1640 return Err(DecodeError::ShortRead);
1643 data: v[2..len+2].to_vec(),
1647 impl MsgEncodable for OnionErrorPacket {
1648 fn encode(&self) -> Vec<u8> {
1649 let mut res = Vec::with_capacity(2 + self.data.len());
1650 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1651 res.extend_from_slice(&self.data);
1656 impl MsgEncodable for ErrorMessage {
1657 fn encode(&self) -> Vec<u8> {
1658 let mut res = Vec::with_capacity(34 + self.data.len());
1659 res.extend_from_slice(&self.channel_id);
1660 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1661 res.extend_from_slice(&self.data.as_bytes());
1665 impl MsgDecodable for ErrorMessage {
1666 fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1668 return Err(DecodeError::ShortRead);
1670 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1671 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1672 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1674 Err(_) => return Err(DecodeError::BadText),
1676 let mut channel_id = [0; 32];
1677 channel_id[..].copy_from_slice(&v[0..32]);
1688 use ln::msgs::MsgEncodable;
1690 use secp256k1::key::{PublicKey,SecretKey};
1691 use secp256k1::Secp256k1;
1694 fn encoding_channel_reestablish_no_secret() {
1695 let cr = msgs::ChannelReestablish {
1696 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1697 next_local_commitment_number: 3,
1698 next_remote_commitment_number: 4,
1699 data_loss_protect: None,
1702 let encoded_value = cr.encode();
1705 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4]
1710 fn encoding_channel_reestablish_with_secret() {
1712 let secp_ctx = Secp256k1::new();
1713 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1716 let cr = msgs::ChannelReestablish {
1717 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1718 next_local_commitment_number: 3,
1719 next_remote_commitment_number: 4,
1720 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1723 let encoded_value = cr.encode();
1726 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143]