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 ChannelReestablish {
280 pub channel_id: [u8; 32],
281 pub next_local_commitment_number: u64,
282 pub next_remote_commitment_number: u64,
283 pub your_last_per_commitment_secret: Option<[u8; 32]>,
284 pub my_current_per_commitment_point: PublicKey,
288 pub struct AnnouncementSignatures {
289 pub channel_id: [u8; 32],
290 pub short_channel_id: u64,
291 pub node_signature: Signature,
292 pub bitcoin_signature: Signature,
296 pub enum NetAddress {
310 ed25519_pubkey: [u8; 32],
317 fn get_id(&self) -> u8 {
319 &NetAddress::IPv4 {..} => { 1 },
320 &NetAddress::IPv6 {..} => { 2 },
321 &NetAddress::OnionV2 {..} => { 3 },
322 &NetAddress::OnionV3 {..} => { 4 },
327 pub struct UnsignedNodeAnnouncement {
328 pub features: GlobalFeatures,
330 pub node_id: PublicKey,
333 /// List of addresses on which this node is reachable. Note that you may only have up to one
334 /// address of each type, if you have more, they may be silently discarded or we may panic!
335 pub addresses: Vec<NetAddress>,
337 pub struct NodeAnnouncement {
338 pub signature: Signature,
339 pub contents: UnsignedNodeAnnouncement,
342 #[derive(PartialEq, Clone)]
343 pub struct UnsignedChannelAnnouncement {
344 pub features: GlobalFeatures,
345 pub chain_hash: Sha256dHash,
346 pub short_channel_id: u64,
347 pub node_id_1: PublicKey,
348 pub node_id_2: PublicKey,
349 pub bitcoin_key_1: PublicKey,
350 pub bitcoin_key_2: PublicKey,
352 #[derive(PartialEq, Clone)]
353 pub struct ChannelAnnouncement {
354 pub node_signature_1: Signature,
355 pub node_signature_2: Signature,
356 pub bitcoin_signature_1: Signature,
357 pub bitcoin_signature_2: Signature,
358 pub contents: UnsignedChannelAnnouncement,
361 #[derive(PartialEq, Clone)]
362 pub struct UnsignedChannelUpdate {
363 pub chain_hash: Sha256dHash,
364 pub short_channel_id: u64,
367 pub cltv_expiry_delta: u16,
368 pub htlc_minimum_msat: u64,
369 pub fee_base_msat: u32,
370 pub fee_proportional_millionths: u32,
372 #[derive(PartialEq, Clone)]
373 pub struct ChannelUpdate {
374 pub signature: Signature,
375 pub contents: UnsignedChannelUpdate,
378 /// Used to put an error message in a HandleError
379 pub enum ErrorAction {
380 /// The peer took some action which made us think they were useless. Disconnect them.
382 msg: Option<ErrorMessage>
384 /// The peer did something harmless that we weren't able to process, just log and ignore
386 /// The peer did something incorrect. Tell them.
392 pub struct HandleError { //TODO: rename me
393 pub err: &'static str,
394 pub action: Option<ErrorAction>, //TODO: Make this required
397 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
398 /// transaction updates if they were pending.
399 pub struct CommitmentUpdate {
400 pub update_add_htlcs: Vec<UpdateAddHTLC>,
401 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
402 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
403 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
404 pub commitment_signed: CommitmentSigned,
407 pub enum HTLCFailChannelUpdate {
408 ChannelUpdateMessage {
412 short_channel_id: u64,
416 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
417 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
418 /// paralell when the two calls have the same their_node_id.
419 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
421 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
422 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
423 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
424 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
425 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
428 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
429 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
432 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
433 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
434 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
435 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
436 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
437 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
439 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
441 // Channel-to-announce:
442 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
445 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
446 /// is believed to be possible in the future (eg they're sending us messages we don't
447 /// understand or indicate they require unknown feature bits), no_connection_possible is set
448 /// and any outstanding channels should be failed.
449 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
451 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
454 pub trait RoutingMessageHandler : Send + Sync {
455 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
456 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
457 /// or returning an Err otherwise.
458 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
459 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
460 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
463 pub struct OnionRealm0HopData {
464 pub short_channel_id: u64,
465 pub amt_to_forward: u64,
466 pub outgoing_cltv_value: u32,
467 // 12 bytes of 0-padding
470 pub struct OnionHopData {
472 pub data: OnionRealm0HopData,
475 unsafe impl internal_traits::NoDealloc for OnionHopData{}
478 pub struct OnionPacket {
480 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
481 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
482 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
483 pub public_key: Result<PublicKey, secp256k1::Error>,
484 pub hop_data: [u8; 20*65],
488 pub struct DecodedOnionErrorPacket {
490 pub failuremsg: Vec<u8>,
495 pub struct OnionErrorPacket {
496 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
497 // (TODO) We limit it in decode to much lower...
501 impl Error for DecodeError {
502 fn description(&self) -> &str {
504 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
505 DecodeError::BadPublicKey => "Invalid public key in packet",
506 DecodeError::BadSignature => "Invalid signature in packet",
507 DecodeError::BadText => "Invalid text in packet",
508 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
509 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
510 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
514 impl fmt::Display for DecodeError {
515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516 f.write_str(self.description())
520 impl fmt::Debug for HandleError {
521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522 f.write_str(self.err)
526 macro_rules! secp_pubkey {
527 ( $ctx: expr, $slice: expr ) => {
528 match PublicKey::from_slice($ctx, $slice) {
530 Err(_) => return Err(DecodeError::BadPublicKey)
535 macro_rules! secp_signature {
536 ( $ctx: expr, $slice: expr ) => {
537 match Signature::from_compact($ctx, $slice) {
539 Err(_) => return Err(DecodeError::BadSignature)
544 impl MsgDecodable for LocalFeatures {
545 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
546 if v.len() < 2 { return Err(DecodeError::ShortRead); }
547 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
548 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
549 let mut flags = Vec::with_capacity(len);
550 flags.extend_from_slice(&v[2..2 + len]);
556 impl MsgEncodable for LocalFeatures {
557 fn encode(&self) -> Vec<u8> {
558 let mut res = Vec::with_capacity(self.flags.len() + 2);
559 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
560 res.extend_from_slice(&self.flags[..]);
563 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
566 impl MsgDecodable for GlobalFeatures {
567 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
568 if v.len() < 2 { return Err(DecodeError::ShortRead); }
569 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
570 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
571 let mut flags = Vec::with_capacity(len);
572 flags.extend_from_slice(&v[2..2 + len]);
578 impl MsgEncodable for GlobalFeatures {
579 fn encode(&self) -> Vec<u8> {
580 let mut res = Vec::with_capacity(self.flags.len() + 2);
581 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
582 res.extend_from_slice(&self.flags[..]);
585 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
588 impl MsgDecodable for Init {
589 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
590 let global_features = GlobalFeatures::decode(v)?;
591 if v.len() < global_features.flags.len() + 4 {
592 return Err(DecodeError::ShortRead);
594 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
596 global_features: global_features,
597 local_features: local_features,
601 impl MsgEncodable for Init {
602 fn encode(&self) -> Vec<u8> {
603 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
604 res.extend_from_slice(&self.global_features.encode()[..]);
605 res.extend_from_slice(&self.local_features.encode()[..]);
610 impl MsgDecodable for Ping {
611 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
613 return Err(DecodeError::ShortRead);
615 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
616 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
617 if v.len() < 4 + byteslen as usize {
618 return Err(DecodeError::ShortRead);
626 impl MsgEncodable for Ping {
627 fn encode(&self) -> Vec<u8> {
628 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
629 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
630 res.resize(2 + self.byteslen as usize, 0);
635 impl MsgDecodable for Pong {
636 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
638 return Err(DecodeError::ShortRead);
640 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
641 if v.len() < 2 + byteslen as usize {
642 return Err(DecodeError::ShortRead);
649 impl MsgEncodable for Pong {
650 fn encode(&self) -> Vec<u8> {
651 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
652 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
653 res.resize(2 + self.byteslen as usize, 0);
658 impl MsgDecodable for OpenChannel {
659 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
660 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
661 return Err(DecodeError::ShortRead);
663 let ctx = Secp256k1::without_caps();
665 let mut shutdown_scriptpubkey = None;
667 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
668 if v.len() < 321+len {
669 return Err(DecodeError::ShortRead);
671 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
675 chain_hash: deserialize(&v[0..32]).unwrap(),
676 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
677 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
678 push_msat: byte_utils::slice_to_be64(&v[72..80]),
679 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
680 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
681 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
682 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
683 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
684 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
685 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
686 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
687 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
688 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
689 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
690 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
691 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
692 channel_flags: v[318],
693 shutdown_scriptpubkey: shutdown_scriptpubkey
697 impl MsgEncodable for OpenChannel {
698 fn encode(&self) -> Vec<u8> {
699 let mut res = match &self.shutdown_scriptpubkey {
700 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
701 &None => Vec::with_capacity(319),
703 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
704 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
705 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
706 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
707 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
708 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
709 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
710 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
711 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
712 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
713 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
714 res.extend_from_slice(&self.funding_pubkey.serialize());
715 res.extend_from_slice(&self.revocation_basepoint.serialize());
716 res.extend_from_slice(&self.payment_basepoint.serialize());
717 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
718 res.extend_from_slice(&self.htlc_basepoint.serialize());
719 res.extend_from_slice(&self.first_per_commitment_point.serialize());
720 res.push(self.channel_flags);
721 if let &Some(ref script) = &self.shutdown_scriptpubkey {
722 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
723 res.extend_from_slice(&script[..]);
729 impl MsgDecodable for AcceptChannel {
730 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
731 if v.len() < 32+4*8+4+2*2+6*33 {
732 return Err(DecodeError::ShortRead);
734 let ctx = Secp256k1::without_caps();
736 let mut shutdown_scriptpubkey = None;
738 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
739 if v.len() < 272+len {
740 return Err(DecodeError::ShortRead);
742 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
745 let mut temporary_channel_id = [0; 32];
746 temporary_channel_id[..].copy_from_slice(&v[0..32]);
748 temporary_channel_id,
749 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
750 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
751 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
752 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
753 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
754 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
755 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
756 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
757 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
758 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
759 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
760 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
761 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
762 shutdown_scriptpubkey: shutdown_scriptpubkey
766 impl MsgEncodable for AcceptChannel {
767 fn encode(&self) -> Vec<u8> {
768 let mut res = match &self.shutdown_scriptpubkey {
769 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
770 &None => Vec::with_capacity(270),
772 res.extend_from_slice(&self.temporary_channel_id);
773 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
774 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
775 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
776 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
777 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
778 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
779 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
780 res.extend_from_slice(&self.funding_pubkey.serialize());
781 res.extend_from_slice(&self.revocation_basepoint.serialize());
782 res.extend_from_slice(&self.payment_basepoint.serialize());
783 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
784 res.extend_from_slice(&self.htlc_basepoint.serialize());
785 res.extend_from_slice(&self.first_per_commitment_point.serialize());
786 if let &Some(ref script) = &self.shutdown_scriptpubkey {
787 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
788 res.extend_from_slice(&script[..]);
794 impl MsgDecodable for FundingCreated {
795 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
796 if v.len() < 32+32+2+64 {
797 return Err(DecodeError::ShortRead);
799 let ctx = Secp256k1::without_caps();
800 let mut temporary_channel_id = [0; 32];
801 temporary_channel_id[..].copy_from_slice(&v[0..32]);
803 temporary_channel_id,
804 funding_txid: deserialize(&v[32..64]).unwrap(),
805 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
806 signature: secp_signature!(&ctx, &v[66..130]),
810 impl MsgEncodable for FundingCreated {
811 fn encode(&self) -> Vec<u8> {
812 let mut res = Vec::with_capacity(32+32+2+64);
813 res.extend_from_slice(&self.temporary_channel_id);
814 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
815 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
816 let secp_ctx = Secp256k1::without_caps();
817 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
822 impl MsgDecodable for FundingSigned {
823 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
825 return Err(DecodeError::ShortRead);
827 let ctx = Secp256k1::without_caps();
828 let mut channel_id = [0; 32];
829 channel_id[..].copy_from_slice(&v[0..32]);
832 signature: secp_signature!(&ctx, &v[32..96]),
836 impl MsgEncodable for FundingSigned {
837 fn encode(&self) -> Vec<u8> {
838 let mut res = Vec::with_capacity(32+64);
839 res.extend_from_slice(&self.channel_id);
840 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
845 impl MsgDecodable for FundingLocked {
846 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
848 return Err(DecodeError::ShortRead);
850 let ctx = Secp256k1::without_caps();
851 let mut channel_id = [0; 32];
852 channel_id[..].copy_from_slice(&v[0..32]);
855 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
859 impl MsgEncodable for FundingLocked {
860 fn encode(&self) -> Vec<u8> {
861 let mut res = Vec::with_capacity(32+33);
862 res.extend_from_slice(&self.channel_id);
863 res.extend_from_slice(&self.next_per_commitment_point.serialize());
868 impl MsgDecodable for Shutdown {
869 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
870 if v.len() < 32 + 2 {
871 return Err(DecodeError::ShortRead);
873 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
874 if v.len() < 32 + 2 + scriptlen {
875 return Err(DecodeError::ShortRead);
877 let mut channel_id = [0; 32];
878 channel_id[..].copy_from_slice(&v[0..32]);
881 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
885 impl MsgEncodable for Shutdown {
886 fn encode(&self) -> Vec<u8> {
887 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
888 res.extend_from_slice(&self.channel_id);
889 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
890 res.extend_from_slice(&self.scriptpubkey[..]);
895 impl MsgDecodable for ClosingSigned {
896 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
897 if v.len() < 32 + 8 + 64 {
898 return Err(DecodeError::ShortRead);
900 let secp_ctx = Secp256k1::without_caps();
901 let mut channel_id = [0; 32];
902 channel_id[..].copy_from_slice(&v[0..32]);
905 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
906 signature: secp_signature!(&secp_ctx, &v[40..104]),
910 impl MsgEncodable for ClosingSigned {
911 fn encode(&self) -> Vec<u8> {
912 let mut res = Vec::with_capacity(32+8+64);
913 res.extend_from_slice(&self.channel_id);
914 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
915 let secp_ctx = Secp256k1::without_caps();
916 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
921 impl MsgDecodable for UpdateAddHTLC {
922 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
923 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
924 return Err(DecodeError::ShortRead);
926 let mut channel_id = [0; 32];
927 channel_id[..].copy_from_slice(&v[0..32]);
928 let mut payment_hash = [0; 32];
929 payment_hash.copy_from_slice(&v[48..80]);
932 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
933 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
935 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
936 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
940 impl MsgEncodable for UpdateAddHTLC {
941 fn encode(&self) -> Vec<u8> {
942 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
943 res.extend_from_slice(&self.channel_id);
944 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
945 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
946 res.extend_from_slice(&self.payment_hash);
947 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
948 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
953 impl MsgDecodable for UpdateFulfillHTLC {
954 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
955 if v.len() < 32+8+32 {
956 return Err(DecodeError::ShortRead);
958 let mut channel_id = [0; 32];
959 channel_id[..].copy_from_slice(&v[0..32]);
960 let mut payment_preimage = [0; 32];
961 payment_preimage.copy_from_slice(&v[40..72]);
964 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
969 impl MsgEncodable for UpdateFulfillHTLC {
970 fn encode(&self) -> Vec<u8> {
971 let mut res = Vec::with_capacity(32+8+32);
972 res.extend_from_slice(&self.channel_id);
973 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
974 res.extend_from_slice(&self.payment_preimage);
979 impl MsgDecodable for UpdateFailHTLC {
980 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
982 return Err(DecodeError::ShortRead);
984 let mut channel_id = [0; 32];
985 channel_id[..].copy_from_slice(&v[0..32]);
988 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
989 reason: OnionErrorPacket::decode(&v[40..])?,
993 impl MsgEncodable for UpdateFailHTLC {
994 fn encode(&self) -> Vec<u8> {
995 let reason = self.reason.encode();
996 let mut res = Vec::with_capacity(32+8+reason.len());
997 res.extend_from_slice(&self.channel_id);
998 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
999 res.extend_from_slice(&reason[..]);
1004 impl MsgDecodable for UpdateFailMalformedHTLC {
1005 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1006 if v.len() < 32+8+32+2 {
1007 return Err(DecodeError::ShortRead);
1009 let mut channel_id = [0; 32];
1010 channel_id[..].copy_from_slice(&v[0..32]);
1011 let mut sha256_of_onion = [0; 32];
1012 sha256_of_onion.copy_from_slice(&v[40..72]);
1015 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1017 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1021 impl MsgEncodable for UpdateFailMalformedHTLC {
1022 fn encode(&self) -> Vec<u8> {
1023 let mut res = Vec::with_capacity(32+8+32+2);
1024 res.extend_from_slice(&self.channel_id);
1025 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1026 res.extend_from_slice(&self.sha256_of_onion);
1027 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1032 impl MsgDecodable for CommitmentSigned {
1033 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1034 if v.len() < 32+64+2 {
1035 return Err(DecodeError::ShortRead);
1037 let mut channel_id = [0; 32];
1038 channel_id[..].copy_from_slice(&v[0..32]);
1040 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1041 if v.len() < 32+64+2+htlcs*64 {
1042 return Err(DecodeError::ShortRead);
1044 let mut htlc_signatures = Vec::with_capacity(htlcs);
1045 let secp_ctx = Secp256k1::without_caps();
1047 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1051 signature: secp_signature!(&secp_ctx, &v[32..96]),
1056 impl MsgEncodable for CommitmentSigned {
1057 fn encode(&self) -> Vec<u8> {
1058 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1059 res.extend_from_slice(&self.channel_id);
1060 let secp_ctx = Secp256k1::without_caps();
1061 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1062 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1063 for i in 0..self.htlc_signatures.len() {
1064 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1070 impl MsgDecodable for RevokeAndACK {
1071 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1072 if v.len() < 32+32+33 {
1073 return Err(DecodeError::ShortRead);
1075 let mut channel_id = [0; 32];
1076 channel_id[..].copy_from_slice(&v[0..32]);
1077 let mut per_commitment_secret = [0; 32];
1078 per_commitment_secret.copy_from_slice(&v[32..64]);
1079 let secp_ctx = Secp256k1::without_caps();
1082 per_commitment_secret,
1083 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1087 impl MsgEncodable for RevokeAndACK {
1088 fn encode(&self) -> Vec<u8> {
1089 let mut res = Vec::with_capacity(32+32+33);
1090 res.extend_from_slice(&self.channel_id);
1091 res.extend_from_slice(&self.per_commitment_secret);
1092 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1097 impl MsgDecodable for UpdateFee {
1098 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1100 return Err(DecodeError::ShortRead);
1102 let mut channel_id = [0; 32];
1103 channel_id[..].copy_from_slice(&v[0..32]);
1106 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1110 impl MsgEncodable for UpdateFee {
1111 fn encode(&self) -> Vec<u8> {
1112 let mut res = Vec::with_capacity(32+4);
1113 res.extend_from_slice(&self.channel_id);
1114 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1119 impl MsgDecodable for ChannelReestablish {
1120 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1121 if v.len() < 32+2*8+33 {
1122 return Err(DecodeError::ShortRead);
1125 let your_last_per_commitment_secret = if v.len() > 32+2*8+33 {
1126 if v.len() < 32+2*8+33 + 32 {
1127 return Err(DecodeError::ShortRead);
1129 let mut inner_array = [0; 32];
1130 inner_array.copy_from_slice(&v[48..48+32]);
1134 let option_size = match &your_last_per_commitment_secret {
1135 &Some(ref _ary) => 32,
1139 channel_id: deserialize(&v[0..32]).unwrap(),
1140 next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1141 next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1142 your_last_per_commitment_secret: your_last_per_commitment_secret,
1143 my_current_per_commitment_point: {
1144 let ctx = Secp256k1::without_caps();
1145 secp_pubkey!(&ctx, &v[48+option_size..48+option_size+33])
1150 impl MsgEncodable for ChannelReestablish {
1151 fn encode(&self) -> Vec<u8> {
1152 let mut res = Vec::with_capacity(if self.your_last_per_commitment_secret.is_some() { 32+2*3+33 + 32 } else { 32+2*8+33 });
1154 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1155 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1156 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1158 if let &Some(ref ary) = &self.your_last_per_commitment_secret {
1159 res.extend_from_slice(&ary[..]);
1162 res.extend_from_slice(&self.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();
1376 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1377 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1378 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1379 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1380 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1381 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1385 impl MsgEncodable for UnsignedChannelAnnouncement {
1386 fn encode(&self) -> Vec<u8> {
1387 let features = self.features.encode();
1388 let mut res = Vec::with_capacity(172 + features.len());
1389 res.extend_from_slice(&features[..]);
1390 res.extend_from_slice(&self.chain_hash[..]);
1391 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1392 res.extend_from_slice(&self.node_id_1.serialize());
1393 res.extend_from_slice(&self.node_id_2.serialize());
1394 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1395 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1400 impl MsgDecodable for ChannelAnnouncement {
1401 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1403 return Err(DecodeError::ShortRead);
1405 let secp_ctx = Secp256k1::without_caps();
1407 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1408 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1409 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1410 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1411 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1415 impl MsgEncodable for ChannelAnnouncement {
1416 fn encode(&self) -> Vec<u8> {
1417 let secp_ctx = Secp256k1::without_caps();
1418 let contents = self.contents.encode();
1419 let mut res = Vec::with_capacity(64 + contents.len());
1420 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1421 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1422 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1423 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1424 res.extend_from_slice(&contents);
1429 impl MsgDecodable for UnsignedChannelUpdate {
1430 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1431 if v.len() < 32+8+4+2+2+8+4+4 {
1432 return Err(DecodeError::ShortRead);
1435 chain_hash: deserialize(&v[0..32]).unwrap(),
1436 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1437 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1438 flags: byte_utils::slice_to_be16(&v[44..46]),
1439 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1440 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1441 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1442 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1446 impl MsgEncodable for UnsignedChannelUpdate {
1447 fn encode(&self) -> Vec<u8> {
1448 let mut res = Vec::with_capacity(64);
1449 res.extend_from_slice(&self.chain_hash[..]);
1450 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1451 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1452 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1453 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1454 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1455 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1456 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1461 impl MsgDecodable for ChannelUpdate {
1462 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1464 return Err(DecodeError::ShortRead);
1466 let secp_ctx = Secp256k1::without_caps();
1468 signature: secp_signature!(&secp_ctx, &v[0..64]),
1469 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1473 impl MsgEncodable for ChannelUpdate {
1474 fn encode(&self) -> Vec<u8> {
1475 let mut res = Vec::with_capacity(128);
1476 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1477 res.extend_from_slice(&self.contents.encode()[..]);
1482 impl MsgDecodable for OnionRealm0HopData {
1483 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1485 return Err(DecodeError::ShortRead);
1487 Ok(OnionRealm0HopData {
1488 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1489 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1490 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1494 impl MsgEncodable for OnionRealm0HopData {
1495 fn encode(&self) -> Vec<u8> {
1496 let mut res = Vec::with_capacity(32);
1497 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1498 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1499 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1505 impl MsgDecodable for OnionHopData {
1506 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1508 return Err(DecodeError::ShortRead);
1512 return Err(DecodeError::UnknownRealmByte);
1514 let mut hmac = [0; 32];
1515 hmac[..].copy_from_slice(&v[33..65]);
1518 data: OnionRealm0HopData::decode(&v[1..33])?,
1523 impl MsgEncodable for OnionHopData {
1524 fn encode(&self) -> Vec<u8> {
1525 let mut res = Vec::with_capacity(65);
1526 res.push(self.realm);
1527 res.extend_from_slice(&self.data.encode()[..]);
1528 res.extend_from_slice(&self.hmac);
1533 impl MsgDecodable for OnionPacket {
1534 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1535 if v.len() < 1+33+20*65+32 {
1536 return Err(DecodeError::ShortRead);
1538 let mut hop_data = [0; 20*65];
1539 hop_data.copy_from_slice(&v[34..1334]);
1540 let mut hmac = [0; 32];
1541 hmac.copy_from_slice(&v[1334..1366]);
1542 let secp_ctx = Secp256k1::without_caps();
1545 public_key: PublicKey::from_slice(&secp_ctx, &v[1..34]),
1551 impl MsgEncodable for OnionPacket {
1552 fn encode(&self) -> Vec<u8> {
1553 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1554 res.push(self.version);
1555 match self.public_key {
1556 Ok(pubkey) => res.extend_from_slice(&pubkey.serialize()),
1557 Err(_) => res.extend_from_slice(&[0; 33]),
1559 res.extend_from_slice(&self.hop_data);
1560 res.extend_from_slice(&self.hmac);
1565 impl MsgDecodable for DecodedOnionErrorPacket {
1566 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1567 if v.len() < 32 + 4 {
1568 return Err(DecodeError::ShortRead);
1570 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1571 if v.len() < 32 + 4 + failuremsg_len {
1572 return Err(DecodeError::ShortRead);
1574 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1575 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1576 return Err(DecodeError::ShortRead);
1579 let mut hmac = [0; 32];
1580 hmac.copy_from_slice(&v[0..32]);
1583 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1584 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1588 impl MsgEncodable for DecodedOnionErrorPacket {
1589 fn encode(&self) -> Vec<u8> {
1590 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1591 res.extend_from_slice(&self.hmac);
1592 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1593 res.extend_from_slice(&self.failuremsg);
1594 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1595 res.extend_from_slice(&self.pad);
1600 impl MsgDecodable for OnionErrorPacket {
1601 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1603 return Err(DecodeError::ShortRead);
1605 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1606 if v.len() < 2 + len {
1607 return Err(DecodeError::ShortRead);
1610 data: v[2..len+2].to_vec(),
1614 impl MsgEncodable for OnionErrorPacket {
1615 fn encode(&self) -> Vec<u8> {
1616 let mut res = Vec::with_capacity(2 + self.data.len());
1617 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1618 res.extend_from_slice(&self.data);
1623 impl MsgEncodable for ErrorMessage {
1624 fn encode(&self) -> Vec<u8> {
1625 let mut res = Vec::with_capacity(34 + self.data.len());
1626 res.extend_from_slice(&self.channel_id);
1627 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1628 res.extend_from_slice(&self.data.as_bytes());
1632 impl MsgDecodable for ErrorMessage {
1633 fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1635 return Err(DecodeError::ShortRead);
1637 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1638 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1639 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1641 Err(_) => return Err(DecodeError::BadText),
1643 let mut channel_id = [0; 32];
1644 channel_id[..].copy_from_slice(&v[0..32]);
1655 use ln::msgs::MsgEncodable;
1657 use secp256k1::key::{PublicKey,SecretKey};
1658 use secp256k1::Secp256k1;
1661 fn encoding_channel_reestablish_no_secret() {
1663 let secp_ctx = Secp256k1::new();
1664 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1667 let cr = msgs::ChannelReestablish {
1668 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],
1669 next_local_commitment_number: 3,
1670 next_remote_commitment_number: 4,
1671 your_last_per_commitment_secret: None,
1672 my_current_per_commitment_point: public_key,
1675 let encoded_value = cr.encode();
1678 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, 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]
1683 fn encoding_channel_reestablish_with_secret() {
1685 let secp_ctx = Secp256k1::new();
1686 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1689 let cr = msgs::ChannelReestablish {
1690 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],
1691 next_local_commitment_number: 3,
1692 next_remote_commitment_number: 4,
1693 your_last_per_commitment_secret: Some([9; 32]),
1694 my_current_per_commitment_point: public_key,
1697 let encoded_value = cr.encode();
1700 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]