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()));
686 chain_hash: deserialize(&v[0..32]).unwrap(),
687 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
688 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
689 push_msat: byte_utils::slice_to_be64(&v[72..80]),
690 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
691 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
692 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
693 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
694 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
695 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
696 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
697 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
698 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
699 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
700 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
701 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
702 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
703 channel_flags: v[318],
704 shutdown_scriptpubkey: shutdown_scriptpubkey
708 impl MsgEncodable for OpenChannel {
709 fn encode(&self) -> Vec<u8> {
710 let mut res = match &self.shutdown_scriptpubkey {
711 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
712 &None => Vec::with_capacity(319),
714 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
715 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
716 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
717 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
718 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
719 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
720 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
721 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
722 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
723 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
724 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
725 res.extend_from_slice(&self.funding_pubkey.serialize());
726 res.extend_from_slice(&self.revocation_basepoint.serialize());
727 res.extend_from_slice(&self.payment_basepoint.serialize());
728 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
729 res.extend_from_slice(&self.htlc_basepoint.serialize());
730 res.extend_from_slice(&self.first_per_commitment_point.serialize());
731 res.push(self.channel_flags);
732 if let &Some(ref script) = &self.shutdown_scriptpubkey {
733 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
734 res.extend_from_slice(&script[..]);
740 impl MsgDecodable for AcceptChannel {
741 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
742 if v.len() < 32+4*8+4+2*2+6*33 {
743 return Err(DecodeError::ShortRead);
745 let ctx = Secp256k1::without_caps();
747 let mut shutdown_scriptpubkey = None;
749 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
750 if v.len() < 272+len {
751 return Err(DecodeError::ShortRead);
753 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
756 let mut temporary_channel_id = [0; 32];
757 temporary_channel_id[..].copy_from_slice(&v[0..32]);
759 temporary_channel_id,
760 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
761 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
762 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
763 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
764 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
765 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
766 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
767 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
768 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
769 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
770 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
771 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
772 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
773 shutdown_scriptpubkey: shutdown_scriptpubkey
777 impl MsgEncodable for AcceptChannel {
778 fn encode(&self) -> Vec<u8> {
779 let mut res = match &self.shutdown_scriptpubkey {
780 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
781 &None => Vec::with_capacity(270),
783 res.extend_from_slice(&self.temporary_channel_id);
784 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
785 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
786 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
787 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
788 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
789 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
790 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
791 res.extend_from_slice(&self.funding_pubkey.serialize());
792 res.extend_from_slice(&self.revocation_basepoint.serialize());
793 res.extend_from_slice(&self.payment_basepoint.serialize());
794 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
795 res.extend_from_slice(&self.htlc_basepoint.serialize());
796 res.extend_from_slice(&self.first_per_commitment_point.serialize());
797 if let &Some(ref script) = &self.shutdown_scriptpubkey {
798 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
799 res.extend_from_slice(&script[..]);
805 impl MsgDecodable for FundingCreated {
806 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
807 if v.len() < 32+32+2+64 {
808 return Err(DecodeError::ShortRead);
810 let ctx = Secp256k1::without_caps();
811 let mut temporary_channel_id = [0; 32];
812 temporary_channel_id[..].copy_from_slice(&v[0..32]);
814 temporary_channel_id,
815 funding_txid: deserialize(&v[32..64]).unwrap(),
816 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
817 signature: secp_signature!(&ctx, &v[66..130]),
821 impl MsgEncodable for FundingCreated {
822 fn encode(&self) -> Vec<u8> {
823 let mut res = Vec::with_capacity(32+32+2+64);
824 res.extend_from_slice(&self.temporary_channel_id);
825 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
826 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
827 let secp_ctx = Secp256k1::without_caps();
828 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
833 impl MsgDecodable for FundingSigned {
834 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
836 return Err(DecodeError::ShortRead);
838 let ctx = Secp256k1::without_caps();
839 let mut channel_id = [0; 32];
840 channel_id[..].copy_from_slice(&v[0..32]);
843 signature: secp_signature!(&ctx, &v[32..96]),
847 impl MsgEncodable for FundingSigned {
848 fn encode(&self) -> Vec<u8> {
849 let mut res = Vec::with_capacity(32+64);
850 res.extend_from_slice(&self.channel_id);
851 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
856 impl MsgDecodable for FundingLocked {
857 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
859 return Err(DecodeError::ShortRead);
861 let ctx = Secp256k1::without_caps();
862 let mut channel_id = [0; 32];
863 channel_id[..].copy_from_slice(&v[0..32]);
866 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
870 impl MsgEncodable for FundingLocked {
871 fn encode(&self) -> Vec<u8> {
872 let mut res = Vec::with_capacity(32+33);
873 res.extend_from_slice(&self.channel_id);
874 res.extend_from_slice(&self.next_per_commitment_point.serialize());
879 impl MsgDecodable for Shutdown {
880 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
881 if v.len() < 32 + 2 {
882 return Err(DecodeError::ShortRead);
884 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
885 if v.len() < 32 + 2 + scriptlen {
886 return Err(DecodeError::ShortRead);
888 let mut channel_id = [0; 32];
889 channel_id[..].copy_from_slice(&v[0..32]);
892 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
896 impl MsgEncodable for Shutdown {
897 fn encode(&self) -> Vec<u8> {
898 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
899 res.extend_from_slice(&self.channel_id);
900 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
901 res.extend_from_slice(&self.scriptpubkey[..]);
906 impl MsgDecodable for ClosingSigned {
907 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
908 if v.len() < 32 + 8 + 64 {
909 return Err(DecodeError::ShortRead);
911 let secp_ctx = Secp256k1::without_caps();
912 let mut channel_id = [0; 32];
913 channel_id[..].copy_from_slice(&v[0..32]);
916 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
917 signature: secp_signature!(&secp_ctx, &v[40..104]),
921 impl MsgEncodable for ClosingSigned {
922 fn encode(&self) -> Vec<u8> {
923 let mut res = Vec::with_capacity(32+8+64);
924 res.extend_from_slice(&self.channel_id);
925 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
926 let secp_ctx = Secp256k1::without_caps();
927 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
932 impl MsgDecodable for UpdateAddHTLC {
933 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
934 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
935 return Err(DecodeError::ShortRead);
937 let mut channel_id = [0; 32];
938 channel_id[..].copy_from_slice(&v[0..32]);
939 let mut payment_hash = [0; 32];
940 payment_hash.copy_from_slice(&v[48..80]);
943 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
944 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
946 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
947 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
951 impl MsgEncodable for UpdateAddHTLC {
952 fn encode(&self) -> Vec<u8> {
953 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
954 res.extend_from_slice(&self.channel_id);
955 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
956 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
957 res.extend_from_slice(&self.payment_hash);
958 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
959 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
964 impl MsgDecodable for UpdateFulfillHTLC {
965 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
966 if v.len() < 32+8+32 {
967 return Err(DecodeError::ShortRead);
969 let mut channel_id = [0; 32];
970 channel_id[..].copy_from_slice(&v[0..32]);
971 let mut payment_preimage = [0; 32];
972 payment_preimage.copy_from_slice(&v[40..72]);
975 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
980 impl MsgEncodable for UpdateFulfillHTLC {
981 fn encode(&self) -> Vec<u8> {
982 let mut res = Vec::with_capacity(32+8+32);
983 res.extend_from_slice(&self.channel_id);
984 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
985 res.extend_from_slice(&self.payment_preimage);
990 impl MsgDecodable for UpdateFailHTLC {
991 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
993 return Err(DecodeError::ShortRead);
995 let mut channel_id = [0; 32];
996 channel_id[..].copy_from_slice(&v[0..32]);
999 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1000 reason: OnionErrorPacket::decode(&v[40..])?,
1004 impl MsgEncodable for UpdateFailHTLC {
1005 fn encode(&self) -> Vec<u8> {
1006 let reason = self.reason.encode();
1007 let mut res = Vec::with_capacity(32+8+reason.len());
1008 res.extend_from_slice(&self.channel_id);
1009 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1010 res.extend_from_slice(&reason[..]);
1015 impl MsgDecodable for UpdateFailMalformedHTLC {
1016 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1017 if v.len() < 32+8+32+2 {
1018 return Err(DecodeError::ShortRead);
1020 let mut channel_id = [0; 32];
1021 channel_id[..].copy_from_slice(&v[0..32]);
1022 let mut sha256_of_onion = [0; 32];
1023 sha256_of_onion.copy_from_slice(&v[40..72]);
1026 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1028 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1032 impl MsgEncodable for UpdateFailMalformedHTLC {
1033 fn encode(&self) -> Vec<u8> {
1034 let mut res = Vec::with_capacity(32+8+32+2);
1035 res.extend_from_slice(&self.channel_id);
1036 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1037 res.extend_from_slice(&self.sha256_of_onion);
1038 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1043 impl MsgDecodable for CommitmentSigned {
1044 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1045 if v.len() < 32+64+2 {
1046 return Err(DecodeError::ShortRead);
1048 let mut channel_id = [0; 32];
1049 channel_id[..].copy_from_slice(&v[0..32]);
1051 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1052 if v.len() < 32+64+2+htlcs*64 {
1053 return Err(DecodeError::ShortRead);
1055 let mut htlc_signatures = Vec::with_capacity(htlcs);
1056 let secp_ctx = Secp256k1::without_caps();
1058 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1062 signature: secp_signature!(&secp_ctx, &v[32..96]),
1067 impl MsgEncodable for CommitmentSigned {
1068 fn encode(&self) -> Vec<u8> {
1069 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1070 res.extend_from_slice(&self.channel_id);
1071 let secp_ctx = Secp256k1::without_caps();
1072 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1073 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1074 for i in 0..self.htlc_signatures.len() {
1075 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1081 impl MsgDecodable for RevokeAndACK {
1082 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1083 if v.len() < 32+32+33 {
1084 return Err(DecodeError::ShortRead);
1086 let mut channel_id = [0; 32];
1087 channel_id[..].copy_from_slice(&v[0..32]);
1088 let mut per_commitment_secret = [0; 32];
1089 per_commitment_secret.copy_from_slice(&v[32..64]);
1090 let secp_ctx = Secp256k1::without_caps();
1093 per_commitment_secret,
1094 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1098 impl MsgEncodable for RevokeAndACK {
1099 fn encode(&self) -> Vec<u8> {
1100 let mut res = Vec::with_capacity(32+32+33);
1101 res.extend_from_slice(&self.channel_id);
1102 res.extend_from_slice(&self.per_commitment_secret);
1103 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1108 impl MsgDecodable for UpdateFee {
1109 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1111 return Err(DecodeError::ShortRead);
1113 let mut channel_id = [0; 32];
1114 channel_id[..].copy_from_slice(&v[0..32]);
1117 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1121 impl MsgEncodable for UpdateFee {
1122 fn encode(&self) -> Vec<u8> {
1123 let mut res = Vec::with_capacity(32+4);
1124 res.extend_from_slice(&self.channel_id);
1125 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1130 impl MsgDecodable for ChannelReestablish {
1131 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1132 if v.len() < 32+2*8 {
1133 return Err(DecodeError::ShortRead);
1136 let data_loss_protect = if v.len() > 32+2*8 {
1137 if v.len() < 32+2*8 + 33+32 {
1138 return Err(DecodeError::ShortRead);
1140 let mut inner_array = [0; 32];
1141 inner_array.copy_from_slice(&v[48..48+32]);
1142 Some(DataLossProtect {
1143 your_last_per_commitment_secret: inner_array,
1144 my_current_per_commitment_point: secp_pubkey!(&Secp256k1::without_caps(), &v[48+32..48+32+33]),
1149 channel_id: deserialize(&v[0..32]).unwrap(),
1150 next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1151 next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1152 data_loss_protect: data_loss_protect,
1156 impl MsgEncodable for ChannelReestablish {
1157 fn encode(&self) -> Vec<u8> {
1158 let mut res = Vec::with_capacity(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
1160 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1161 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1162 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1164 if let &Some(ref data_loss_protect) = &self.data_loss_protect {
1165 res.extend_from_slice(&data_loss_protect.your_last_per_commitment_secret[..]);
1166 res.extend_from_slice(&data_loss_protect.my_current_per_commitment_point.serialize());
1172 impl MsgDecodable for AnnouncementSignatures {
1173 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1174 if v.len() < 32+8+64*2 {
1175 return Err(DecodeError::ShortRead);
1177 let secp_ctx = Secp256k1::without_caps();
1178 let mut channel_id = [0; 32];
1179 channel_id[..].copy_from_slice(&v[0..32]);
1182 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1183 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1184 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1188 impl MsgEncodable for AnnouncementSignatures {
1189 fn encode(&self) -> Vec<u8> {
1190 let mut res = Vec::with_capacity(32+8+64*2);
1191 res.extend_from_slice(&self.channel_id);
1192 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1193 let secp_ctx = Secp256k1::without_caps();
1194 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1195 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1200 impl MsgDecodable for UnsignedNodeAnnouncement {
1201 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1202 let features = GlobalFeatures::decode(&v[..])?;
1203 if features.requires_unknown_bits() {
1204 return Err(DecodeError::UnknownRequiredFeature);
1207 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1208 return Err(DecodeError::ShortRead);
1210 let start = features.encoded_len();
1212 let mut rgb = [0; 3];
1213 rgb.copy_from_slice(&v[start + 37..start + 40]);
1215 let mut alias = [0; 32];
1216 alias.copy_from_slice(&v[start + 40..start + 72]);
1218 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1219 if v.len() < start + 74 + addrlen {
1220 return Err(DecodeError::ShortRead);
1222 let addr_read_limit = start + 74 + addrlen;
1224 let mut addresses = Vec::with_capacity(4);
1225 let mut read_pos = start + 74;
1227 if addr_read_limit <= read_pos { break; }
1230 if addresses.len() > 0 {
1231 return Err(DecodeError::ExtraAddressesPerType);
1233 if addr_read_limit < read_pos + 1 + 6 {
1234 return Err(DecodeError::BadLengthDescriptor);
1236 let mut addr = [0; 4];
1237 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1238 addresses.push(NetAddress::IPv4 {
1240 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1245 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1246 return Err(DecodeError::ExtraAddressesPerType);
1248 if addr_read_limit < read_pos + 1 + 18 {
1249 return Err(DecodeError::BadLengthDescriptor);
1251 let mut addr = [0; 16];
1252 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1253 addresses.push(NetAddress::IPv6 {
1255 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1260 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1261 return Err(DecodeError::ExtraAddressesPerType);
1263 if addr_read_limit < read_pos + 1 + 12 {
1264 return Err(DecodeError::BadLengthDescriptor);
1266 let mut addr = [0; 10];
1267 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1268 addresses.push(NetAddress::OnionV2 {
1270 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1275 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1276 return Err(DecodeError::ExtraAddressesPerType);
1278 if addr_read_limit < read_pos + 1 + 37 {
1279 return Err(DecodeError::BadLengthDescriptor);
1281 let mut ed25519_pubkey = [0; 32];
1282 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1283 addresses.push(NetAddress::OnionV3 {
1285 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1286 version: v[read_pos + 35],
1287 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1291 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1295 let excess_address_data = if read_pos < addr_read_limit {
1296 let mut excess_address_data = Vec::with_capacity(addr_read_limit - read_pos);
1297 excess_address_data.extend_from_slice(&v[read_pos..addr_read_limit]);
1299 } else { Vec::new() };
1301 let mut excess_data = Vec::with_capacity(v.len() - addr_read_limit);
1302 excess_data.extend_from_slice(&v[addr_read_limit..]);
1304 let secp_ctx = Secp256k1::without_caps();
1307 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1308 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1312 excess_address_data,
1317 impl MsgEncodable for UnsignedNodeAnnouncement {
1318 fn encode(&self) -> Vec<u8> {
1319 let features = self.features.encode();
1320 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len()*7 + self.excess_address_data.len() + self.excess_data.len());
1321 res.extend_from_slice(&features[..]);
1322 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1323 res.extend_from_slice(&self.node_id.serialize());
1324 res.extend_from_slice(&self.rgb);
1325 res.extend_from_slice(&self.alias);
1326 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1327 let mut addrs_to_encode = self.addresses.clone();
1328 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1329 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1330 for addr in addrs_to_encode.iter() {
1332 &NetAddress::IPv4{addr, port} => {
1334 addr_slice.extend_from_slice(&addr);
1335 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1337 &NetAddress::IPv6{addr, port} => {
1339 addr_slice.extend_from_slice(&addr);
1340 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1342 &NetAddress::OnionV2{addr, port} => {
1344 addr_slice.extend_from_slice(&addr);
1345 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1347 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1349 addr_slice.extend_from_slice(&ed25519_pubkey);
1350 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1351 addr_slice.push(version);
1352 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1356 res.extend_from_slice(&byte_utils::be16_to_array((addr_slice.len() + self.excess_address_data.len()) as u16));
1357 res.extend_from_slice(&addr_slice[..]);
1358 res.extend_from_slice(&self.excess_address_data[..]);
1359 res.extend_from_slice(&self.excess_data[..]);
1364 impl MsgDecodable for NodeAnnouncement {
1365 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1367 return Err(DecodeError::ShortRead);
1369 let secp_ctx = Secp256k1::without_caps();
1371 signature: secp_signature!(&secp_ctx, &v[0..64]),
1372 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1376 impl MsgEncodable for NodeAnnouncement {
1377 fn encode(&self) -> Vec<u8> {
1378 let contents = self.contents.encode();
1379 let mut res = Vec::with_capacity(64 + contents.len());
1380 let secp_ctx = Secp256k1::without_caps();
1381 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1382 res.extend_from_slice(&contents);
1387 impl MsgDecodable for UnsignedChannelAnnouncement {
1388 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1389 let features = GlobalFeatures::decode(&v[..])?;
1390 if features.requires_unknown_bits() {
1391 return Err(DecodeError::UnknownRequiredFeature);
1393 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1394 return Err(DecodeError::ShortRead);
1396 let start = features.encoded_len();
1397 let secp_ctx = Secp256k1::without_caps();
1398 let mut excess_data = Vec::with_capacity(v.len() - start - 172);
1399 excess_data.extend_from_slice(&v[start + 172..]);
1402 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1403 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1404 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1405 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1406 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1407 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1412 impl MsgEncodable for UnsignedChannelAnnouncement {
1413 fn encode(&self) -> Vec<u8> {
1414 let features = self.features.encode();
1415 let mut res = Vec::with_capacity(172 + features.len() + self.excess_data.len());
1416 res.extend_from_slice(&features[..]);
1417 res.extend_from_slice(&self.chain_hash[..]);
1418 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1419 res.extend_from_slice(&self.node_id_1.serialize());
1420 res.extend_from_slice(&self.node_id_2.serialize());
1421 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1422 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1423 res.extend_from_slice(&self.excess_data[..]);
1428 impl MsgDecodable for ChannelAnnouncement {
1429 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1431 return Err(DecodeError::ShortRead);
1433 let secp_ctx = Secp256k1::without_caps();
1435 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1436 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1437 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1438 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1439 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1443 impl MsgEncodable for ChannelAnnouncement {
1444 fn encode(&self) -> Vec<u8> {
1445 let secp_ctx = Secp256k1::without_caps();
1446 let contents = self.contents.encode();
1447 let mut res = Vec::with_capacity(64 + contents.len());
1448 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1449 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1450 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1451 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1452 res.extend_from_slice(&contents);
1457 impl MsgDecodable for UnsignedChannelUpdate {
1458 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1459 if v.len() < 32+8+4+2+2+8+4+4 {
1460 return Err(DecodeError::ShortRead);
1462 let mut excess_data = Vec::with_capacity(v.len() - 64);
1463 excess_data.extend_from_slice(&v[64..]);
1465 chain_hash: deserialize(&v[0..32]).unwrap(),
1466 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1467 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1468 flags: byte_utils::slice_to_be16(&v[44..46]),
1469 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1470 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1471 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1472 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1477 impl MsgEncodable for UnsignedChannelUpdate {
1478 fn encode(&self) -> Vec<u8> {
1479 let mut res = Vec::with_capacity(64 + self.excess_data.len());
1480 res.extend_from_slice(&self.chain_hash[..]);
1481 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1482 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1483 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1484 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1485 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1486 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1487 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1488 res.extend_from_slice(&self.excess_data[..]);
1493 impl MsgDecodable for ChannelUpdate {
1494 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1496 return Err(DecodeError::ShortRead);
1498 let secp_ctx = Secp256k1::without_caps();
1500 signature: secp_signature!(&secp_ctx, &v[0..64]),
1501 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1505 impl MsgEncodable for ChannelUpdate {
1506 fn encode(&self) -> Vec<u8> {
1507 let mut res = Vec::with_capacity(128);
1508 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1509 res.extend_from_slice(&self.contents.encode()[..]);
1514 impl MsgDecodable for OnionRealm0HopData {
1515 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1517 return Err(DecodeError::ShortRead);
1519 Ok(OnionRealm0HopData {
1520 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1521 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1522 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1526 impl MsgEncodable for OnionRealm0HopData {
1527 fn encode(&self) -> Vec<u8> {
1528 let mut res = Vec::with_capacity(32);
1529 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1530 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1531 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1537 impl MsgDecodable for OnionHopData {
1538 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1540 return Err(DecodeError::ShortRead);
1544 return Err(DecodeError::UnknownRealmByte);
1546 let mut hmac = [0; 32];
1547 hmac[..].copy_from_slice(&v[33..65]);
1550 data: OnionRealm0HopData::decode(&v[1..33])?,
1555 impl MsgEncodable for OnionHopData {
1556 fn encode(&self) -> Vec<u8> {
1557 let mut res = Vec::with_capacity(65);
1558 res.push(self.realm);
1559 res.extend_from_slice(&self.data.encode()[..]);
1560 res.extend_from_slice(&self.hmac);
1565 impl MsgDecodable for OnionPacket {
1566 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1567 if v.len() < 1+33+20*65+32 {
1568 return Err(DecodeError::ShortRead);
1570 let mut hop_data = [0; 20*65];
1571 hop_data.copy_from_slice(&v[34..1334]);
1572 let mut hmac = [0; 32];
1573 hmac.copy_from_slice(&v[1334..1366]);
1574 let secp_ctx = Secp256k1::without_caps();
1577 public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1583 impl MsgEncodable for OnionPacket {
1584 fn encode(&self) -> Vec<u8> {
1585 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1586 res.push(self.version);
1587 match self.public_key {
1588 Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1589 Err(_) => res.extend_from_slice(&[0; 33]),
1591 res.extend_from_slice(&self.hop_data);
1592 res.extend_from_slice(&self.hmac);
1597 impl MsgDecodable for DecodedOnionErrorPacket {
1598 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1599 if v.len() < 32 + 4 {
1600 return Err(DecodeError::ShortRead);
1602 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1603 if v.len() < 32 + 4 + failuremsg_len {
1604 return Err(DecodeError::ShortRead);
1606 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1607 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1608 return Err(DecodeError::ShortRead);
1611 let mut hmac = [0; 32];
1612 hmac.copy_from_slice(&v[0..32]);
1615 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1616 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1620 impl MsgEncodable for DecodedOnionErrorPacket {
1621 fn encode(&self) -> Vec<u8> {
1622 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1623 res.extend_from_slice(&self.hmac);
1624 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1625 res.extend_from_slice(&self.failuremsg);
1626 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1627 res.extend_from_slice(&self.pad);
1632 impl MsgDecodable for OnionErrorPacket {
1633 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1635 return Err(DecodeError::ShortRead);
1637 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1638 if v.len() < 2 + len {
1639 return Err(DecodeError::ShortRead);
1642 data: v[2..len+2].to_vec(),
1646 impl MsgEncodable for OnionErrorPacket {
1647 fn encode(&self) -> Vec<u8> {
1648 let mut res = Vec::with_capacity(2 + self.data.len());
1649 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1650 res.extend_from_slice(&self.data);
1655 impl MsgEncodable for ErrorMessage {
1656 fn encode(&self) -> Vec<u8> {
1657 let mut res = Vec::with_capacity(34 + self.data.len());
1658 res.extend_from_slice(&self.channel_id);
1659 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1660 res.extend_from_slice(&self.data.as_bytes());
1664 impl MsgDecodable for ErrorMessage {
1665 fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1667 return Err(DecodeError::ShortRead);
1669 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1670 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1671 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1673 Err(_) => return Err(DecodeError::BadText),
1675 let mut channel_id = [0; 32];
1676 channel_id[..].copy_from_slice(&v[0..32]);
1687 use ln::msgs::MsgEncodable;
1689 use secp256k1::key::{PublicKey,SecretKey};
1690 use secp256k1::Secp256k1;
1693 fn encoding_channel_reestablish_no_secret() {
1694 let cr = msgs::ChannelReestablish {
1695 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],
1696 next_local_commitment_number: 3,
1697 next_remote_commitment_number: 4,
1698 data_loss_protect: None,
1701 let encoded_value = cr.encode();
1704 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]
1709 fn encoding_channel_reestablish_with_secret() {
1711 let secp_ctx = Secp256k1::new();
1712 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1715 let cr = msgs::ChannelReestablish {
1716 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],
1717 next_local_commitment_number: 3,
1718 next_remote_commitment_number: 4,
1719 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1722 let encoded_value = cr.encode();
1725 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]