1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use bitcoin::util::hash::Sha256dHash;
4 use bitcoin::network::serialize::{deserialize,serialize};
5 use bitcoin::blockdata::script::Script;
9 use std::result::Result;
11 use util::{byte_utils, internal_traits, events};
13 pub trait MsgEncodable {
14 fn encode(&self) -> Vec<u8>;
16 fn encoded_len(&self) -> usize { self.encode().len() }
18 fn encode_with_len(&self) -> Vec<u8> {
19 let enc = self.encode();
20 let mut res = Vec::with_capacity(enc.len() + 2);
21 res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
22 res.extend_from_slice(&enc);
27 pub enum DecodeError {
28 /// Unknown realm byte in an OnionHopData packet
30 /// Failed to decode a public key (ie it's invalid)
32 /// Failed to decode a signature (ie it's invalid)
34 /// Value expected to be text wasn't decodable as text
38 /// node_announcement included more than one address of a given type!
39 ExtraAddressesPerType,
40 /// A length descriptor in the packet didn't describe the later data correctly
41 /// (currently only generated in node_announcement)
44 pub trait MsgDecodable: Sized {
45 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
48 /// Tracks localfeatures which are only in init messages
49 #[derive(Clone, PartialEq)]
50 pub struct LocalFeatures {
55 pub fn new() -> LocalFeatures {
61 pub fn supports_data_loss_protect(&self) -> bool {
62 self.flags.len() > 0 && (self.flags[0] & 3) != 0
64 pub fn requires_data_loss_protect(&self) -> bool {
65 self.flags.len() > 0 && (self.flags[0] & 1) != 0
68 pub fn initial_routing_sync(&self) -> bool {
69 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
71 pub fn set_initial_routing_sync(&mut self) {
72 if self.flags.len() == 0 {
73 self.flags.resize(1, 1 << 3);
75 self.flags[0] |= 1 << 3;
79 pub fn supports_upfront_shutdown_script(&self) -> bool {
80 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
82 pub fn requires_upfront_shutdown_script(&self) -> bool {
83 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
86 pub fn requires_unknown_bits(&self) -> bool {
87 for (idx, &byte) in self.flags.iter().enumerate() {
88 if idx != 0 && (byte & 0x55) != 0 {
90 } else if idx == 0 && (byte & 0x14) != 0 {
97 pub fn supports_unknown_bits(&self) -> bool {
98 for (idx, &byte) in self.flags.iter().enumerate() {
99 if idx != 0 && byte != 0 {
101 } else if idx == 0 && (byte & 0xc4) != 0 {
109 /// Tracks globalfeatures which are in init messages and routing announcements
110 #[derive(Clone, PartialEq)]
111 pub struct GlobalFeatures {
115 impl GlobalFeatures {
116 pub fn new() -> GlobalFeatures {
122 pub fn requires_unknown_bits(&self) -> bool {
123 for &byte in self.flags.iter() {
124 if (byte & 0x55) != 0 {
131 pub fn supports_unknown_bits(&self) -> bool {
132 for &byte in self.flags.iter() {
142 pub global_features: GlobalFeatures,
143 pub local_features: LocalFeatures,
146 pub struct ErrorMessage {
147 pub channel_id: [u8; 32],
160 pub struct OpenChannel {
161 pub chain_hash: Sha256dHash,
162 pub temporary_channel_id: [u8; 32],
163 pub funding_satoshis: u64,
165 pub dust_limit_satoshis: u64,
166 pub max_htlc_value_in_flight_msat: u64,
167 pub channel_reserve_satoshis: u64,
168 pub htlc_minimum_msat: u64,
169 pub feerate_per_kw: u32,
170 pub to_self_delay: u16,
171 pub max_accepted_htlcs: u16,
172 pub funding_pubkey: PublicKey,
173 pub revocation_basepoint: PublicKey,
174 pub payment_basepoint: PublicKey,
175 pub delayed_payment_basepoint: PublicKey,
176 pub htlc_basepoint: PublicKey,
177 pub first_per_commitment_point: PublicKey,
178 pub channel_flags: u8,
179 pub shutdown_scriptpubkey: Option<Script>,
182 pub struct AcceptChannel {
183 pub temporary_channel_id: [u8; 32],
184 pub dust_limit_satoshis: u64,
185 pub max_htlc_value_in_flight_msat: u64,
186 pub channel_reserve_satoshis: u64,
187 pub htlc_minimum_msat: u64,
188 pub minimum_depth: u32,
189 pub to_self_delay: u16,
190 pub max_accepted_htlcs: u16,
191 pub funding_pubkey: PublicKey,
192 pub revocation_basepoint: PublicKey,
193 pub payment_basepoint: PublicKey,
194 pub delayed_payment_basepoint: PublicKey,
195 pub htlc_basepoint: PublicKey,
196 pub first_per_commitment_point: PublicKey,
197 pub shutdown_scriptpubkey: Option<Script>,
200 pub struct FundingCreated {
201 pub temporary_channel_id: [u8; 32],
202 pub funding_txid: Sha256dHash,
203 pub funding_output_index: u16,
204 pub signature: Signature,
207 pub struct FundingSigned {
208 pub channel_id: [u8; 32],
209 pub signature: Signature,
212 pub struct FundingLocked {
213 pub channel_id: [u8; 32],
214 pub next_per_commitment_point: PublicKey,
217 pub struct Shutdown {
218 pub channel_id: [u8; 32],
219 pub scriptpubkey: Script,
222 pub struct ClosingSigned {
223 pub channel_id: [u8; 32],
224 pub fee_satoshis: u64,
225 pub signature: Signature,
229 pub struct UpdateAddHTLC {
230 pub channel_id: [u8; 32],
232 pub amount_msat: u64,
233 pub payment_hash: [u8; 32],
234 pub cltv_expiry: u32,
235 pub onion_routing_packet: OnionPacket,
239 pub struct UpdateFulfillHTLC {
240 pub channel_id: [u8; 32],
242 pub payment_preimage: [u8; 32],
246 pub struct UpdateFailHTLC {
247 pub channel_id: [u8; 32],
249 pub reason: OnionErrorPacket,
253 pub struct UpdateFailMalformedHTLC {
254 pub channel_id: [u8; 32],
256 pub sha256_of_onion: [u8; 32],
257 pub failure_code: u16,
261 pub struct CommitmentSigned {
262 pub channel_id: [u8; 32],
263 pub signature: Signature,
264 pub htlc_signatures: Vec<Signature>,
267 pub struct RevokeAndACK {
268 pub channel_id: [u8; 32],
269 pub per_commitment_secret: [u8; 32],
270 pub next_per_commitment_point: PublicKey,
273 pub struct UpdateFee {
274 pub channel_id: [u8; 32],
275 pub feerate_per_kw: u32,
278 pub struct ChannelReestablish {
279 pub channel_id: [u8; 32],
280 pub next_local_commitment_number: u64,
281 pub next_remote_commitment_number: u64,
282 pub your_last_per_commitment_secret: Option<[u8; 32]>,
283 pub my_current_per_commitment_point: PublicKey,
287 pub struct AnnouncementSignatures {
288 pub channel_id: [u8; 32],
289 pub short_channel_id: u64,
290 pub node_signature: Signature,
291 pub bitcoin_signature: Signature,
295 pub enum NetAddress {
309 ed25519_pubkey: [u8; 32],
316 fn get_id(&self) -> u8 {
318 &NetAddress::IPv4 {..} => { 1 },
319 &NetAddress::IPv6 {..} => { 2 },
320 &NetAddress::OnionV2 {..} => { 3 },
321 &NetAddress::OnionV3 {..} => { 4 },
326 pub struct UnsignedNodeAnnouncement {
327 pub features: GlobalFeatures,
329 pub node_id: PublicKey,
332 /// List of addresses on which this node is reachable. Note that you may only have up to one
333 /// address of each type, if you have more, they may be silently discarded or we may panic!
334 pub addresses: Vec<NetAddress>,
336 pub struct NodeAnnouncement {
337 pub signature: Signature,
338 pub contents: UnsignedNodeAnnouncement,
341 #[derive(PartialEq, Clone)]
342 pub struct UnsignedChannelAnnouncement {
343 pub features: GlobalFeatures,
344 pub chain_hash: Sha256dHash,
345 pub short_channel_id: u64,
346 pub node_id_1: PublicKey,
347 pub node_id_2: PublicKey,
348 pub bitcoin_key_1: PublicKey,
349 pub bitcoin_key_2: PublicKey,
351 #[derive(PartialEq, Clone)]
352 pub struct ChannelAnnouncement {
353 pub node_signature_1: Signature,
354 pub node_signature_2: Signature,
355 pub bitcoin_signature_1: Signature,
356 pub bitcoin_signature_2: Signature,
357 pub contents: UnsignedChannelAnnouncement,
360 #[derive(PartialEq, Clone)]
361 pub struct UnsignedChannelUpdate {
362 pub chain_hash: Sha256dHash,
363 pub short_channel_id: u64,
366 pub cltv_expiry_delta: u16,
367 pub htlc_minimum_msat: u64,
368 pub fee_base_msat: u32,
369 pub fee_proportional_millionths: u32,
371 #[derive(PartialEq, Clone)]
372 pub struct ChannelUpdate {
373 pub signature: Signature,
374 pub contents: UnsignedChannelUpdate,
377 /// Used to put an error message in a HandleError
378 pub enum ErrorAction {
379 /// The peer took some action which made us think they were useless. Disconnect them.
381 msg: Option<ErrorMessage>
383 /// The peer did something harmless that we weren't able to process, just log and ignore
385 /// The peer did something incorrect. Tell them.
391 pub struct HandleError { //TODO: rename me
392 pub err: &'static str,
393 pub action: Option<ErrorAction>, //TODO: Make this required
396 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
397 /// transaction updates if they were pending.
398 pub struct CommitmentUpdate {
399 pub update_add_htlcs: Vec<UpdateAddHTLC>,
400 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
401 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
402 pub commitment_signed: CommitmentSigned,
405 pub enum HTLCFailChannelUpdate {
406 ChannelUpdateMessage {
410 short_channel_id: u64,
414 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
415 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
416 /// paralell when the two calls have the same their_node_id.
417 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
419 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
420 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
421 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
422 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
423 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
426 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
427 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
430 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
431 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
432 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
433 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
434 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
435 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
437 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
439 // Channel-to-announce:
440 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
443 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
444 /// is believed to be possible in the future (eg they're sending us messages we don't
445 /// understand or indicate they require unknown feature bits), no_connection_possible is set
446 /// and any outstanding channels should be failed.
447 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
449 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
452 pub trait RoutingMessageHandler : Send + Sync {
453 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
454 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
455 /// or returning an Err otherwise.
456 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
457 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
458 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
461 pub struct OnionRealm0HopData {
462 pub short_channel_id: u64,
463 pub amt_to_forward: u64,
464 pub outgoing_cltv_value: u32,
465 // 12 bytes of 0-padding
468 pub struct OnionHopData {
470 pub data: OnionRealm0HopData,
473 unsafe impl internal_traits::NoDealloc for OnionHopData{}
476 pub struct OnionPacket {
478 pub public_key: PublicKey,
479 pub hop_data: [u8; 20*65],
483 pub struct DecodedOnionErrorPacket {
485 pub failuremsg: Vec<u8>,
490 pub struct OnionErrorPacket {
491 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
492 // (TODO) We limit it in decode to much lower...
496 impl Error for DecodeError {
497 fn description(&self) -> &str {
499 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
500 DecodeError::BadPublicKey => "Invalid public key in packet",
501 DecodeError::BadSignature => "Invalid signature in packet",
502 DecodeError::BadText => "Invalid text in packet",
503 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
504 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
505 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
509 impl fmt::Display for DecodeError {
510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
511 f.write_str(self.description())
515 impl fmt::Debug for HandleError {
516 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
517 f.write_str(self.err)
521 macro_rules! secp_pubkey {
522 ( $ctx: expr, $slice: expr ) => {
523 match PublicKey::from_slice($ctx, $slice) {
525 Err(_) => return Err(DecodeError::BadPublicKey)
530 macro_rules! secp_signature {
531 ( $ctx: expr, $slice: expr ) => {
532 match Signature::from_compact($ctx, $slice) {
534 Err(_) => return Err(DecodeError::BadSignature)
539 impl MsgDecodable for LocalFeatures {
540 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
541 if v.len() < 2 { return Err(DecodeError::ShortRead); }
542 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
543 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
544 let mut flags = Vec::with_capacity(len);
545 flags.extend_from_slice(&v[2..2 + len]);
551 impl MsgEncodable for LocalFeatures {
552 fn encode(&self) -> Vec<u8> {
553 let mut res = Vec::with_capacity(self.flags.len() + 2);
554 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
555 res.extend_from_slice(&self.flags[..]);
558 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
561 impl MsgDecodable for GlobalFeatures {
562 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
563 if v.len() < 2 { return Err(DecodeError::ShortRead); }
564 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
565 if v.len() < len + 2 { return Err(DecodeError::ShortRead); }
566 let mut flags = Vec::with_capacity(len);
567 flags.extend_from_slice(&v[2..2 + len]);
573 impl MsgEncodable for GlobalFeatures {
574 fn encode(&self) -> Vec<u8> {
575 let mut res = Vec::with_capacity(self.flags.len() + 2);
576 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
577 res.extend_from_slice(&self.flags[..]);
580 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
583 impl MsgDecodable for Init {
584 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
585 let global_features = GlobalFeatures::decode(v)?;
586 if v.len() < global_features.flags.len() + 4 {
587 return Err(DecodeError::ShortRead);
589 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
591 global_features: global_features,
592 local_features: local_features,
596 impl MsgEncodable for Init {
597 fn encode(&self) -> Vec<u8> {
598 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
599 res.extend_from_slice(&self.global_features.encode()[..]);
600 res.extend_from_slice(&self.local_features.encode()[..]);
605 impl MsgDecodable for Ping {
606 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
608 return Err(DecodeError::ShortRead);
610 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
611 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
612 if v.len() < 4 + byteslen as usize {
613 return Err(DecodeError::ShortRead);
621 impl MsgEncodable for Ping {
622 fn encode(&self) -> Vec<u8> {
623 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
624 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
625 res.resize(2 + self.byteslen as usize, 0);
630 impl MsgDecodable for Pong {
631 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
633 return Err(DecodeError::ShortRead);
635 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
636 if v.len() < 2 + byteslen as usize {
637 return Err(DecodeError::ShortRead);
644 impl MsgEncodable for Pong {
645 fn encode(&self) -> Vec<u8> {
646 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
647 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
648 res.resize(2 + self.byteslen as usize, 0);
653 impl MsgDecodable for OpenChannel {
654 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
655 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
656 return Err(DecodeError::ShortRead);
658 let ctx = Secp256k1::without_caps();
660 let mut shutdown_scriptpubkey = None;
662 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
663 if v.len() < 321+len {
664 return Err(DecodeError::ShortRead);
666 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
670 chain_hash: deserialize(&v[0..32]).unwrap(),
671 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
672 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
673 push_msat: byte_utils::slice_to_be64(&v[72..80]),
674 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
675 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
676 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
677 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
678 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
679 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
680 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
681 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
682 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
683 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
684 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
685 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
686 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
687 channel_flags: v[318],
688 shutdown_scriptpubkey: shutdown_scriptpubkey
692 impl MsgEncodable for OpenChannel {
693 fn encode(&self) -> Vec<u8> {
694 let mut res = match &self.shutdown_scriptpubkey {
695 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
696 &None => Vec::with_capacity(319),
698 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
699 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
700 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
701 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
702 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
703 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
704 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
705 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
706 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
707 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
708 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
709 res.extend_from_slice(&self.funding_pubkey.serialize());
710 res.extend_from_slice(&self.revocation_basepoint.serialize());
711 res.extend_from_slice(&self.payment_basepoint.serialize());
712 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
713 res.extend_from_slice(&self.htlc_basepoint.serialize());
714 res.extend_from_slice(&self.first_per_commitment_point.serialize());
715 res.push(self.channel_flags);
716 if let &Some(ref script) = &self.shutdown_scriptpubkey {
717 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
718 res.extend_from_slice(&script[..]);
724 impl MsgDecodable for AcceptChannel {
725 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
726 if v.len() < 32+4*8+4+2*2+6*33 {
727 return Err(DecodeError::ShortRead);
729 let ctx = Secp256k1::without_caps();
731 let mut shutdown_scriptpubkey = None;
733 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
734 if v.len() < 272+len {
735 return Err(DecodeError::ShortRead);
737 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
740 let mut temporary_channel_id = [0; 32];
741 temporary_channel_id[..].copy_from_slice(&v[0..32]);
743 temporary_channel_id,
744 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
745 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
746 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
747 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
748 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
749 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
750 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
751 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
752 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
753 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
754 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
755 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
756 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
757 shutdown_scriptpubkey: shutdown_scriptpubkey
761 impl MsgEncodable for AcceptChannel {
762 fn encode(&self) -> Vec<u8> {
763 let mut res = match &self.shutdown_scriptpubkey {
764 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
765 &None => Vec::with_capacity(270),
767 res.extend_from_slice(&self.temporary_channel_id);
768 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
769 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
770 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
771 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
772 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
773 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
774 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
775 res.extend_from_slice(&self.funding_pubkey.serialize());
776 res.extend_from_slice(&self.revocation_basepoint.serialize());
777 res.extend_from_slice(&self.payment_basepoint.serialize());
778 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
779 res.extend_from_slice(&self.htlc_basepoint.serialize());
780 res.extend_from_slice(&self.first_per_commitment_point.serialize());
781 if let &Some(ref script) = &self.shutdown_scriptpubkey {
782 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
783 res.extend_from_slice(&script[..]);
789 impl MsgDecodable for FundingCreated {
790 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
791 if v.len() < 32+32+2+64 {
792 return Err(DecodeError::ShortRead);
794 let ctx = Secp256k1::without_caps();
795 let mut temporary_channel_id = [0; 32];
796 temporary_channel_id[..].copy_from_slice(&v[0..32]);
798 temporary_channel_id,
799 funding_txid: deserialize(&v[32..64]).unwrap(),
800 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
801 signature: secp_signature!(&ctx, &v[66..130]),
805 impl MsgEncodable for FundingCreated {
806 fn encode(&self) -> Vec<u8> {
807 let mut res = Vec::with_capacity(32+32+2+64);
808 res.extend_from_slice(&self.temporary_channel_id);
809 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
810 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
811 let secp_ctx = Secp256k1::without_caps();
812 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
817 impl MsgDecodable for FundingSigned {
818 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
820 return Err(DecodeError::ShortRead);
822 let ctx = Secp256k1::without_caps();
823 let mut channel_id = [0; 32];
824 channel_id[..].copy_from_slice(&v[0..32]);
827 signature: secp_signature!(&ctx, &v[32..96]),
831 impl MsgEncodable for FundingSigned {
832 fn encode(&self) -> Vec<u8> {
833 let mut res = Vec::with_capacity(32+64);
834 res.extend_from_slice(&self.channel_id);
835 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
840 impl MsgDecodable for FundingLocked {
841 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
843 return Err(DecodeError::ShortRead);
845 let ctx = Secp256k1::without_caps();
846 let mut channel_id = [0; 32];
847 channel_id[..].copy_from_slice(&v[0..32]);
850 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
854 impl MsgEncodable for FundingLocked {
855 fn encode(&self) -> Vec<u8> {
856 let mut res = Vec::with_capacity(32+33);
857 res.extend_from_slice(&self.channel_id);
858 res.extend_from_slice(&self.next_per_commitment_point.serialize());
863 impl MsgDecodable for Shutdown {
864 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
865 if v.len() < 32 + 2 {
866 return Err(DecodeError::ShortRead);
868 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
869 if v.len() < 32 + 2 + scriptlen {
870 return Err(DecodeError::ShortRead);
872 let mut channel_id = [0; 32];
873 channel_id[..].copy_from_slice(&v[0..32]);
876 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
880 impl MsgEncodable for Shutdown {
881 fn encode(&self) -> Vec<u8> {
882 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
883 res.extend_from_slice(&self.channel_id);
884 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
885 res.extend_from_slice(&self.scriptpubkey[..]);
890 impl MsgDecodable for ClosingSigned {
891 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
892 if v.len() < 32 + 8 + 64 {
893 return Err(DecodeError::ShortRead);
895 let secp_ctx = Secp256k1::without_caps();
896 let mut channel_id = [0; 32];
897 channel_id[..].copy_from_slice(&v[0..32]);
900 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
901 signature: secp_signature!(&secp_ctx, &v[40..104]),
905 impl MsgEncodable for ClosingSigned {
906 fn encode(&self) -> Vec<u8> {
907 let mut res = Vec::with_capacity(32+8+64);
908 res.extend_from_slice(&self.channel_id);
909 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
910 let secp_ctx = Secp256k1::without_caps();
911 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
916 impl MsgDecodable for UpdateAddHTLC {
917 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
918 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
919 return Err(DecodeError::ShortRead);
921 let mut channel_id = [0; 32];
922 channel_id[..].copy_from_slice(&v[0..32]);
923 let mut payment_hash = [0; 32];
924 payment_hash.copy_from_slice(&v[48..80]);
927 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
928 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
930 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
931 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
935 impl MsgEncodable for UpdateAddHTLC {
936 fn encode(&self) -> Vec<u8> {
937 let mut res = Vec::with_capacity(32+8+8+32+4+1366);
938 res.extend_from_slice(&self.channel_id);
939 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
940 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
941 res.extend_from_slice(&self.payment_hash);
942 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
943 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
948 impl MsgDecodable for UpdateFulfillHTLC {
949 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
950 if v.len() < 32+8+32 {
951 return Err(DecodeError::ShortRead);
953 let mut channel_id = [0; 32];
954 channel_id[..].copy_from_slice(&v[0..32]);
955 let mut payment_preimage = [0; 32];
956 payment_preimage.copy_from_slice(&v[40..72]);
959 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
964 impl MsgEncodable for UpdateFulfillHTLC {
965 fn encode(&self) -> Vec<u8> {
966 let mut res = Vec::with_capacity(32+8+32);
967 res.extend_from_slice(&self.channel_id);
968 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
969 res.extend_from_slice(&self.payment_preimage);
974 impl MsgDecodable for UpdateFailHTLC {
975 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
977 return Err(DecodeError::ShortRead);
979 let mut channel_id = [0; 32];
980 channel_id[..].copy_from_slice(&v[0..32]);
983 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
984 reason: OnionErrorPacket::decode(&v[40..])?,
988 impl MsgEncodable for UpdateFailHTLC {
989 fn encode(&self) -> Vec<u8> {
990 let reason = self.reason.encode();
991 let mut res = Vec::with_capacity(32+8+reason.len());
992 res.extend_from_slice(&self.channel_id);
993 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
994 res.extend_from_slice(&reason[..]);
999 impl MsgDecodable for UpdateFailMalformedHTLC {
1000 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1001 if v.len() < 32+8+32+2 {
1002 return Err(DecodeError::ShortRead);
1004 let mut channel_id = [0; 32];
1005 channel_id[..].copy_from_slice(&v[0..32]);
1006 let mut sha256_of_onion = [0; 32];
1007 sha256_of_onion.copy_from_slice(&v[40..72]);
1010 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1012 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1016 impl MsgEncodable for UpdateFailMalformedHTLC {
1017 fn encode(&self) -> Vec<u8> {
1018 let mut res = Vec::with_capacity(32+8+32+2);
1019 res.extend_from_slice(&self.channel_id);
1020 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1021 res.extend_from_slice(&self.sha256_of_onion);
1022 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1027 impl MsgDecodable for CommitmentSigned {
1028 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1029 if v.len() < 32+64+2 {
1030 return Err(DecodeError::ShortRead);
1032 let mut channel_id = [0; 32];
1033 channel_id[..].copy_from_slice(&v[0..32]);
1035 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1036 if v.len() < 32+64+2+htlcs*64 {
1037 return Err(DecodeError::ShortRead);
1039 let mut htlc_signatures = Vec::with_capacity(htlcs);
1040 let secp_ctx = Secp256k1::without_caps();
1042 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1046 signature: secp_signature!(&secp_ctx, &v[32..96]),
1051 impl MsgEncodable for CommitmentSigned {
1052 fn encode(&self) -> Vec<u8> {
1053 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1054 res.extend_from_slice(&self.channel_id);
1055 let secp_ctx = Secp256k1::without_caps();
1056 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1057 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1058 for i in 0..self.htlc_signatures.len() {
1059 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1065 impl MsgDecodable for RevokeAndACK {
1066 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1067 if v.len() < 32+32+33 {
1068 return Err(DecodeError::ShortRead);
1070 let mut channel_id = [0; 32];
1071 channel_id[..].copy_from_slice(&v[0..32]);
1072 let mut per_commitment_secret = [0; 32];
1073 per_commitment_secret.copy_from_slice(&v[32..64]);
1074 let secp_ctx = Secp256k1::without_caps();
1077 per_commitment_secret,
1078 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1082 impl MsgEncodable for RevokeAndACK {
1083 fn encode(&self) -> Vec<u8> {
1084 let mut res = Vec::with_capacity(32+32+33);
1085 res.extend_from_slice(&self.channel_id);
1086 res.extend_from_slice(&self.per_commitment_secret);
1087 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1092 impl MsgDecodable for UpdateFee {
1093 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1095 return Err(DecodeError::ShortRead);
1097 let mut channel_id = [0; 32];
1098 channel_id[..].copy_from_slice(&v[0..32]);
1101 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1105 impl MsgEncodable for UpdateFee {
1106 fn encode(&self) -> Vec<u8> {
1107 let mut res = Vec::with_capacity(32+4);
1108 res.extend_from_slice(&self.channel_id);
1109 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1114 impl MsgDecodable for ChannelReestablish {
1115 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1116 if v.len() < 32+2*8+33 {
1117 return Err(DecodeError::ShortRead);
1120 let your_last_per_commitment_secret = if v.len() > 32+2*8+33 {
1121 if v.len() < 32+2*8+33 + 32 {
1122 return Err(DecodeError::ShortRead);
1124 let mut inner_array = [0; 32];
1125 inner_array.copy_from_slice(&v[48..48+32]);
1129 let option_size = match &your_last_per_commitment_secret {
1130 &Some(ref _ary) => 32,
1134 channel_id: deserialize(&v[0..32]).unwrap(),
1135 next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1136 next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1137 your_last_per_commitment_secret: your_last_per_commitment_secret,
1138 my_current_per_commitment_point: {
1139 let ctx = Secp256k1::without_caps();
1140 secp_pubkey!(&ctx, &v[48+option_size..48+option_size+33])
1145 impl MsgEncodable for ChannelReestablish {
1146 fn encode(&self) -> Vec<u8> {
1147 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 });
1149 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1150 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1151 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1153 if let &Some(ref ary) = &self.your_last_per_commitment_secret {
1154 res.extend_from_slice(&ary[..]);
1157 res.extend_from_slice(&self.my_current_per_commitment_point.serialize());
1162 impl MsgDecodable for AnnouncementSignatures {
1163 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1164 if v.len() < 32+8+64*2 {
1165 return Err(DecodeError::ShortRead);
1167 let secp_ctx = Secp256k1::without_caps();
1168 let mut channel_id = [0; 32];
1169 channel_id[..].copy_from_slice(&v[0..32]);
1172 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1173 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1174 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1178 impl MsgEncodable for AnnouncementSignatures {
1179 fn encode(&self) -> Vec<u8> {
1180 let mut res = Vec::with_capacity(32+8+64*2);
1181 res.extend_from_slice(&self.channel_id);
1182 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1183 let secp_ctx = Secp256k1::without_caps();
1184 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1185 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1190 impl MsgDecodable for UnsignedNodeAnnouncement {
1191 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1192 let features = GlobalFeatures::decode(&v[..])?;
1193 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1194 return Err(DecodeError::ShortRead);
1196 let start = features.encoded_len();
1198 let mut rgb = [0; 3];
1199 rgb.copy_from_slice(&v[start + 37..start + 40]);
1201 let mut alias = [0; 32];
1202 alias.copy_from_slice(&v[start + 40..start + 72]);
1204 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1205 if v.len() < start + 74 + addrlen {
1206 return Err(DecodeError::ShortRead);
1208 let addr_read_limit = start + 74 + addrlen;
1210 let mut addresses = Vec::with_capacity(4);
1211 let mut read_pos = start + 74;
1213 if addr_read_limit <= read_pos { break; }
1215 0 => { read_pos += 1; },
1217 if addresses.len() > 0 {
1218 return Err(DecodeError::ExtraAddressesPerType);
1220 if addr_read_limit < read_pos + 1 + 6 {
1221 return Err(DecodeError::BadLengthDescriptor);
1223 let mut addr = [0; 4];
1224 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1225 addresses.push(NetAddress::IPv4 {
1227 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1232 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1233 return Err(DecodeError::ExtraAddressesPerType);
1235 if addr_read_limit < read_pos + 1 + 18 {
1236 return Err(DecodeError::BadLengthDescriptor);
1238 let mut addr = [0; 16];
1239 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1240 addresses.push(NetAddress::IPv6 {
1242 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1247 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1248 return Err(DecodeError::ExtraAddressesPerType);
1250 if addr_read_limit < read_pos + 1 + 12 {
1251 return Err(DecodeError::BadLengthDescriptor);
1253 let mut addr = [0; 10];
1254 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1255 addresses.push(NetAddress::OnionV2 {
1257 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1262 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1263 return Err(DecodeError::ExtraAddressesPerType);
1265 if addr_read_limit < read_pos + 1 + 37 {
1266 return Err(DecodeError::BadLengthDescriptor);
1268 let mut ed25519_pubkey = [0; 32];
1269 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1270 addresses.push(NetAddress::OnionV3 {
1272 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1273 version: v[read_pos + 35],
1274 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1278 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1282 let secp_ctx = Secp256k1::without_caps();
1285 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1286 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1293 impl MsgEncodable for UnsignedNodeAnnouncement {
1294 fn encode(&self) -> Vec<u8> {
1295 let features = self.features.encode();
1296 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1297 res.extend_from_slice(&features[..]);
1298 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1299 res.extend_from_slice(&self.node_id.serialize());
1300 res.extend_from_slice(&self.rgb);
1301 res.extend_from_slice(&self.alias);
1302 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1303 let mut addrs_to_encode = self.addresses.clone();
1304 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1305 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1306 for addr in addrs_to_encode.iter() {
1308 &NetAddress::IPv4{addr, port} => {
1310 addr_slice.extend_from_slice(&addr);
1311 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1313 &NetAddress::IPv6{addr, port} => {
1315 addr_slice.extend_from_slice(&addr);
1316 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1318 &NetAddress::OnionV2{addr, port} => {
1320 addr_slice.extend_from_slice(&addr);
1321 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1323 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1325 addr_slice.extend_from_slice(&ed25519_pubkey);
1326 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1327 addr_slice.push(version);
1328 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1332 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1333 res.extend_from_slice(&addr_slice[..]);
1338 impl MsgDecodable for NodeAnnouncement {
1339 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1341 return Err(DecodeError::ShortRead);
1343 let secp_ctx = Secp256k1::without_caps();
1345 signature: secp_signature!(&secp_ctx, &v[0..64]),
1346 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1350 impl MsgEncodable for NodeAnnouncement {
1351 fn encode(&self) -> Vec<u8> {
1352 let contents = self.contents.encode();
1353 let mut res = Vec::with_capacity(64 + contents.len());
1354 let secp_ctx = Secp256k1::without_caps();
1355 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1356 res.extend_from_slice(&contents);
1361 impl MsgDecodable for UnsignedChannelAnnouncement {
1362 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1363 let features = GlobalFeatures::decode(&v[..])?;
1364 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1365 return Err(DecodeError::ShortRead);
1367 let start = features.encoded_len();
1368 let secp_ctx = Secp256k1::without_caps();
1371 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1372 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1373 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1374 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1375 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1376 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1380 impl MsgEncodable for UnsignedChannelAnnouncement {
1381 fn encode(&self) -> Vec<u8> {
1382 let features = self.features.encode();
1383 let mut res = Vec::with_capacity(172 + features.len());
1384 res.extend_from_slice(&features[..]);
1385 res.extend_from_slice(&self.chain_hash[..]);
1386 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1387 res.extend_from_slice(&self.node_id_1.serialize());
1388 res.extend_from_slice(&self.node_id_2.serialize());
1389 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1390 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1395 impl MsgDecodable for ChannelAnnouncement {
1396 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1398 return Err(DecodeError::ShortRead);
1400 let secp_ctx = Secp256k1::without_caps();
1402 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1403 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1404 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1405 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1406 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1410 impl MsgEncodable for ChannelAnnouncement {
1411 fn encode(&self) -> Vec<u8> {
1412 let secp_ctx = Secp256k1::without_caps();
1413 let contents = self.contents.encode();
1414 let mut res = Vec::with_capacity(64 + contents.len());
1415 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1416 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1417 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1418 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1419 res.extend_from_slice(&contents);
1424 impl MsgDecodable for UnsignedChannelUpdate {
1425 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1426 if v.len() < 32+8+4+2+2+8+4+4 {
1427 return Err(DecodeError::ShortRead);
1430 chain_hash: deserialize(&v[0..32]).unwrap(),
1431 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1432 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1433 flags: byte_utils::slice_to_be16(&v[44..46]),
1434 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1435 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1436 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1437 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1441 impl MsgEncodable for UnsignedChannelUpdate {
1442 fn encode(&self) -> Vec<u8> {
1443 let mut res = Vec::with_capacity(64);
1444 res.extend_from_slice(&self.chain_hash[..]);
1445 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1446 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1447 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1448 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1449 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1450 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1451 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1456 impl MsgDecodable for ChannelUpdate {
1457 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1459 return Err(DecodeError::ShortRead);
1461 let secp_ctx = Secp256k1::without_caps();
1463 signature: secp_signature!(&secp_ctx, &v[0..64]),
1464 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1468 impl MsgEncodable for ChannelUpdate {
1469 fn encode(&self) -> Vec<u8> {
1470 let mut res = Vec::with_capacity(128);
1471 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1472 res.extend_from_slice(&self.contents.encode()[..]);
1477 impl MsgDecodable for OnionRealm0HopData {
1478 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1480 return Err(DecodeError::ShortRead);
1482 Ok(OnionRealm0HopData {
1483 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1484 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1485 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1489 impl MsgEncodable for OnionRealm0HopData {
1490 fn encode(&self) -> Vec<u8> {
1491 let mut res = Vec::with_capacity(32);
1492 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1493 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1494 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1500 impl MsgDecodable for OnionHopData {
1501 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1503 return Err(DecodeError::ShortRead);
1507 return Err(DecodeError::UnknownRealmByte);
1509 let mut hmac = [0; 32];
1510 hmac[..].copy_from_slice(&v[33..65]);
1513 data: OnionRealm0HopData::decode(&v[1..33])?,
1518 impl MsgEncodable for OnionHopData {
1519 fn encode(&self) -> Vec<u8> {
1520 let mut res = Vec::with_capacity(65);
1521 res.push(self.realm);
1522 res.extend_from_slice(&self.data.encode()[..]);
1523 res.extend_from_slice(&self.hmac);
1528 impl MsgDecodable for OnionPacket {
1529 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1530 if v.len() < 1+33+20*65+32 {
1531 return Err(DecodeError::ShortRead);
1533 let mut hop_data = [0; 20*65];
1534 hop_data.copy_from_slice(&v[34..1334]);
1535 let mut hmac = [0; 32];
1536 hmac.copy_from_slice(&v[1334..1366]);
1537 let secp_ctx = Secp256k1::without_caps();
1540 public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1546 impl MsgEncodable for OnionPacket {
1547 fn encode(&self) -> Vec<u8> {
1548 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1549 res.push(self.version);
1550 res.extend_from_slice(&self.public_key.serialize());
1551 res.extend_from_slice(&self.hop_data);
1552 res.extend_from_slice(&self.hmac);
1557 impl MsgDecodable for DecodedOnionErrorPacket {
1558 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1559 if v.len() < 32 + 4 {
1560 return Err(DecodeError::ShortRead);
1562 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1563 if v.len() < 32 + 4 + failuremsg_len {
1564 return Err(DecodeError::ShortRead);
1566 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1567 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1568 return Err(DecodeError::ShortRead);
1571 let mut hmac = [0; 32];
1572 hmac.copy_from_slice(&v[0..32]);
1575 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1576 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1580 impl MsgEncodable for DecodedOnionErrorPacket {
1581 fn encode(&self) -> Vec<u8> {
1582 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1583 res.extend_from_slice(&self.hmac);
1584 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1585 res.extend_from_slice(&self.failuremsg);
1586 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1587 res.extend_from_slice(&self.pad);
1592 impl MsgDecodable for OnionErrorPacket {
1593 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1595 return Err(DecodeError::ShortRead);
1597 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1598 if v.len() < 2 + len {
1599 return Err(DecodeError::ShortRead);
1602 data: v[2..len+2].to_vec(),
1606 impl MsgEncodable for OnionErrorPacket {
1607 fn encode(&self) -> Vec<u8> {
1608 let mut res = Vec::with_capacity(2 + self.data.len());
1609 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1610 res.extend_from_slice(&self.data);
1615 impl MsgEncodable for ErrorMessage {
1616 fn encode(&self) -> Vec<u8> {
1617 let mut res = Vec::with_capacity(34 + self.data.len());
1618 res.extend_from_slice(&self.channel_id);
1619 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1620 res.extend_from_slice(&self.data.as_bytes());
1624 impl MsgDecodable for ErrorMessage {
1625 fn decode(v: &[u8]) -> Result<Self,DecodeError> {
1627 return Err(DecodeError::ShortRead);
1629 // Unlike most messages, BOLT 1 requires we truncate our read if the value is out of range
1630 let len = cmp::min(byte_utils::slice_to_be16(&v[32..34]) as usize, v.len() - 34);
1631 let data = match String::from_utf8(v[34..34 + len].to_vec()) {
1633 Err(_) => return Err(DecodeError::BadText),
1635 let mut channel_id = [0; 32];
1636 channel_id[..].copy_from_slice(&v[0..32]);
1647 use ln::msgs::MsgEncodable;
1649 use secp256k1::key::{PublicKey,SecretKey};
1650 use secp256k1::Secp256k1;
1653 fn encoding_channel_reestablish_no_secret() {
1655 let secp_ctx = Secp256k1::new();
1656 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1659 let cr = msgs::ChannelReestablish {
1660 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],
1661 next_local_commitment_number: 3,
1662 next_remote_commitment_number: 4,
1663 your_last_per_commitment_secret: None,
1664 my_current_per_commitment_point: public_key,
1667 let encoded_value = cr.encode();
1670 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]
1675 fn encoding_channel_reestablish_with_secret() {
1677 let secp_ctx = Secp256k1::new();
1678 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1681 let cr = msgs::ChannelReestablish {
1682 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],
1683 next_local_commitment_number: 3,
1684 next_remote_commitment_number: 4,
1685 your_last_per_commitment_secret: Some([9; 32]),
1686 my_current_per_commitment_point: public_key,
1689 let encoded_value = cr.encode();
1692 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]