1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use bitcoin::util::uint::Uint256;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::{deserialize,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 /// Failed to decode a public key (ie it's invalid)
33 /// Failed to decode a signature (ie it's invalid)
35 /// Buffer not of right length (either too short or too long)
37 /// node_announcement included more than one address of a given type!
38 ExtraAddressesPerType,
40 pub trait MsgDecodable: Sized {
41 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
44 /// Tracks localfeatures which are only in init messages
45 #[derive(Clone, PartialEq)]
46 pub struct LocalFeatures {
51 pub fn new() -> LocalFeatures {
57 pub fn supports_data_loss_protect(&self) -> bool {
58 self.flags.len() > 0 && (self.flags[0] & 3) != 0
60 pub fn requires_data_loss_protect(&self) -> bool {
61 self.flags.len() > 0 && (self.flags[0] & 1) != 0
64 pub fn initial_routing_sync(&self) -> bool {
65 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
67 pub fn set_initial_routing_sync(&mut self) {
68 if self.flags.len() == 0 {
69 self.flags.resize(1, 1 << 3);
71 self.flags[0] |= 1 << 3;
75 pub fn supports_upfront_shutdown_script(&self) -> bool {
76 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
78 pub fn requires_upfront_shutdown_script(&self) -> bool {
79 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
82 pub fn requires_unknown_bits(&self) -> bool {
83 for (idx, &byte) in self.flags.iter().enumerate() {
84 if idx != 0 && (byte & 0x55) != 0 {
86 } else if idx == 0 && (byte & 0x14) != 0 {
93 pub fn supports_unknown_bits(&self) -> bool {
94 for (idx, &byte) in self.flags.iter().enumerate() {
95 if idx != 0 && byte != 0 {
97 } else if idx == 0 && (byte & 0xc4) != 0 {
105 /// Tracks globalfeatures which are in init messages and routing announcements
106 #[derive(Clone, PartialEq)]
107 pub struct GlobalFeatures {
111 impl GlobalFeatures {
112 pub fn new() -> GlobalFeatures {
118 pub fn requires_unknown_bits(&self) -> bool {
119 for &byte in self.flags.iter() {
120 if (byte & 0x55) != 0 {
127 pub fn supports_unknown_bits(&self) -> bool {
128 for &byte in self.flags.iter() {
138 pub global_features: GlobalFeatures,
139 pub local_features: LocalFeatures,
151 pub struct OpenChannel {
152 pub chain_hash: Sha256dHash,
153 pub temporary_channel_id: Uint256,
154 pub funding_satoshis: u64,
156 pub dust_limit_satoshis: u64,
157 pub max_htlc_value_in_flight_msat: u64,
158 pub channel_reserve_satoshis: u64,
159 pub htlc_minimum_msat: u64,
160 pub feerate_per_kw: u32,
161 pub to_self_delay: u16,
162 pub max_accepted_htlcs: u16,
163 pub funding_pubkey: PublicKey,
164 pub revocation_basepoint: PublicKey,
165 pub payment_basepoint: PublicKey,
166 pub delayed_payment_basepoint: PublicKey,
167 pub htlc_basepoint: PublicKey,
168 pub first_per_commitment_point: PublicKey,
169 pub channel_flags: u8,
170 pub shutdown_scriptpubkey: Option<Script>,
173 pub struct AcceptChannel {
174 pub temporary_channel_id: Uint256,
175 pub dust_limit_satoshis: u64,
176 pub max_htlc_value_in_flight_msat: u64,
177 pub channel_reserve_satoshis: u64,
178 pub htlc_minimum_msat: u64,
179 pub minimum_depth: u32,
180 pub to_self_delay: u16,
181 pub max_accepted_htlcs: u16,
182 pub funding_pubkey: PublicKey,
183 pub revocation_basepoint: PublicKey,
184 pub payment_basepoint: PublicKey,
185 pub delayed_payment_basepoint: PublicKey,
186 pub htlc_basepoint: PublicKey,
187 pub first_per_commitment_point: PublicKey,
188 pub shutdown_scriptpubkey: Option<Script>,
191 pub struct FundingCreated {
192 pub temporary_channel_id: Uint256,
193 pub funding_txid: Sha256dHash,
194 pub funding_output_index: u16,
195 pub signature: Signature,
198 pub struct FundingSigned {
199 pub channel_id: Uint256,
200 pub signature: Signature,
203 pub struct FundingLocked {
204 pub channel_id: Uint256,
205 pub next_per_commitment_point: PublicKey,
208 pub struct Shutdown {
209 pub channel_id: Uint256,
210 pub scriptpubkey: Script,
213 pub struct ClosingSigned {
214 pub channel_id: Uint256,
215 pub fee_satoshis: u64,
216 pub signature: Signature,
220 pub struct UpdateAddHTLC {
221 pub channel_id: Uint256,
223 pub amount_msat: u64,
224 pub payment_hash: [u8; 32],
225 pub cltv_expiry: u32,
226 pub onion_routing_packet: OnionPacket,
230 pub struct UpdateFulfillHTLC {
231 pub channel_id: Uint256,
233 pub payment_preimage: [u8; 32],
237 pub struct UpdateFailHTLC {
238 pub channel_id: Uint256,
240 pub reason: OnionErrorPacket,
244 pub struct UpdateFailMalformedHTLC {
245 pub channel_id: Uint256,
247 pub sha256_of_onion: [u8; 32],
248 pub failure_code: u16,
252 pub struct CommitmentSigned {
253 pub channel_id: Uint256,
254 pub signature: Signature,
255 pub htlc_signatures: Vec<Signature>,
258 pub struct RevokeAndACK {
259 pub channel_id: Uint256,
260 pub per_commitment_secret: [u8; 32],
261 pub next_per_commitment_point: PublicKey,
264 pub struct UpdateFee {
265 pub channel_id: Uint256,
266 pub feerate_per_kw: u32,
269 pub struct ChannelReestablish {
270 pub channel_id: Uint256,
271 pub next_local_commitment_number: u64,
272 pub next_remote_commitment_number: u64,
273 pub your_last_per_commitment_secret: Option<[u8; 32]>,
274 pub my_current_per_commitment_point: PublicKey,
278 pub struct AnnouncementSignatures {
279 pub channel_id: Uint256,
280 pub short_channel_id: u64,
281 pub node_signature: Signature,
282 pub bitcoin_signature: Signature,
286 pub enum NetAddress {
300 ed25519_pubkey: [u8; 32],
307 fn get_id(&self) -> u8 {
309 &NetAddress::IPv4 {..} => { 1 },
310 &NetAddress::IPv6 {..} => { 2 },
311 &NetAddress::OnionV2 {..} => { 3 },
312 &NetAddress::OnionV3 {..} => { 4 },
317 pub struct UnsignedNodeAnnouncement {
318 pub features: GlobalFeatures,
320 pub node_id: PublicKey,
323 /// List of addresses on which this node is reachable. Note that you may only have up to one
324 /// address of each type, if you have more, they may be silently discarded or we may panic!
325 pub addresses: Vec<NetAddress>,
327 pub struct NodeAnnouncement {
328 pub signature: Signature,
329 pub contents: UnsignedNodeAnnouncement,
332 #[derive(PartialEq, Clone)]
333 pub struct UnsignedChannelAnnouncement {
334 pub features: GlobalFeatures,
335 pub chain_hash: Sha256dHash,
336 pub short_channel_id: u64,
337 pub node_id_1: PublicKey,
338 pub node_id_2: PublicKey,
339 pub bitcoin_key_1: PublicKey,
340 pub bitcoin_key_2: PublicKey,
342 #[derive(PartialEq, Clone)]
343 pub struct ChannelAnnouncement {
344 pub node_signature_1: Signature,
345 pub node_signature_2: Signature,
346 pub bitcoin_signature_1: Signature,
347 pub bitcoin_signature_2: Signature,
348 pub contents: UnsignedChannelAnnouncement,
351 #[derive(PartialEq, Clone)]
352 pub struct UnsignedChannelUpdate {
353 pub chain_hash: Sha256dHash,
354 pub short_channel_id: u64,
357 pub cltv_expiry_delta: u16,
358 pub htlc_minimum_msat: u64,
359 pub fee_base_msat: u32,
360 pub fee_proportional_millionths: u32,
362 #[derive(PartialEq, Clone)]
363 pub struct ChannelUpdate {
364 pub signature: Signature,
365 pub contents: UnsignedChannelUpdate,
368 /// Used to put an error message in a HandleError
369 pub enum ErrorAction {
370 /// Indicates an inbound HTLC add resulted in a failure, and the UpdateFailHTLC provided in msg
371 /// should be sent back to the sender.
375 /// The peer took some action which made us think they were useless. Disconnect them.
377 /// The peer did something harmless that we weren't able to process, just log and ignore
381 pub struct HandleError { //TODO: rename me
382 pub err: &'static str,
383 pub msg: Option<ErrorAction>, //TODO: Make this required and rename it
386 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
387 /// transaction updates if they were pending.
388 pub struct CommitmentUpdate {
389 pub update_add_htlcs: Vec<UpdateAddHTLC>,
390 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
391 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
392 pub commitment_signed: CommitmentSigned,
395 pub enum HTLCFailChannelUpdate {
396 ChannelUpdateMessage {
400 short_channel_id: u64,
404 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
405 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
406 /// paralell when the two calls have the same their_node_id.
407 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
409 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
410 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
411 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
412 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
413 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
416 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
417 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
420 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
421 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
422 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
423 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
424 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
425 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
427 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
429 // Channel-to-announce:
430 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
433 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
434 /// is believed to be possible in the future (eg they're sending us messages we don't
435 /// understand or indicate they require unknown feature bits), no_connection_possible is set
436 /// and any outstanding channels should be failed.
437 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
440 pub trait RoutingMessageHandler : Send + Sync {
441 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
442 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
443 /// or returning an Err otherwise.
444 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
445 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
446 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
449 pub struct OnionRealm0HopData {
450 pub short_channel_id: u64,
451 pub amt_to_forward: u64,
452 pub outgoing_cltv_value: u32,
453 // 12 bytes of 0-padding
456 pub struct OnionHopData {
458 pub data: OnionRealm0HopData,
461 unsafe impl internal_traits::NoDealloc for OnionHopData{}
464 pub struct OnionPacket {
466 pub public_key: PublicKey,
467 pub hop_data: [u8; 20*65],
471 pub struct DecodedOnionErrorPacket {
473 pub failuremsg: Vec<u8>,
478 pub struct OnionErrorPacket {
479 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
480 // (TODO) We limit it in decode to much lower...
484 impl Error for DecodeError {
485 fn description(&self) -> &str {
487 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
488 DecodeError::BadPublicKey => "Invalid public key in packet",
489 DecodeError::BadSignature => "Invalid signature in packet",
490 DecodeError::WrongLength => "Data was wrong length for packet",
491 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
495 impl fmt::Display for DecodeError {
496 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
497 f.write_str(self.description())
501 impl fmt::Debug for HandleError {
502 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
503 f.write_str(self.err)
507 macro_rules! secp_pubkey {
508 ( $ctx: expr, $slice: expr ) => {
509 match PublicKey::from_slice($ctx, $slice) {
511 Err(_) => return Err(DecodeError::BadPublicKey)
516 macro_rules! secp_signature {
517 ( $ctx: expr, $slice: expr ) => {
518 match Signature::from_compact($ctx, $slice) {
520 Err(_) => return Err(DecodeError::BadSignature)
525 impl MsgDecodable for LocalFeatures {
526 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
527 if v.len() < 2 { return Err(DecodeError::WrongLength); }
528 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
529 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
530 let mut flags = Vec::with_capacity(len);
531 flags.extend_from_slice(&v[2..2 + len]);
537 impl MsgEncodable for LocalFeatures {
538 fn encode(&self) -> Vec<u8> {
539 let mut res = Vec::with_capacity(self.flags.len() + 2);
540 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
541 res.extend_from_slice(&self.flags[..]);
544 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
547 impl MsgDecodable for GlobalFeatures {
548 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
549 if v.len() < 2 { return Err(DecodeError::WrongLength); }
550 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
551 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
552 let mut flags = Vec::with_capacity(len);
553 flags.extend_from_slice(&v[2..2 + len]);
559 impl MsgEncodable for GlobalFeatures {
560 fn encode(&self) -> Vec<u8> {
561 let mut res = Vec::with_capacity(self.flags.len() + 2);
562 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
563 res.extend_from_slice(&self.flags[..]);
566 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
569 impl MsgDecodable for Init {
570 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
571 let global_features = GlobalFeatures::decode(v)?;
572 if v.len() < global_features.flags.len() + 4 {
573 return Err(DecodeError::WrongLength);
575 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
577 global_features: global_features,
578 local_features: local_features,
582 impl MsgEncodable for Init {
583 fn encode(&self) -> Vec<u8> {
584 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
585 res.extend_from_slice(&self.global_features.encode()[..]);
586 res.extend_from_slice(&self.local_features.encode()[..]);
591 impl MsgDecodable for Ping {
592 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
594 return Err(DecodeError::WrongLength);
596 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
597 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
598 if v.len() < 4 + byteslen as usize {
599 return Err(DecodeError::WrongLength);
607 impl MsgEncodable for Ping {
608 fn encode(&self) -> Vec<u8> {
609 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
610 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
611 res.resize(2 + self.byteslen as usize, 0);
616 impl MsgDecodable for Pong {
617 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
619 return Err(DecodeError::WrongLength);
621 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
622 if v.len() < 2 + byteslen as usize {
623 return Err(DecodeError::WrongLength);
630 impl MsgEncodable for Pong {
631 fn encode(&self) -> Vec<u8> {
632 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
633 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
634 res.resize(2 + self.byteslen as usize, 0);
639 impl MsgDecodable for OpenChannel {
640 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
641 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
642 return Err(DecodeError::WrongLength);
644 let ctx = Secp256k1::without_caps();
646 let mut shutdown_scriptpubkey = None;
648 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
649 if v.len() < 321+len {
650 return Err(DecodeError::WrongLength);
652 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
653 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
654 return Err(DecodeError::WrongLength);
658 chain_hash: deserialize(&v[0..32]).unwrap(),
659 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
660 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
661 push_msat: byte_utils::slice_to_be64(&v[72..80]),
662 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
663 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
664 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
665 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
666 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
667 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
668 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
669 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
670 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
671 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
672 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
673 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
674 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
675 channel_flags: v[318],
676 shutdown_scriptpubkey: shutdown_scriptpubkey
680 impl MsgEncodable for OpenChannel {
681 fn encode(&self) -> Vec<u8> {
682 let mut res = match &self.shutdown_scriptpubkey {
683 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
684 &None => Vec::with_capacity(319),
686 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
687 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
688 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
689 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
690 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
691 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
692 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
693 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
694 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
695 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
696 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
697 res.extend_from_slice(&self.funding_pubkey.serialize());
698 res.extend_from_slice(&self.revocation_basepoint.serialize());
699 res.extend_from_slice(&self.payment_basepoint.serialize());
700 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
701 res.extend_from_slice(&self.htlc_basepoint.serialize());
702 res.extend_from_slice(&self.first_per_commitment_point.serialize());
703 res.push(self.channel_flags);
704 if let &Some(ref script) = &self.shutdown_scriptpubkey {
705 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
706 res.extend_from_slice(&script[..]);
712 impl MsgDecodable for AcceptChannel {
713 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
714 if v.len() < 32+4*8+4+2*2+6*33 {
715 return Err(DecodeError::WrongLength);
717 let ctx = Secp256k1::without_caps();
719 let mut shutdown_scriptpubkey = None;
721 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
722 if v.len() < 272+len {
723 return Err(DecodeError::WrongLength);
725 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
726 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
727 return Err(DecodeError::WrongLength);
731 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
732 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
733 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
734 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
735 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
736 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
737 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
738 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
739 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
740 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
741 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
742 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
743 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
744 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
745 shutdown_scriptpubkey: shutdown_scriptpubkey
749 impl MsgEncodable for AcceptChannel {
750 fn encode(&self) -> Vec<u8> {
751 let mut res = match &self.shutdown_scriptpubkey {
752 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
753 &None => Vec::with_capacity(270),
755 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
756 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
757 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
758 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
759 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
760 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
761 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
762 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
763 res.extend_from_slice(&self.funding_pubkey.serialize());
764 res.extend_from_slice(&self.revocation_basepoint.serialize());
765 res.extend_from_slice(&self.payment_basepoint.serialize());
766 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
767 res.extend_from_slice(&self.htlc_basepoint.serialize());
768 res.extend_from_slice(&self.first_per_commitment_point.serialize());
769 if let &Some(ref script) = &self.shutdown_scriptpubkey {
770 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
771 res.extend_from_slice(&script[..]);
777 impl MsgDecodable for FundingCreated {
778 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
779 if v.len() < 32+32+2+64 {
780 return Err(DecodeError::WrongLength);
782 let ctx = Secp256k1::without_caps();
784 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
785 funding_txid: deserialize(&v[32..64]).unwrap(),
786 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
787 signature: secp_signature!(&ctx, &v[66..130]),
791 impl MsgEncodable for FundingCreated {
792 fn encode(&self) -> Vec<u8> {
793 let mut res = Vec::with_capacity(32+32+2+64);
794 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
795 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
796 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
797 let secp_ctx = Secp256k1::without_caps();
798 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
803 impl MsgDecodable for FundingSigned {
804 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
806 return Err(DecodeError::WrongLength);
808 let ctx = Secp256k1::without_caps();
810 channel_id: deserialize(&v[0..32]).unwrap(),
811 signature: secp_signature!(&ctx, &v[32..96]),
815 impl MsgEncodable for FundingSigned {
816 fn encode(&self) -> Vec<u8> {
817 let mut res = Vec::with_capacity(32+64);
818 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
819 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
824 impl MsgDecodable for FundingLocked {
825 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
827 return Err(DecodeError::WrongLength);
829 let ctx = Secp256k1::without_caps();
831 channel_id: deserialize(&v[0..32]).unwrap(),
832 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
836 impl MsgEncodable for FundingLocked {
837 fn encode(&self) -> Vec<u8> {
838 let mut res = Vec::with_capacity(32+33);
839 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
840 res.extend_from_slice(&self.next_per_commitment_point.serialize());
845 impl MsgDecodable for Shutdown {
846 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
847 if v.len() < 32 + 2 {
848 return Err(DecodeError::WrongLength);
850 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
851 if v.len() < 32 + 2 + scriptlen {
852 return Err(DecodeError::WrongLength);
855 channel_id: deserialize(&v[0..32]).unwrap(),
856 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
860 impl MsgEncodable for Shutdown {
861 fn encode(&self) -> Vec<u8> {
862 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
863 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
864 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
865 res.extend_from_slice(&self.scriptpubkey[..]);
870 impl MsgDecodable for ClosingSigned {
871 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
872 if v.len() < 32 + 8 + 64 {
873 return Err(DecodeError::WrongLength);
875 let secp_ctx = Secp256k1::without_caps();
877 channel_id: deserialize(&v[0..32]).unwrap(),
878 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
879 signature: secp_signature!(&secp_ctx, &v[40..104]),
883 impl MsgEncodable for ClosingSigned {
884 fn encode(&self) -> Vec<u8> {
885 let mut res = Vec::with_capacity(32+8+64);
886 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
887 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
888 let secp_ctx = Secp256k1::without_caps();
889 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
894 impl MsgDecodable for UpdateAddHTLC {
895 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
896 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
897 return Err(DecodeError::WrongLength);
899 let mut payment_hash = [0; 32];
900 payment_hash.copy_from_slice(&v[48..80]);
902 channel_id: deserialize(&v[0..32]).unwrap(),
903 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
904 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
906 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
907 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
911 impl MsgEncodable for UpdateAddHTLC {
912 fn encode(&self) -> Vec<u8> {
913 let mut res = Vec::with_capacity(32+8+8+32+4+1+1366);
914 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
915 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
916 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
917 res.extend_from_slice(&self.payment_hash);
918 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
919 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
924 impl MsgDecodable for UpdateFulfillHTLC {
925 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
926 if v.len() < 32+8+32 {
927 return Err(DecodeError::WrongLength);
929 let mut payment_preimage = [0; 32];
930 payment_preimage.copy_from_slice(&v[40..72]);
932 channel_id: deserialize(&v[0..32]).unwrap(),
933 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
938 impl MsgEncodable for UpdateFulfillHTLC {
939 fn encode(&self) -> Vec<u8> {
940 let mut res = Vec::with_capacity(32+8+32);
941 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
942 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
943 res.extend_from_slice(&self.payment_preimage);
948 impl MsgDecodable for UpdateFailHTLC {
949 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
951 return Err(DecodeError::WrongLength);
954 channel_id: deserialize(&v[0..32]).unwrap(),
955 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
956 reason: OnionErrorPacket::decode(&v[40..])?,
960 impl MsgEncodable for UpdateFailHTLC {
961 fn encode(&self) -> Vec<u8> {
962 let reason = self.reason.encode();
963 let mut res = Vec::with_capacity(32+8+reason.len());
964 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
965 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
966 res.extend_from_slice(&reason[..]);
971 impl MsgDecodable for UpdateFailMalformedHTLC {
972 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
973 if v.len() < 32+8+32+2 {
974 return Err(DecodeError::WrongLength);
976 let mut sha256_of_onion = [0; 32];
977 sha256_of_onion.copy_from_slice(&v[40..72]);
979 channel_id: deserialize(&v[0..32]).unwrap(),
980 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
982 failure_code: byte_utils::slice_to_be16(&v[72..74]),
986 impl MsgEncodable for UpdateFailMalformedHTLC {
987 fn encode(&self) -> Vec<u8> {
988 let mut res = Vec::with_capacity(32+8+32+2);
989 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
990 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
991 res.extend_from_slice(&self.sha256_of_onion);
992 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
997 impl MsgDecodable for CommitmentSigned {
998 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
999 if v.len() < 32+64+2 {
1000 return Err(DecodeError::WrongLength);
1002 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1003 if v.len() < 32+64+2+htlcs*64 {
1004 return Err(DecodeError::WrongLength);
1006 let mut htlc_signatures = Vec::with_capacity(htlcs);
1007 let secp_ctx = Secp256k1::without_caps();
1009 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1012 channel_id: deserialize(&v[0..32]).unwrap(),
1013 signature: secp_signature!(&secp_ctx, &v[32..96]),
1018 impl MsgEncodable for CommitmentSigned {
1019 fn encode(&self) -> Vec<u8> {
1020 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1021 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
1022 let secp_ctx = Secp256k1::without_caps();
1023 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1024 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1025 for i in 0..self.htlc_signatures.len() {
1026 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1032 impl MsgDecodable for RevokeAndACK {
1033 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1034 if v.len() < 32+32+33 {
1035 return Err(DecodeError::WrongLength);
1037 let mut per_commitment_secret = [0; 32];
1038 per_commitment_secret.copy_from_slice(&v[32..64]);
1039 let secp_ctx = Secp256k1::without_caps();
1041 channel_id: deserialize(&v[0..32]).unwrap(),
1042 per_commitment_secret,
1043 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1047 impl MsgEncodable for RevokeAndACK {
1048 fn encode(&self) -> Vec<u8> {
1049 let mut res = Vec::with_capacity(32+32+33);
1050 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
1051 res.extend_from_slice(&self.per_commitment_secret);
1052 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1057 impl MsgDecodable for UpdateFee {
1058 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1060 return Err(DecodeError::WrongLength);
1063 channel_id: deserialize(&v[0..32]).unwrap(),
1064 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1068 impl MsgEncodable for UpdateFee {
1069 fn encode(&self) -> Vec<u8> {
1070 let mut res = Vec::with_capacity(32+4);
1071 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
1072 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1077 impl MsgDecodable for ChannelReestablish {
1078 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1082 impl MsgEncodable for ChannelReestablish {
1083 fn encode(&self) -> Vec<u8> {
1088 impl MsgDecodable for AnnouncementSignatures {
1089 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1090 if v.len() < 32+8+64*2 {
1091 return Err(DecodeError::WrongLength);
1093 let secp_ctx = Secp256k1::without_caps();
1095 channel_id: deserialize(&v[0..32]).unwrap(),
1096 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1097 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1098 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1102 impl MsgEncodable for AnnouncementSignatures {
1103 fn encode(&self) -> Vec<u8> {
1104 let mut res = Vec::with_capacity(32+8+64*2);
1105 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
1106 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1107 let secp_ctx = Secp256k1::without_caps();
1108 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1109 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1114 impl MsgDecodable for UnsignedNodeAnnouncement {
1115 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1116 let features = GlobalFeatures::decode(&v[..])?;
1117 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1118 return Err(DecodeError::WrongLength);
1120 let start = features.encoded_len();
1122 let mut rgb = [0; 3];
1123 rgb.copy_from_slice(&v[start + 37..start + 40]);
1125 let mut alias = [0; 32];
1126 alias.copy_from_slice(&v[start + 40..start + 72]);
1128 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1129 if v.len() < start + 74 + addrlen {
1130 return Err(DecodeError::WrongLength);
1133 let mut addresses = Vec::with_capacity(4);
1134 let mut read_pos = start + 74;
1136 if v.len() <= read_pos { break; }
1138 0 => { read_pos += 1; },
1140 if v.len() < read_pos + 1 + 6 {
1141 return Err(DecodeError::WrongLength);
1143 if addresses.len() > 0 {
1144 return Err(DecodeError::ExtraAddressesPerType);
1146 let mut addr = [0; 4];
1147 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1148 addresses.push(NetAddress::IPv4 {
1150 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1155 if v.len() < read_pos + 1 + 18 {
1156 return Err(DecodeError::WrongLength);
1158 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1159 return Err(DecodeError::ExtraAddressesPerType);
1161 let mut addr = [0; 16];
1162 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1163 addresses.push(NetAddress::IPv6 {
1165 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1170 if v.len() < read_pos + 1 + 12 {
1171 return Err(DecodeError::WrongLength);
1173 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1174 return Err(DecodeError::ExtraAddressesPerType);
1176 let mut addr = [0; 10];
1177 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1178 addresses.push(NetAddress::OnionV2 {
1180 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1185 if v.len() < read_pos + 1 + 37 {
1186 return Err(DecodeError::WrongLength);
1188 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1189 return Err(DecodeError::ExtraAddressesPerType);
1191 let mut ed25519_pubkey = [0; 32];
1192 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1193 addresses.push(NetAddress::OnionV3 {
1195 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1196 version: v[read_pos + 35],
1197 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1201 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1205 let secp_ctx = Secp256k1::without_caps();
1208 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1209 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1216 impl MsgEncodable for UnsignedNodeAnnouncement {
1217 fn encode(&self) -> Vec<u8> {
1218 let features = self.features.encode();
1219 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1220 res.extend_from_slice(&features[..]);
1221 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1222 res.extend_from_slice(&self.node_id.serialize());
1223 res.extend_from_slice(&self.rgb);
1224 res.extend_from_slice(&self.alias);
1225 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1226 let mut addrs_to_encode = self.addresses.clone();
1227 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1228 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1229 for addr in addrs_to_encode.iter() {
1231 &NetAddress::IPv4{addr, port} => {
1233 addr_slice.extend_from_slice(&addr);
1234 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1236 &NetAddress::IPv6{addr, port} => {
1238 addr_slice.extend_from_slice(&addr);
1239 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1241 &NetAddress::OnionV2{addr, port} => {
1243 addr_slice.extend_from_slice(&addr);
1244 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1246 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1248 addr_slice.extend_from_slice(&ed25519_pubkey);
1249 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1250 addr_slice.push(version);
1251 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1255 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1256 res.extend_from_slice(&addr_slice[..]);
1261 impl MsgDecodable for NodeAnnouncement {
1262 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1264 return Err(DecodeError::WrongLength);
1266 let secp_ctx = Secp256k1::without_caps();
1268 signature: secp_signature!(&secp_ctx, &v[0..64]),
1269 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1273 impl MsgEncodable for NodeAnnouncement {
1274 fn encode(&self) -> Vec<u8> {
1275 let contents = self.contents.encode();
1276 let mut res = Vec::with_capacity(64 + contents.len());
1277 let secp_ctx = Secp256k1::without_caps();
1278 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1279 res.extend_from_slice(&contents);
1284 impl MsgDecodable for UnsignedChannelAnnouncement {
1285 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1286 let features = GlobalFeatures::decode(&v[..])?;
1287 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1288 return Err(DecodeError::WrongLength);
1290 let start = features.encoded_len();
1291 let secp_ctx = Secp256k1::without_caps();
1294 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1295 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1296 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1297 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1298 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1299 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1303 impl MsgEncodable for UnsignedChannelAnnouncement {
1304 fn encode(&self) -> Vec<u8> {
1305 let features = self.features.encode();
1306 let mut res = Vec::with_capacity(172 + features.len());
1307 res.extend_from_slice(&features[..]);
1308 res.extend_from_slice(&self.chain_hash[..]);
1309 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1310 res.extend_from_slice(&self.node_id_1.serialize());
1311 res.extend_from_slice(&self.node_id_2.serialize());
1312 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1313 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1318 impl MsgDecodable for ChannelAnnouncement {
1319 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1321 return Err(DecodeError::WrongLength);
1323 let secp_ctx = Secp256k1::without_caps();
1325 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1326 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1327 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1328 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1329 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1333 impl MsgEncodable for ChannelAnnouncement {
1334 fn encode(&self) -> Vec<u8> {
1335 let secp_ctx = Secp256k1::without_caps();
1336 let contents = self.contents.encode();
1337 let mut res = Vec::with_capacity(64 + contents.len());
1338 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1339 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1340 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1341 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1342 res.extend_from_slice(&contents);
1347 impl MsgDecodable for UnsignedChannelUpdate {
1348 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1349 if v.len() < 32+8+4+2+2+8+4+4 {
1350 return Err(DecodeError::WrongLength);
1353 chain_hash: deserialize(&v[0..32]).unwrap(),
1354 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1355 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1356 flags: byte_utils::slice_to_be16(&v[44..46]),
1357 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1358 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1359 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1360 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1364 impl MsgEncodable for UnsignedChannelUpdate {
1365 fn encode(&self) -> Vec<u8> {
1366 let mut res = Vec::with_capacity(64);
1367 res.extend_from_slice(&self.chain_hash[..]);
1368 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1369 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1370 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1371 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1372 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1373 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1374 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1379 impl MsgDecodable for ChannelUpdate {
1380 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1382 return Err(DecodeError::WrongLength);
1384 let secp_ctx = Secp256k1::without_caps();
1386 signature: secp_signature!(&secp_ctx, &v[0..64]),
1387 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1391 impl MsgEncodable for ChannelUpdate {
1392 fn encode(&self) -> Vec<u8> {
1393 let mut res = Vec::with_capacity(128);
1394 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1395 res.extend_from_slice(&self.contents.encode()[..]);
1400 impl MsgDecodable for OnionRealm0HopData {
1401 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1403 return Err(DecodeError::WrongLength);
1405 Ok(OnionRealm0HopData {
1406 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1407 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1408 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1412 impl MsgEncodable for OnionRealm0HopData {
1413 fn encode(&self) -> Vec<u8> {
1414 let mut res = Vec::with_capacity(32);
1415 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1416 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1417 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1423 impl MsgDecodable for OnionHopData {
1424 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1426 return Err(DecodeError::WrongLength);
1430 return Err(DecodeError::UnknownRealmByte);
1432 let mut hmac = [0; 32];
1433 hmac[..].copy_from_slice(&v[33..65]);
1436 data: OnionRealm0HopData::decode(&v[1..33])?,
1441 impl MsgEncodable for OnionHopData {
1442 fn encode(&self) -> Vec<u8> {
1443 let mut res = Vec::with_capacity(65);
1444 res.push(self.realm);
1445 res.extend_from_slice(&self.data.encode()[..]);
1446 res.extend_from_slice(&self.hmac);
1451 impl MsgDecodable for OnionPacket {
1452 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1453 if v.len() < 1+33+20*65+32 {
1454 return Err(DecodeError::WrongLength);
1456 let mut hop_data = [0; 20*65];
1457 hop_data.copy_from_slice(&v[34..1334]);
1458 let mut hmac = [0; 32];
1459 hmac.copy_from_slice(&v[1334..1366]);
1460 let secp_ctx = Secp256k1::without_caps();
1463 public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1469 impl MsgEncodable for OnionPacket {
1470 fn encode(&self) -> Vec<u8> {
1471 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1472 res.push(self.version);
1473 res.extend_from_slice(&self.public_key.serialize());
1474 res.extend_from_slice(&self.hop_data);
1475 res.extend_from_slice(&self.hmac);
1480 impl MsgDecodable for DecodedOnionErrorPacket {
1481 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1482 if v.len() < 32 + 4 {
1483 return Err(DecodeError::WrongLength);
1485 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1486 if v.len() < 32 + 4 + failuremsg_len {
1487 return Err(DecodeError::WrongLength);
1489 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1490 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1491 return Err(DecodeError::WrongLength);
1494 let mut hmac = [0; 32];
1495 hmac.copy_from_slice(&v[0..32]);
1498 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1499 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1503 impl MsgEncodable for DecodedOnionErrorPacket {
1504 fn encode(&self) -> Vec<u8> {
1505 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1506 res.extend_from_slice(&self.hmac);
1507 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1508 res.extend_from_slice(&self.failuremsg);
1509 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1510 res.extend_from_slice(&self.pad);
1515 impl MsgDecodable for OnionErrorPacket {
1516 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1518 return Err(DecodeError::WrongLength);
1520 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1521 if v.len() < 2 + len {
1522 return Err(DecodeError::WrongLength);
1525 data: v[2..len+2].to_vec(),
1529 impl MsgEncodable for OnionErrorPacket {
1530 fn encode(&self) -> Vec<u8> {
1531 let mut res = Vec::with_capacity(2 + self.data.len());
1532 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1533 res.extend_from_slice(&self.data);