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 /// Failed to decode a public key (ie it's invalid)
33 /// Failed to decode a signature (ie it's invalid)
35 /// Value expected to be text wasn't decodable as text
39 /// node_announcement included more than one address of a given type!
40 ExtraAddressesPerType,
41 /// A length descriptor in the packet didn't describe the later data correctly
42 /// (currently only generated in node_announcement)
45 pub trait MsgDecodable: Sized {
46 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
49 /// Tracks localfeatures which are only in init messages
50 #[derive(Clone, PartialEq)]
51 pub struct LocalFeatures {
56 pub fn new() -> LocalFeatures {
62 pub fn supports_data_loss_protect(&self) -> bool {
63 self.flags.len() > 0 && (self.flags[0] & 3) != 0
65 pub fn requires_data_loss_protect(&self) -> bool {
66 self.flags.len() > 0 && (self.flags[0] & 1) != 0
69 pub fn initial_routing_sync(&self) -> bool {
70 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
72 pub fn set_initial_routing_sync(&mut self) {
73 if self.flags.len() == 0 {
74 self.flags.resize(1, 1 << 3);
76 self.flags[0] |= 1 << 3;
80 pub fn supports_upfront_shutdown_script(&self) -> bool {
81 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
83 pub fn requires_upfront_shutdown_script(&self) -> bool {
84 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
87 pub fn requires_unknown_bits(&self) -> bool {
88 for (idx, &byte) in self.flags.iter().enumerate() {
89 if idx != 0 && (byte & 0x55) != 0 {
91 } else if idx == 0 && (byte & 0x14) != 0 {
98 pub fn supports_unknown_bits(&self) -> bool {
99 for (idx, &byte) in self.flags.iter().enumerate() {
100 if idx != 0 && byte != 0 {
102 } else if idx == 0 && (byte & 0xc4) != 0 {
110 /// Tracks globalfeatures which are in init messages and routing announcements
111 #[derive(Clone, PartialEq)]
112 pub struct GlobalFeatures {
116 impl GlobalFeatures {
117 pub fn new() -> GlobalFeatures {
123 pub fn requires_unknown_bits(&self) -> bool {
124 for &byte in self.flags.iter() {
125 if (byte & 0x55) != 0 {
132 pub fn supports_unknown_bits(&self) -> bool {
133 for &byte in self.flags.iter() {
143 pub global_features: GlobalFeatures,
144 pub local_features: LocalFeatures,
147 pub struct ErrorMessage {
148 pub channel_id: [u8; 32],
161 pub struct OpenChannel {
162 pub chain_hash: Sha256dHash,
163 pub temporary_channel_id: [u8; 32],
164 pub funding_satoshis: u64,
166 pub dust_limit_satoshis: u64,
167 pub max_htlc_value_in_flight_msat: u64,
168 pub channel_reserve_satoshis: u64,
169 pub htlc_minimum_msat: u64,
170 pub feerate_per_kw: u32,
171 pub to_self_delay: u16,
172 pub max_accepted_htlcs: u16,
173 pub funding_pubkey: PublicKey,
174 pub revocation_basepoint: PublicKey,
175 pub payment_basepoint: PublicKey,
176 pub delayed_payment_basepoint: PublicKey,
177 pub htlc_basepoint: PublicKey,
178 pub first_per_commitment_point: PublicKey,
179 pub channel_flags: u8,
180 pub shutdown_scriptpubkey: Option<Script>,
183 pub struct AcceptChannel {
184 pub temporary_channel_id: [u8; 32],
185 pub dust_limit_satoshis: u64,
186 pub max_htlc_value_in_flight_msat: u64,
187 pub channel_reserve_satoshis: u64,
188 pub htlc_minimum_msat: u64,
189 pub minimum_depth: u32,
190 pub to_self_delay: u16,
191 pub max_accepted_htlcs: u16,
192 pub funding_pubkey: PublicKey,
193 pub revocation_basepoint: PublicKey,
194 pub payment_basepoint: PublicKey,
195 pub delayed_payment_basepoint: PublicKey,
196 pub htlc_basepoint: PublicKey,
197 pub first_per_commitment_point: PublicKey,
198 pub shutdown_scriptpubkey: Option<Script>,
201 pub struct FundingCreated {
202 pub temporary_channel_id: [u8; 32],
203 pub funding_txid: Sha256dHash,
204 pub funding_output_index: u16,
205 pub signature: Signature,
208 pub struct FundingSigned {
209 pub channel_id: [u8; 32],
210 pub signature: Signature,
213 pub struct FundingLocked {
214 pub channel_id: [u8; 32],
215 pub next_per_commitment_point: PublicKey,
218 pub struct Shutdown {
219 pub channel_id: [u8; 32],
220 pub scriptpubkey: Script,
223 pub struct ClosingSigned {
224 pub channel_id: [u8; 32],
225 pub fee_satoshis: u64,
226 pub signature: Signature,
230 pub struct UpdateAddHTLC {
231 pub channel_id: [u8; 32],
233 pub amount_msat: u64,
234 pub payment_hash: [u8; 32],
235 pub cltv_expiry: u32,
236 pub onion_routing_packet: OnionPacket,
240 pub struct UpdateFulfillHTLC {
241 pub channel_id: [u8; 32],
243 pub payment_preimage: [u8; 32],
247 pub struct UpdateFailHTLC {
248 pub channel_id: [u8; 32],
250 pub reason: OnionErrorPacket,
254 pub struct UpdateFailMalformedHTLC {
255 pub channel_id: [u8; 32],
257 pub sha256_of_onion: [u8; 32],
258 pub failure_code: u16,
262 pub struct CommitmentSigned {
263 pub channel_id: [u8; 32],
264 pub signature: Signature,
265 pub htlc_signatures: Vec<Signature>,
268 pub struct RevokeAndACK {
269 pub channel_id: [u8; 32],
270 pub per_commitment_secret: [u8; 32],
271 pub next_per_commitment_point: PublicKey,
274 pub struct UpdateFee {
275 pub channel_id: [u8; 32],
276 pub feerate_per_kw: u32,
279 pub struct DataLossProtect {
280 pub your_last_per_commitment_secret: [u8; 32],
281 pub my_current_per_commitment_point: PublicKey,
284 pub struct ChannelReestablish {
285 pub channel_id: [u8; 32],
286 pub next_local_commitment_number: u64,
287 pub next_remote_commitment_number: u64,
288 pub data_loss_protect: Option<DataLossProtect>,
292 pub struct AnnouncementSignatures {
293 pub channel_id: [u8; 32],
294 pub short_channel_id: u64,
295 pub node_signature: Signature,
296 pub bitcoin_signature: Signature,
300 pub enum NetAddress {
314 ed25519_pubkey: [u8; 32],
321 fn get_id(&self) -> u8 {
323 &NetAddress::IPv4 {..} => { 1 },
324 &NetAddress::IPv6 {..} => { 2 },
325 &NetAddress::OnionV2 {..} => { 3 },
326 &NetAddress::OnionV3 {..} => { 4 },
331 pub struct UnsignedNodeAnnouncement {
332 pub features: GlobalFeatures,
334 pub node_id: PublicKey,
337 /// List of addresses on which this node is reachable. Note that you may only have up to one
338 /// address of each type, if you have more, they may be silently discarded or we may panic!
339 pub addresses: Vec<NetAddress>,
341 pub struct NodeAnnouncement {
342 pub signature: Signature,
343 pub contents: UnsignedNodeAnnouncement,
346 #[derive(PartialEq, Clone)]
347 pub struct UnsignedChannelAnnouncement {
348 pub features: GlobalFeatures,
349 pub chain_hash: Sha256dHash,
350 pub short_channel_id: u64,
351 pub node_id_1: PublicKey,
352 pub node_id_2: PublicKey,
353 pub bitcoin_key_1: PublicKey,
354 pub bitcoin_key_2: PublicKey,
355 pub excess_data: Vec<u8>,
357 #[derive(PartialEq, Clone)]
358 pub struct ChannelAnnouncement {
359 pub node_signature_1: Signature,
360 pub node_signature_2: Signature,
361 pub bitcoin_signature_1: Signature,
362 pub bitcoin_signature_2: Signature,
363 pub contents: UnsignedChannelAnnouncement,
366 #[derive(PartialEq, Clone)]
367 pub struct UnsignedChannelUpdate {
368 pub chain_hash: Sha256dHash,
369 pub short_channel_id: u64,
372 pub cltv_expiry_delta: u16,
373 pub htlc_minimum_msat: u64,
374 pub fee_base_msat: u32,
375 pub fee_proportional_millionths: u32,
376 pub excess_data: Vec<u8>,
378 #[derive(PartialEq, Clone)]
379 pub struct ChannelUpdate {
380 pub signature: Signature,
381 pub contents: UnsignedChannelUpdate,
384 /// Used to put an error message in a HandleError
385 pub enum ErrorAction {
386 /// The peer took some action which made us think they were useless. Disconnect them.
388 msg: Option<ErrorMessage>
390 /// The peer did something harmless that we weren't able to process, just log and ignore
392 /// The peer did something incorrect. Tell them.
398 pub struct HandleError { //TODO: rename me
399 pub err: &'static str,
400 pub action: Option<ErrorAction>, //TODO: Make this required
403 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
404 /// transaction updates if they were pending.
405 pub struct CommitmentUpdate {
406 pub update_add_htlcs: Vec<UpdateAddHTLC>,
407 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
408 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
409 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
410 pub commitment_signed: CommitmentSigned,
413 pub enum HTLCFailChannelUpdate {
414 ChannelUpdateMessage {
418 short_channel_id: u64,
422 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
423 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
424 /// paralell when the two calls have the same their_node_id.
425 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
427 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
428 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
429 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
430 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
431 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
434 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
435 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
438 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
439 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
440 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
441 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
442 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
443 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
445 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
447 // Channel-to-announce:
448 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
451 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
452 /// is believed to be possible in the future (eg they're sending us messages we don't
453 /// understand or indicate they require unknown feature bits), no_connection_possible is set
454 /// and any outstanding channels should be failed.
455 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
457 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
460 pub trait RoutingMessageHandler : Send + Sync {
461 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
462 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
463 /// or returning an Err otherwise.
464 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
465 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
466 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
469 pub struct OnionRealm0HopData {
470 pub short_channel_id: u64,
471 pub amt_to_forward: u64,
472 pub outgoing_cltv_value: u32,
473 // 12 bytes of 0-padding
476 pub struct OnionHopData {
478 pub data: OnionRealm0HopData,
481 unsafe impl internal_traits::NoDealloc for OnionHopData{}
484 pub struct OnionPacket {
486 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
487 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
488 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
489 pub public_key: Result<PublicKey, secp256k1::Error>,
490 pub hop_data: [u8; 20*65],
494 pub struct DecodedOnionErrorPacket {
496 pub failuremsg: Vec<u8>,
501 pub struct OnionErrorPacket {
502 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
503 // (TODO) We limit it in decode to much lower...
507 impl Error for DecodeError {
508 fn description(&self) -> &str {
510 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
511 DecodeError::BadPublicKey => "Invalid public key in packet",
512 DecodeError::BadSignature => "Invalid signature in packet",
513 DecodeError::BadText => "Invalid text in packet",
514 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
515 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
516 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
520 impl fmt::Display for DecodeError {
521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522 f.write_str(self.description())
526 impl fmt::Debug for HandleError {
527 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528 f.write_str(self.err)
532 macro_rules! secp_pubkey {
533 ( $ctx: expr, $slice: expr ) => {
534 match PublicKey::from_slice($ctx, $slice) {
536 Err(_) => return Err(DecodeError::BadPublicKey)
541 macro_rules! secp_signature {
542 ( $ctx: expr, $slice: expr ) => {
543 match Signature::from_compact($ctx, $slice) {
545 Err(_) => return Err(DecodeError::BadSignature)
550 impl MsgDecodable for LocalFeatures {
551 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
552 if v.len() < 2 { return Err(DecodeError::ShortRead); }
553 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
554 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
555 let mut flags = Vec::with_capacity(len);
556 flags.extend_from_slice(&v[2..2 + len]);
562 impl MsgEncodable for LocalFeatures {
563 fn encode(&self) -> Vec<u8> {
564 let mut res = Vec::with_capacity(self.flags.len() + 2);
565 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
566 res.extend_from_slice(&self.flags[..]);
569 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
572 impl MsgDecodable for GlobalFeatures {
573 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
574 if v.len() < 2 { return Err(DecodeError::ShortRead); }
575 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
576 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
577 let mut flags = Vec::with_capacity(len);
578 flags.extend_from_slice(&v[2..2 + len]);
584 impl MsgEncodable for GlobalFeatures {
585 fn encode(&self) -> Vec<u8> {
586 let mut res = Vec::with_capacity(self.flags.len() + 2);
587 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
588 res.extend_from_slice(&self.flags[..]);
591 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
594 impl MsgDecodable for Init {
595 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
596 let global_features = GlobalFeatures::decode(v)?;
597 if v.len() < global_features.flags.len() + 4 {
598 return Err(DecodeError::ShortRead);
600 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
602 global_features: global_features,
603 local_features: local_features,
607 impl MsgEncodable for Init {
608 fn encode(&self) -> Vec<u8> {
609 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
610 res.extend_from_slice(&self.global_features.encode()[..]);
611 res.extend_from_slice(&self.local_features.encode()[..]);
616 impl MsgDecodable for Ping {
617 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
619 return Err(DecodeError::ShortRead);
621 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
622 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
623 if v.len() < 4 + byteslen as usize {
624 return Err(DecodeError::ShortRead);
632 impl MsgEncodable for Ping {
633 fn encode(&self) -> Vec<u8> {
634 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
635 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
636 res.resize(2 + self.byteslen as usize, 0);
641 impl MsgDecodable for Pong {
642 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
644 return Err(DecodeError::ShortRead);
646 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
647 if v.len() < 2 + byteslen as usize {
648 return Err(DecodeError::ShortRead);
655 impl MsgEncodable for Pong {
656 fn encode(&self) -> Vec<u8> {
657 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
658 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
659 res.resize(2 + self.byteslen as usize, 0);
664 impl MsgDecodable for OpenChannel {
665 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
666 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
667 return Err(DecodeError::ShortRead);
669 let ctx = Secp256k1::without_caps();
671 let mut shutdown_scriptpubkey = None;
673 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
674 if v.len() < 321+len {
675 return Err(DecodeError::ShortRead);
677 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
681 chain_hash: deserialize(&v[0..32]).unwrap(),
682 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
683 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
684 push_msat: byte_utils::slice_to_be64(&v[72..80]),
685 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
686 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
687 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
688 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
689 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
690 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
691 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
692 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
693 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
694 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
695 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
696 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
697 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
698 channel_flags: v[318],
699 shutdown_scriptpubkey: shutdown_scriptpubkey
703 impl MsgEncodable for OpenChannel {
704 fn encode(&self) -> Vec<u8> {
705 let mut res = match &self.shutdown_scriptpubkey {
706 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
707 &None => Vec::with_capacity(319),
709 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
710 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
711 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
712 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
713 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
714 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
715 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
716 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
717 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
718 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
719 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
720 res.extend_from_slice(&self.funding_pubkey.serialize());
721 res.extend_from_slice(&self.revocation_basepoint.serialize());
722 res.extend_from_slice(&self.payment_basepoint.serialize());
723 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
724 res.extend_from_slice(&self.htlc_basepoint.serialize());
725 res.extend_from_slice(&self.first_per_commitment_point.serialize());
726 res.push(self.channel_flags);
727 if let &Some(ref script) = &self.shutdown_scriptpubkey {
728 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
729 res.extend_from_slice(&script[..]);
735 impl MsgDecodable for AcceptChannel {
736 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
737 if v.len() < 32+4*8+4+2*2+6*33 {
738 return Err(DecodeError::ShortRead);
740 let ctx = Secp256k1::without_caps();
742 let mut shutdown_scriptpubkey = None;
744 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
745 if v.len() < 272+len {
746 return Err(DecodeError::ShortRead);
748 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
751 let mut temporary_channel_id = [0; 32];
752 temporary_channel_id[..].copy_from_slice(&v[0..32]);
754 temporary_channel_id,
755 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
756 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
757 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
758 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
759 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
760 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
761 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
762 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
763 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
764 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
765 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
766 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
767 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
768 shutdown_scriptpubkey: shutdown_scriptpubkey
772 impl MsgEncodable for AcceptChannel {
773 fn encode(&self) -> Vec<u8> {
774 let mut res = match &self.shutdown_scriptpubkey {
775 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
776 &None => Vec::with_capacity(270),
778 res.extend_from_slice(&self.temporary_channel_id);
779 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
780 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
781 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
782 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
783 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
784 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
785 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
786 res.extend_from_slice(&self.funding_pubkey.serialize());
787 res.extend_from_slice(&self.revocation_basepoint.serialize());
788 res.extend_from_slice(&self.payment_basepoint.serialize());
789 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
790 res.extend_from_slice(&self.htlc_basepoint.serialize());
791 res.extend_from_slice(&self.first_per_commitment_point.serialize());
792 if let &Some(ref script) = &self.shutdown_scriptpubkey {
793 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
794 res.extend_from_slice(&script[..]);
800 impl MsgDecodable for FundingCreated {
801 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
802 if v.len() < 32+32+2+64 {
803 return Err(DecodeError::ShortRead);
805 let ctx = Secp256k1::without_caps();
806 let mut temporary_channel_id = [0; 32];
807 temporary_channel_id[..].copy_from_slice(&v[0..32]);
809 temporary_channel_id,
810 funding_txid: deserialize(&v[32..64]).unwrap(),
811 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
812 signature: secp_signature!(&ctx, &v[66..130]),
816 impl MsgEncodable for FundingCreated {
817 fn encode(&self) -> Vec<u8> {
818 let mut res = Vec::with_capacity(32+32+2+64);
819 res.extend_from_slice(&self.temporary_channel_id);
820 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
821 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
822 let secp_ctx = Secp256k1::without_caps();
823 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
828 impl MsgDecodable for FundingSigned {
829 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
831 return Err(DecodeError::ShortRead);
833 let ctx = Secp256k1::without_caps();
834 let mut channel_id = [0; 32];
835 channel_id[..].copy_from_slice(&v[0..32]);
838 signature: secp_signature!(&ctx, &v[32..96]),
842 impl MsgEncodable for FundingSigned {
843 fn encode(&self) -> Vec<u8> {
844 let mut res = Vec::with_capacity(32+64);
845 res.extend_from_slice(&self.channel_id);
846 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
851 impl MsgDecodable for FundingLocked {
852 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
854 return Err(DecodeError::ShortRead);
856 let ctx = Secp256k1::without_caps();
857 let mut channel_id = [0; 32];
858 channel_id[..].copy_from_slice(&v[0..32]);
861 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
865 impl MsgEncodable for FundingLocked {
866 fn encode(&self) -> Vec<u8> {
867 let mut res = Vec::with_capacity(32+33);
868 res.extend_from_slice(&self.channel_id);
869 res.extend_from_slice(&self.next_per_commitment_point.serialize());
874 impl MsgDecodable for Shutdown {
875 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
876 if v.len() < 32 + 2 {
877 return Err(DecodeError::ShortRead);
879 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
880 if v.len() < 32 + 2 + scriptlen {
881 return Err(DecodeError::ShortRead);
883 let mut channel_id = [0; 32];
884 channel_id[..].copy_from_slice(&v[0..32]);
887 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
891 impl MsgEncodable for Shutdown {
892 fn encode(&self) -> Vec<u8> {
893 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
894 res.extend_from_slice(&self.channel_id);
895 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
896 res.extend_from_slice(&self.scriptpubkey[..]);
901 impl MsgDecodable for ClosingSigned {
902 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
903 if v.len() < 32 + 8 + 64 {
904 return Err(DecodeError::ShortRead);
906 let secp_ctx = Secp256k1::without_caps();
907 let mut channel_id = [0; 32];
908 channel_id[..].copy_from_slice(&v[0..32]);
911 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
912 signature: secp_signature!(&secp_ctx, &v[40..104]),
916 impl MsgEncodable for ClosingSigned {
917 fn encode(&self) -> Vec<u8> {
918 let mut res = Vec::with_capacity(32+8+64);
919 res.extend_from_slice(&self.channel_id);
920 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
921 let secp_ctx = Secp256k1::without_caps();
922 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
927 impl MsgDecodable for UpdateAddHTLC {
928 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
929 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
930 return Err(DecodeError::ShortRead);
932 let mut channel_id = [0; 32];
933 channel_id[..].copy_from_slice(&v[0..32]);
934 let mut payment_hash = [0; 32];
935 payment_hash.copy_from_slice(&v[48..80]);
938 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
939 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
941 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
942 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
946 impl MsgEncodable for UpdateAddHTLC {
947 fn encode(&self) -> Vec<u8> {
948 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
949 res.extend_from_slice(&self.channel_id);
950 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
951 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
952 res.extend_from_slice(&self.payment_hash);
953 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
954 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
959 impl MsgDecodable for UpdateFulfillHTLC {
960 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
961 if v.len() < 32+8+32 {
962 return Err(DecodeError::ShortRead);
964 let mut channel_id = [0; 32];
965 channel_id[..].copy_from_slice(&v[0..32]);
966 let mut payment_preimage = [0; 32];
967 payment_preimage.copy_from_slice(&v[40..72]);
970 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
975 impl MsgEncodable for UpdateFulfillHTLC {
976 fn encode(&self) -> Vec<u8> {
977 let mut res = Vec::with_capacity(32+8+32);
978 res.extend_from_slice(&self.channel_id);
979 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
980 res.extend_from_slice(&self.payment_preimage);
985 impl MsgDecodable for UpdateFailHTLC {
986 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
988 return Err(DecodeError::ShortRead);
990 let mut channel_id = [0; 32];
991 channel_id[..].copy_from_slice(&v[0..32]);
994 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
995 reason: OnionErrorPacket::decode(&v[40..])?,
999 impl MsgEncodable for UpdateFailHTLC {
1000 fn encode(&self) -> Vec<u8> {
1001 let reason = self.reason.encode();
1002 let mut res = Vec::with_capacity(32+8+reason.len());
1003 res.extend_from_slice(&self.channel_id);
1004 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1005 res.extend_from_slice(&reason[..]);
1010 impl MsgDecodable for UpdateFailMalformedHTLC {
1011 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1012 if v.len() < 32+8+32+2 {
1013 return Err(DecodeError::ShortRead);
1015 let mut channel_id = [0; 32];
1016 channel_id[..].copy_from_slice(&v[0..32]);
1017 let mut sha256_of_onion = [0; 32];
1018 sha256_of_onion.copy_from_slice(&v[40..72]);
1021 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1023 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1027 impl MsgEncodable for UpdateFailMalformedHTLC {
1028 fn encode(&self) -> Vec<u8> {
1029 let mut res = Vec::with_capacity(32+8+32+2);
1030 res.extend_from_slice(&self.channel_id);
1031 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1032 res.extend_from_slice(&self.sha256_of_onion);
1033 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1038 impl MsgDecodable for CommitmentSigned {
1039 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1040 if v.len() < 32+64+2 {
1041 return Err(DecodeError::ShortRead);
1043 let mut channel_id = [0; 32];
1044 channel_id[..].copy_from_slice(&v[0..32]);
1046 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1047 if v.len() < 32+64+2+htlcs*64 {
1048 return Err(DecodeError::ShortRead);
1050 let mut htlc_signatures = Vec::with_capacity(htlcs);
1051 let secp_ctx = Secp256k1::without_caps();
1053 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1057 signature: secp_signature!(&secp_ctx, &v[32..96]),
1062 impl MsgEncodable for CommitmentSigned {
1063 fn encode(&self) -> Vec<u8> {
1064 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1065 res.extend_from_slice(&self.channel_id);
1066 let secp_ctx = Secp256k1::without_caps();
1067 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1068 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1069 for i in 0..self.htlc_signatures.len() {
1070 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1076 impl MsgDecodable for RevokeAndACK {
1077 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1078 if v.len() < 32+32+33 {
1079 return Err(DecodeError::ShortRead);
1081 let mut channel_id = [0; 32];
1082 channel_id[..].copy_from_slice(&v[0..32]);
1083 let mut per_commitment_secret = [0; 32];
1084 per_commitment_secret.copy_from_slice(&v[32..64]);
1085 let secp_ctx = Secp256k1::without_caps();
1088 per_commitment_secret,
1089 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1093 impl MsgEncodable for RevokeAndACK {
1094 fn encode(&self) -> Vec<u8> {
1095 let mut res = Vec::with_capacity(32+32+33);
1096 res.extend_from_slice(&self.channel_id);
1097 res.extend_from_slice(&self.per_commitment_secret);
1098 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1103 impl MsgDecodable for UpdateFee {
1104 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1106 return Err(DecodeError::ShortRead);
1108 let mut channel_id = [0; 32];
1109 channel_id[..].copy_from_slice(&v[0..32]);
1112 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1116 impl MsgEncodable for UpdateFee {
1117 fn encode(&self) -> Vec<u8> {
1118 let mut res = Vec::with_capacity(32+4);
1119 res.extend_from_slice(&self.channel_id);
1120 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1125 impl MsgDecodable for ChannelReestablish {
1126 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1127 if v.len() < 32+2*8 {
1128 return Err(DecodeError::ShortRead);
1131 let data_loss_protect = if v.len() > 32+2*8 {
1132 if v.len() < 32+2*8 + 33+32 {
1133 return Err(DecodeError::ShortRead);
1135 let mut inner_array = [0; 32];
1136 inner_array.copy_from_slice(&v[48..48+32]);
1137 Some(DataLossProtect {
1138 your_last_per_commitment_secret: inner_array,
1139 my_current_per_commitment_point: secp_pubkey!(&Secp256k1::without_caps(), &v[48+32..48+32+33]),
1144 channel_id: deserialize(&v[0..32]).unwrap(),
1145 next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1146 next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1147 data_loss_protect: data_loss_protect,
1151 impl MsgEncodable for ChannelReestablish {
1152 fn encode(&self) -> Vec<u8> {
1153 let mut res = Vec::with_capacity(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
1155 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1156 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1157 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1159 if let &Some(ref data_loss_protect) = &self.data_loss_protect {
1160 res.extend_from_slice(&data_loss_protect.your_last_per_commitment_secret[..]);
1161 res.extend_from_slice(&data_loss_protect.my_current_per_commitment_point.serialize());
1167 impl MsgDecodable for AnnouncementSignatures {
1168 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1169 if v.len() < 32+8+64*2 {
1170 return Err(DecodeError::ShortRead);
1172 let secp_ctx = Secp256k1::without_caps();
1173 let mut channel_id = [0; 32];
1174 channel_id[..].copy_from_slice(&v[0..32]);
1177 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1178 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1179 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1183 impl MsgEncodable for AnnouncementSignatures {
1184 fn encode(&self) -> Vec<u8> {
1185 let mut res = Vec::with_capacity(32+8+64*2);
1186 res.extend_from_slice(&self.channel_id);
1187 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1188 let secp_ctx = Secp256k1::without_caps();
1189 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1190 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1195 impl MsgDecodable for UnsignedNodeAnnouncement {
1196 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1197 let features = GlobalFeatures::decode(&v[..])?;
1198 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1199 return Err(DecodeError::ShortRead);
1201 let start = features.encoded_len();
1203 let mut rgb = [0; 3];
1204 rgb.copy_from_slice(&v[start + 37..start + 40]);
1206 let mut alias = [0; 32];
1207 alias.copy_from_slice(&v[start + 40..start + 72]);
1209 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1210 if v.len() < start + 74 + addrlen {
1211 return Err(DecodeError::ShortRead);
1213 let addr_read_limit = start + 74 + addrlen;
1215 let mut addresses = Vec::with_capacity(4);
1216 let mut read_pos = start + 74;
1218 if addr_read_limit <= read_pos { break; }
1220 0 => { read_pos += 1; },
1222 if addresses.len() > 0 {
1223 return Err(DecodeError::ExtraAddressesPerType);
1225 if addr_read_limit < read_pos + 1 + 6 {
1226 return Err(DecodeError::BadLengthDescriptor);
1228 let mut addr = [0; 4];
1229 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1230 addresses.push(NetAddress::IPv4 {
1232 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1237 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1238 return Err(DecodeError::ExtraAddressesPerType);
1240 if addr_read_limit < read_pos + 1 + 18 {
1241 return Err(DecodeError::BadLengthDescriptor);
1243 let mut addr = [0; 16];
1244 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1245 addresses.push(NetAddress::IPv6 {
1247 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1252 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1253 return Err(DecodeError::ExtraAddressesPerType);
1255 if addr_read_limit < read_pos + 1 + 12 {
1256 return Err(DecodeError::BadLengthDescriptor);
1258 let mut addr = [0; 10];
1259 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1260 addresses.push(NetAddress::OnionV2 {
1262 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1267 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1268 return Err(DecodeError::ExtraAddressesPerType);
1270 if addr_read_limit < read_pos + 1 + 37 {
1271 return Err(DecodeError::BadLengthDescriptor);
1273 let mut ed25519_pubkey = [0; 32];
1274 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1275 addresses.push(NetAddress::OnionV3 {
1277 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1278 version: v[read_pos + 35],
1279 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1283 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1287 let secp_ctx = Secp256k1::without_caps();
1290 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1291 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1298 impl MsgEncodable for UnsignedNodeAnnouncement {
1299 fn encode(&self) -> Vec<u8> {
1300 let features = self.features.encode();
1301 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1302 res.extend_from_slice(&features[..]);
1303 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1304 res.extend_from_slice(&self.node_id.serialize());
1305 res.extend_from_slice(&self.rgb);
1306 res.extend_from_slice(&self.alias);
1307 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1308 let mut addrs_to_encode = self.addresses.clone();
1309 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1310 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1311 for addr in addrs_to_encode.iter() {
1313 &NetAddress::IPv4{addr, port} => {
1315 addr_slice.extend_from_slice(&addr);
1316 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1318 &NetAddress::IPv6{addr, port} => {
1320 addr_slice.extend_from_slice(&addr);
1321 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1323 &NetAddress::OnionV2{addr, port} => {
1325 addr_slice.extend_from_slice(&addr);
1326 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1328 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1330 addr_slice.extend_from_slice(&ed25519_pubkey);
1331 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1332 addr_slice.push(version);
1333 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1337 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1338 res.extend_from_slice(&addr_slice[..]);
1343 impl MsgDecodable for NodeAnnouncement {
1344 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1346 return Err(DecodeError::ShortRead);
1348 let secp_ctx = Secp256k1::without_caps();
1350 signature: secp_signature!(&secp_ctx, &v[0..64]),
1351 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1355 impl MsgEncodable for NodeAnnouncement {
1356 fn encode(&self) -> Vec<u8> {
1357 let contents = self.contents.encode();
1358 let mut res = Vec::with_capacity(64 + contents.len());
1359 let secp_ctx = Secp256k1::without_caps();
1360 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1361 res.extend_from_slice(&contents);
1366 impl MsgDecodable for UnsignedChannelAnnouncement {
1367 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1368 let features = GlobalFeatures::decode(&v[..])?;
1369 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1370 return Err(DecodeError::ShortRead);
1372 let start = features.encoded_len();
1373 let secp_ctx = Secp256k1::without_caps();
1374 let mut excess_data = Vec::with_capacity(v.len() - start - 172);
1375 excess_data.extend_from_slice(&v[start + 172..]);
1378 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1379 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1380 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1381 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1382 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1383 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1388 impl MsgEncodable for UnsignedChannelAnnouncement {
1389 fn encode(&self) -> Vec<u8> {
1390 let features = self.features.encode();
1391 let mut res = Vec::with_capacity(172 + features.len() + self.excess_data.len());
1392 res.extend_from_slice(&features[..]);
1393 res.extend_from_slice(&self.chain_hash[..]);
1394 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1395 res.extend_from_slice(&self.node_id_1.serialize());
1396 res.extend_from_slice(&self.node_id_2.serialize());
1397 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1398 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1399 res.extend_from_slice(&self.excess_data[..]);
1404 impl MsgDecodable for ChannelAnnouncement {
1405 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1407 return Err(DecodeError::ShortRead);
1409 let secp_ctx = Secp256k1::without_caps();
1411 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1412 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1413 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1414 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1415 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1419 impl MsgEncodable for ChannelAnnouncement {
1420 fn encode(&self) -> Vec<u8> {
1421 let secp_ctx = Secp256k1::without_caps();
1422 let contents = self.contents.encode();
1423 let mut res = Vec::with_capacity(64 + contents.len());
1424 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1425 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1426 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1427 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1428 res.extend_from_slice(&contents);
1433 impl MsgDecodable for UnsignedChannelUpdate {
1434 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1435 if v.len() < 32+8+4+2+2+8+4+4 {
1436 return Err(DecodeError::ShortRead);
1438 let mut excess_data = Vec::with_capacity(v.len() - 64);
1439 excess_data.extend_from_slice(&v[64..]);
1441 chain_hash: deserialize(&v[0..32]).unwrap(),
1442 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1443 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1444 flags: byte_utils::slice_to_be16(&v[44..46]),
1445 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1446 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1447 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1448 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1453 impl MsgEncodable for UnsignedChannelUpdate {
1454 fn encode(&self) -> Vec<u8> {
1455 let mut res = Vec::with_capacity(64 + self.excess_data.len());
1456 res.extend_from_slice(&self.chain_hash[..]);
1457 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1458 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1459 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1460 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1461 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1462 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1463 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1464 res.extend_from_slice(&self.excess_data[..]);
1469 impl MsgDecodable for ChannelUpdate {
1470 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1472 return Err(DecodeError::ShortRead);
1474 let secp_ctx = Secp256k1::without_caps();
1476 signature: secp_signature!(&secp_ctx, &v[0..64]),
1477 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1481 impl MsgEncodable for ChannelUpdate {
1482 fn encode(&self) -> Vec<u8> {
1483 let mut res = Vec::with_capacity(128);
1484 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1485 res.extend_from_slice(&self.contents.encode()[..]);
1490 impl MsgDecodable for OnionRealm0HopData {
1491 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1493 return Err(DecodeError::ShortRead);
1495 Ok(OnionRealm0HopData {
1496 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1497 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1498 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1502 impl MsgEncodable for OnionRealm0HopData {
1503 fn encode(&self) -> Vec<u8> {
1504 let mut res = Vec::with_capacity(32);
1505 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1506 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1507 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1513 impl MsgDecodable for OnionHopData {
1514 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1516 return Err(DecodeError::ShortRead);
1520 return Err(DecodeError::UnknownRealmByte);
1522 let mut hmac = [0; 32];
1523 hmac[..].copy_from_slice(&v[33..65]);
1526 data: OnionRealm0HopData::decode(&v[1..33])?,
1531 impl MsgEncodable for OnionHopData {
1532 fn encode(&self) -> Vec<u8> {
1533 let mut res = Vec::with_capacity(65);
1534 res.push(self.realm);
1535 res.extend_from_slice(&self.data.encode()[..]);
1536 res.extend_from_slice(&self.hmac);
1541 impl MsgDecodable for OnionPacket {
1542 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1543 if v.len() < 1+33+20*65+32 {
1544 return Err(DecodeError::ShortRead);
1546 let mut hop_data = [0; 20*65];
1547 hop_data.copy_from_slice(&v[34..1334]);
1548 let mut hmac = [0; 32];
1549 hmac.copy_from_slice(&v[1334..1366]);
1550 let secp_ctx = Secp256k1::without_caps();
1553 public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1559 impl MsgEncodable for OnionPacket {
1560 fn encode(&self) -> Vec<u8> {
1561 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1562 res.push(self.version);
1563 match self.public_key {
1564 Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1565 Err(_) => res.extend_from_slice(&[0; 33]),
1567 res.extend_from_slice(&self.hop_data);
1568 res.extend_from_slice(&self.hmac);
1573 impl MsgDecodable for DecodedOnionErrorPacket {
1574 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1575 if v.len() < 32 + 4 {
1576 return Err(DecodeError::ShortRead);
1578 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1579 if v.len() < 32 + 4 + failuremsg_len {
1580 return Err(DecodeError::ShortRead);
1582 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1583 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1584 return Err(DecodeError::ShortRead);
1587 let mut hmac = [0; 32];
1588 hmac.copy_from_slice(&v[0..32]);
1591 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1592 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1596 impl MsgEncodable for DecodedOnionErrorPacket {
1597 fn encode(&self) -> Vec<u8> {
1598 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1599 res.extend_from_slice(&self.hmac);
1600 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1601 res.extend_from_slice(&self.failuremsg);
1602 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1603 res.extend_from_slice(&self.pad);
1608 impl MsgDecodable for OnionErrorPacket {
1609 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1611 return Err(DecodeError::ShortRead);
1613 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1614 if v.len() < 2 + len {
1615 return Err(DecodeError::ShortRead);
1618 data: v[2..len+2].to_vec(),
1622 impl MsgEncodable for OnionErrorPacket {
1623 fn encode(&self) -> Vec<u8> {
1624 let mut res = Vec::with_capacity(2 + self.data.len());
1625 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1626 res.extend_from_slice(&self.data);
1631 impl MsgEncodable for ErrorMessage {
1632 fn encode(&self) -> Vec<u8> {
1633 let mut res = Vec::with_capacity(34 + self.data.len());
1634 res.extend_from_slice(&self.channel_id);
1635 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1636 res.extend_from_slice(&self.data.as_bytes());
1640 impl MsgDecodable for ErrorMessage {
1641 fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1643 return Err(DecodeError::ShortRead);
1645 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1646 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1647 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1649 Err(_) => return Err(DecodeError::BadText),
1651 let mut channel_id = [0; 32];
1652 channel_id[..].copy_from_slice(&v[0..32]);
1663 use ln::msgs::MsgEncodable;
1665 use secp256k1::key::{PublicKey,SecretKey};
1666 use secp256k1::Secp256k1;
1669 fn encoding_channel_reestablish_no_secret() {
1670 let cr = msgs::ChannelReestablish {
1671 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],
1672 next_local_commitment_number: 3,
1673 next_remote_commitment_number: 4,
1674 data_loss_protect: None,
1677 let encoded_value = cr.encode();
1680 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]
1685 fn encoding_channel_reestablish_with_secret() {
1687 let secp_ctx = Secp256k1::new();
1688 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1691 let cr = msgs::ChannelReestablish {
1692 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],
1693 next_local_commitment_number: 3,
1694 next_remote_commitment_number: 4,
1695 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1698 let encoded_value = cr.encode();
1701 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]