1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use bitcoin::util::uint::Uint256;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::deserialize;
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() }
20 pub enum DecodeError {
21 /// Unknown realm byte in an OnionHopData packet
23 /// Failed to decode a public key (ie it's invalid)
25 /// Failed to decode a signature (ie it's invalid)
27 /// Buffer not of right length (either too short or too long)
29 /// node_announcement included more than one address of a given type!
30 ExtraAddressesPerType,
32 pub trait MsgDecodable: Sized {
33 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
36 /// Tracks localfeatures which are only in init messages
37 #[derive(Clone, PartialEq)]
38 pub struct LocalFeatures {
43 pub fn new() -> LocalFeatures {
49 pub fn supports_data_loss_protect(&self) -> bool {
50 self.flags.len() > 0 && (self.flags[0] & 3) != 0
52 pub fn requires_data_loss_protect(&self) -> bool {
53 self.flags.len() > 0 && (self.flags[0] & 1) != 0
56 pub fn supports_initial_routing_sync(&self) -> bool {
57 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
60 pub fn supports_upfront_shutdown_script(&self) -> bool {
61 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
63 pub fn requires_upfront_shutdown_script(&self) -> bool {
64 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
67 pub fn requires_unknown_bits(&self) -> bool {
68 for (idx, &byte) in self.flags.iter().enumerate() {
69 if idx != 0 && (byte & 0x55) != 0 {
71 } else if idx == 0 && (byte & 0x14) != 0 {
78 pub fn supports_unknown_bits(&self) -> bool {
79 for (idx, &byte) in self.flags.iter().enumerate() {
80 if idx != 0 && byte != 0 {
82 } else if idx == 0 && (byte & 0xc4) != 0 {
90 /// Tracks globalfeatures which are in init messages and routing announcements
91 #[derive(Clone, PartialEq)]
92 pub struct GlobalFeatures {
97 pub fn new() -> GlobalFeatures {
103 pub fn requires_unknown_bits(&self) -> bool {
104 for &byte in self.flags.iter() {
105 if (byte & 0x55) != 0 {
112 pub fn supports_unknown_bits(&self) -> bool {
113 for &byte in self.flags.iter() {
123 pub global_features: GlobalFeatures,
124 pub local_features: LocalFeatures,
127 pub struct OpenChannel {
128 pub chain_hash: Sha256dHash,
129 pub temporary_channel_id: Uint256,
130 pub funding_satoshis: u64,
132 pub dust_limit_satoshis: u64,
133 pub max_htlc_value_in_flight_msat: u64,
134 pub channel_reserve_satoshis: u64,
135 pub htlc_minimum_msat: u64,
136 pub feerate_per_kw: u32,
137 pub to_self_delay: u16,
138 pub max_accepted_htlcs: u16,
139 pub funding_pubkey: PublicKey,
140 pub revocation_basepoint: PublicKey,
141 pub payment_basepoint: PublicKey,
142 pub delayed_payment_basepoint: PublicKey,
143 pub htlc_basepoint: PublicKey,
144 pub first_per_commitment_point: PublicKey,
145 pub channel_flags: u8,
146 pub shutdown_scriptpubkey: Option<Script>,
149 pub struct AcceptChannel {
150 pub temporary_channel_id: Uint256,
151 pub dust_limit_satoshis: u64,
152 pub max_htlc_value_in_flight_msat: u64,
153 pub channel_reserve_satoshis: u64,
154 pub htlc_minimum_msat: u64,
155 pub minimum_depth: u32,
156 pub to_self_delay: u16,
157 pub max_accepted_htlcs: u16,
158 pub funding_pubkey: PublicKey,
159 pub revocation_basepoint: PublicKey,
160 pub payment_basepoint: PublicKey,
161 pub delayed_payment_basepoint: PublicKey,
162 pub htlc_basepoint: PublicKey,
163 pub first_per_commitment_point: PublicKey,
164 pub shutdown_scriptpubkey: Option<Script>,
167 pub struct FundingCreated {
168 pub temporary_channel_id: Uint256,
169 pub funding_txid: Sha256dHash,
170 pub funding_output_index: u16,
171 pub signature: Signature,
174 pub struct FundingSigned {
175 pub channel_id: Uint256,
176 pub signature: Signature,
179 pub struct FundingLocked {
180 pub channel_id: Uint256,
181 pub next_per_commitment_point: PublicKey,
184 pub struct Shutdown {
185 pub channel_id: Uint256,
186 pub scriptpubkey: Script,
189 pub struct ClosingSigned {
190 pub channel_id: Uint256,
191 pub fee_satoshis: u64,
192 pub signature: Signature,
196 pub struct UpdateAddHTLC {
197 pub channel_id: Uint256,
199 pub amount_msat: u64,
200 pub payment_hash: [u8; 32],
201 pub cltv_expiry: u32,
202 pub onion_routing_packet: OnionPacket,
206 pub struct UpdateFulfillHTLC {
207 pub channel_id: Uint256,
209 pub payment_preimage: [u8; 32],
213 pub struct UpdateFailHTLC {
214 pub channel_id: Uint256,
216 pub reason: OnionErrorPacket,
220 pub struct UpdateFailMalformedHTLC {
221 pub channel_id: Uint256,
223 pub sha256_of_onion: [u8; 32],
224 pub failure_code: u16,
228 pub struct CommitmentSigned {
229 pub channel_id: Uint256,
230 pub signature: Signature,
231 pub htlc_signatures: Vec<Signature>,
234 pub struct RevokeAndACK {
235 pub channel_id: Uint256,
236 pub per_commitment_secret: [u8; 32],
237 pub next_per_commitment_point: PublicKey,
240 pub struct UpdateFee {
241 pub channel_id: Uint256,
242 pub feerate_per_kw: u32,
245 pub struct ChannelReestablish {
246 pub channel_id: Uint256,
247 pub next_local_commitment_number: u64,
248 pub next_remote_commitment_number: u64,
249 pub your_last_per_commitment_secret: Option<[u8; 32]>,
250 pub my_current_per_commitment_point: PublicKey,
254 pub struct AnnouncementSignatures {
255 pub channel_id: Uint256,
256 pub short_channel_id: u64,
257 pub node_signature: Signature,
258 pub bitcoin_signature: Signature,
262 pub enum NetAddress {
276 ed25519_pubkey: [u8; 32],
283 fn get_id(&self) -> u8 {
285 &NetAddress::IPv4 {..} => { 1 },
286 &NetAddress::IPv6 {..} => { 2 },
287 &NetAddress::OnionV2 {..} => { 3 },
288 &NetAddress::OnionV3 {..} => { 4 },
293 pub struct UnsignedNodeAnnouncement {
294 pub features: GlobalFeatures,
296 pub node_id: PublicKey,
299 /// List of addresses on which this node is reachable. Note that you may only have up to one
300 /// address of each type, if you have more, they may be silently discarded or we may panic!
301 pub addresses: Vec<NetAddress>,
303 pub struct NodeAnnouncement {
304 pub signature: Signature,
305 pub contents: UnsignedNodeAnnouncement,
308 #[derive(PartialEq, Clone)]
309 pub struct UnsignedChannelAnnouncement {
310 pub features: GlobalFeatures,
311 pub chain_hash: Sha256dHash,
312 pub short_channel_id: u64,
313 pub node_id_1: PublicKey,
314 pub node_id_2: PublicKey,
315 pub bitcoin_key_1: PublicKey,
316 pub bitcoin_key_2: PublicKey,
318 #[derive(PartialEq, Clone)]
319 pub struct ChannelAnnouncement {
320 pub node_signature_1: Signature,
321 pub node_signature_2: Signature,
322 pub bitcoin_signature_1: Signature,
323 pub bitcoin_signature_2: Signature,
324 pub contents: UnsignedChannelAnnouncement,
327 #[derive(PartialEq, Clone)]
328 pub struct UnsignedChannelUpdate {
329 pub chain_hash: Sha256dHash,
330 pub short_channel_id: u64,
333 pub cltv_expiry_delta: u16,
334 pub htlc_minimum_msat: u64,
335 pub fee_base_msat: u32,
336 pub fee_proportional_millionths: u32,
338 #[derive(PartialEq, Clone)]
339 pub struct ChannelUpdate {
340 pub signature: Signature,
341 pub contents: UnsignedChannelUpdate,
344 /// Used to put an error message in a HandleError
345 pub enum ErrorMessage {
352 pub struct HandleError { //TODO: rename me
353 pub err: &'static str,
354 pub msg: Option<ErrorMessage>, //TODO: Move into an Action enum and require it!
357 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
358 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
359 /// paralell when the two calls have the same their_node_id.
360 pub trait ChannelMessageHandler : events::EventsProvider {
362 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
363 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
364 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
365 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
366 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
369 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
370 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
373 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
374 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
375 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
376 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
377 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<RevokeAndACK, HandleError>;
378 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
380 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
382 // Channel-to-announce:
383 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
386 pub trait RoutingMessageHandler {
387 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
388 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
389 /// or returning an Err otherwise.
390 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
391 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
394 pub struct OnionRealm0HopData {
395 pub short_channel_id: u64,
396 pub amt_to_forward: u64,
397 pub outgoing_cltv_value: u32,
398 // 12 bytes of 0-padding
401 pub struct OnionHopData {
403 pub data: OnionRealm0HopData,
406 unsafe impl internal_traits::NoDealloc for OnionHopData{}
409 pub struct OnionPacket {
411 pub public_key: PublicKey,
412 pub hop_data: [u8; 20*65],
416 pub struct DecodedOnionErrorPacket {
418 pub failuremsg: Vec<u8>,
423 pub struct OnionErrorPacket {
424 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
425 // (TODO) We limit it in decode to much lower...
429 impl Error for DecodeError {
430 fn description(&self) -> &str {
432 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
433 DecodeError::BadPublicKey => "Invalid public key in packet",
434 DecodeError::BadSignature => "Invalid signature in packet",
435 DecodeError::WrongLength => "Data was wrong length for packet",
436 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
440 impl fmt::Display for DecodeError {
441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
442 f.write_str(self.description())
446 impl fmt::Debug for HandleError {
447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
448 f.write_str(self.err)
452 macro_rules! secp_pubkey {
453 ( $ctx: expr, $slice: expr ) => {
454 match PublicKey::from_slice($ctx, $slice) {
456 Err(_) => return Err(DecodeError::BadPublicKey)
461 macro_rules! secp_signature {
462 ( $ctx: expr, $slice: expr ) => {
463 match Signature::from_compact($ctx, $slice) {
465 Err(_) => return Err(DecodeError::BadSignature)
470 impl MsgDecodable for LocalFeatures {
471 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
472 if v.len() < 3 { return Err(DecodeError::WrongLength); }
473 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
474 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
475 let mut flags = Vec::with_capacity(len);
476 flags.extend_from_slice(&v[2..]);
482 impl MsgEncodable for LocalFeatures {
483 fn encode(&self) -> Vec<u8> {
484 let mut res = Vec::with_capacity(self.flags.len() + 2);
485 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
486 res.extend_from_slice(&self.flags[..]);
489 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
492 impl MsgDecodable for GlobalFeatures {
493 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
494 if v.len() < 3 { return Err(DecodeError::WrongLength); }
495 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
496 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
497 let mut flags = Vec::with_capacity(len);
498 flags.extend_from_slice(&v[2..]);
504 impl MsgEncodable for GlobalFeatures {
505 fn encode(&self) -> Vec<u8> {
506 let mut res = Vec::with_capacity(self.flags.len() + 2);
507 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
508 res.extend_from_slice(&self.flags[..]);
511 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
514 impl MsgDecodable for Init {
515 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
516 let global_features = GlobalFeatures::decode(v)?;
517 if v.len() < global_features.flags.len() + 4 {
518 return Err(DecodeError::WrongLength);
520 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
522 global_features: global_features,
523 local_features: local_features,
527 impl MsgEncodable for Init {
528 fn encode(&self) -> Vec<u8> {
529 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
530 res.extend_from_slice(&self.global_features.encode()[..]);
531 res.extend_from_slice(&self.local_features.encode()[..]);
536 impl MsgDecodable for OpenChannel {
537 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
538 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
539 return Err(DecodeError::WrongLength);
541 let ctx = Secp256k1::without_caps();
543 let mut shutdown_scriptpubkey = None;
545 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
546 if v.len() < 321+len {
547 return Err(DecodeError::WrongLength);
549 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
550 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
551 return Err(DecodeError::WrongLength);
555 chain_hash: deserialize(&v[0..32]).unwrap(),
556 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
557 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
558 push_msat: byte_utils::slice_to_be64(&v[72..80]),
559 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
560 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
561 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
562 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
563 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
564 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
565 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
566 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
567 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
568 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
569 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
570 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
571 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
572 channel_flags: v[318],
573 shutdown_scriptpubkey: shutdown_scriptpubkey
577 impl MsgEncodable for OpenChannel {
578 fn encode(&self) -> Vec<u8> {
583 impl MsgDecodable for AcceptChannel {
584 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
585 if v.len() < 32+4*8+4+2*2+6*33 {
586 return Err(DecodeError::WrongLength);
588 let ctx = Secp256k1::without_caps();
590 let mut shutdown_scriptpubkey = None;
592 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
593 if v.len() < 272+len {
594 return Err(DecodeError::WrongLength);
596 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
597 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
598 return Err(DecodeError::WrongLength);
602 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
603 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
604 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
605 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
606 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
607 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
608 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
609 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
610 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
611 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
612 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
613 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
614 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
615 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
616 shutdown_scriptpubkey: shutdown_scriptpubkey
620 impl MsgEncodable for AcceptChannel {
621 fn encode(&self) -> Vec<u8> {
626 impl MsgDecodable for FundingCreated {
627 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
628 if v.len() < 32+32+2+64 {
629 return Err(DecodeError::WrongLength);
631 let ctx = Secp256k1::without_caps();
633 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
634 funding_txid: deserialize(&v[32..64]).unwrap(),
635 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
636 signature: secp_signature!(&ctx, &v[66..130]),
640 impl MsgEncodable for FundingCreated {
641 fn encode(&self) -> Vec<u8> {
646 impl MsgDecodable for FundingSigned {
647 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
649 return Err(DecodeError::WrongLength);
651 let ctx = Secp256k1::without_caps();
653 channel_id: deserialize(&v[0..32]).unwrap(),
654 signature: secp_signature!(&ctx, &v[32..96]),
658 impl MsgEncodable for FundingSigned {
659 fn encode(&self) -> Vec<u8> {
664 impl MsgDecodable for FundingLocked {
665 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
667 return Err(DecodeError::WrongLength);
669 let ctx = Secp256k1::without_caps();
671 channel_id: deserialize(&v[0..32]).unwrap(),
672 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
676 impl MsgEncodable for FundingLocked {
677 fn encode(&self) -> Vec<u8> {
682 impl MsgDecodable for Shutdown {
683 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
684 if v.len() < 32 + 2 {
685 return Err(DecodeError::WrongLength);
687 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
688 if v.len() < 32 + 2 + scriptlen {
689 return Err(DecodeError::WrongLength);
692 channel_id: deserialize(&v[0..32]).unwrap(),
693 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
697 impl MsgEncodable for Shutdown {
698 fn encode(&self) -> Vec<u8> {
703 impl MsgDecodable for ClosingSigned {
704 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
705 if v.len() < 32 + 8 + 64 {
706 return Err(DecodeError::WrongLength);
708 let secp_ctx = Secp256k1::without_caps();
710 channel_id: deserialize(&v[0..32]).unwrap(),
711 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
712 signature: secp_signature!(&secp_ctx, &v[40..104]),
716 impl MsgEncodable for ClosingSigned {
717 fn encode(&self) -> Vec<u8> {
722 impl MsgDecodable for UpdateAddHTLC {
723 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
724 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
725 return Err(DecodeError::WrongLength);
727 let mut payment_hash = [0; 32];
728 payment_hash.copy_from_slice(&v[48..80]);
730 channel_id: deserialize(&v[0..32]).unwrap(),
731 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
732 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
734 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
735 onion_routing_packet: OnionPacket::decode(&v[84..])?,
739 impl MsgEncodable for UpdateAddHTLC {
740 fn encode(&self) -> Vec<u8> {
745 impl MsgDecodable for UpdateFulfillHTLC {
746 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
747 if v.len() < 32+8+32 {
748 return Err(DecodeError::WrongLength);
750 let mut payment_preimage = [0; 32];
751 payment_preimage.copy_from_slice(&v[40..72]);
753 channel_id: deserialize(&v[0..32]).unwrap(),
754 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
759 impl MsgEncodable for UpdateFulfillHTLC {
760 fn encode(&self) -> Vec<u8> {
765 impl MsgDecodable for UpdateFailHTLC {
766 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
768 return Err(DecodeError::WrongLength);
771 channel_id: deserialize(&v[0..32]).unwrap(),
772 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
773 reason: OnionErrorPacket::decode(&v[40..])?,
777 impl MsgEncodable for UpdateFailHTLC {
778 fn encode(&self) -> Vec<u8> {
783 impl MsgDecodable for UpdateFailMalformedHTLC {
784 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
785 if v.len() < 32+8+32+2 {
786 return Err(DecodeError::WrongLength);
788 let mut sha256_of_onion = [0; 32];
789 sha256_of_onion.copy_from_slice(&v[40..72]);
791 channel_id: deserialize(&v[0..32]).unwrap(),
792 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
794 failure_code: byte_utils::slice_to_be16(&v[72..74]),
798 impl MsgEncodable for UpdateFailMalformedHTLC {
799 fn encode(&self) -> Vec<u8> {
804 impl MsgDecodable for CommitmentSigned {
805 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
806 if v.len() < 32+64+2 {
807 return Err(DecodeError::WrongLength);
809 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
810 if v.len() < 32+64+2+htlcs*64 {
811 return Err(DecodeError::WrongLength);
813 let mut htlc_signatures = Vec::with_capacity(htlcs);
814 let secp_ctx = Secp256k1::without_caps();
816 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
819 channel_id: deserialize(&v[0..32]).unwrap(),
820 signature: secp_signature!(&secp_ctx, &v[32..96]),
825 impl MsgEncodable for CommitmentSigned {
826 fn encode(&self) -> Vec<u8> {
831 impl MsgDecodable for RevokeAndACK {
832 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
833 if v.len() < 32+32+33 {
834 return Err(DecodeError::WrongLength);
836 let mut per_commitment_secret = [0; 32];
837 per_commitment_secret.copy_from_slice(&v[32..64]);
838 let secp_ctx = Secp256k1::without_caps();
840 channel_id: deserialize(&v[0..32]).unwrap(),
841 per_commitment_secret,
842 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
846 impl MsgEncodable for RevokeAndACK {
847 fn encode(&self) -> Vec<u8> {
852 impl MsgDecodable for UpdateFee {
853 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
855 return Err(DecodeError::WrongLength);
858 channel_id: deserialize(&v[0..32]).unwrap(),
859 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
863 impl MsgEncodable for UpdateFee {
864 fn encode(&self) -> Vec<u8> {
869 impl MsgDecodable for ChannelReestablish {
870 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
874 impl MsgEncodable for ChannelReestablish {
875 fn encode(&self) -> Vec<u8> {
880 impl MsgDecodable for AnnouncementSignatures {
881 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
882 if v.len() < 32+8+64*2 {
883 return Err(DecodeError::WrongLength);
885 let secp_ctx = Secp256k1::without_caps();
887 channel_id: deserialize(&v[0..32]).unwrap(),
888 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
889 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
890 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
894 impl MsgEncodable for AnnouncementSignatures {
895 fn encode(&self) -> Vec<u8> {
900 impl MsgDecodable for UnsignedNodeAnnouncement {
901 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
902 let features = GlobalFeatures::decode(&v[..])?;
903 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
904 return Err(DecodeError::WrongLength);
906 let start = features.encoded_len();
908 let mut rgb = [0; 3];
909 rgb.copy_from_slice(&v[start + 37..start + 40]);
911 let mut alias = [0; 32];
912 alias.copy_from_slice(&v[start + 40..start + 72]);
914 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
915 if v.len() < start + 74 + addrlen {
916 return Err(DecodeError::WrongLength);
919 let mut addresses = Vec::with_capacity(4);
920 let mut read_pos = start + 74;
922 if v.len() <= read_pos { break; }
924 0 => { read_pos += 1; },
926 if v.len() < read_pos + 1 + 6 {
927 return Err(DecodeError::WrongLength);
929 if addresses.len() > 0 {
930 return Err(DecodeError::ExtraAddressesPerType);
932 let mut addr = [0; 4];
933 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
934 addresses.push(NetAddress::IPv4 {
936 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
941 if v.len() < read_pos + 1 + 18 {
942 return Err(DecodeError::WrongLength);
944 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
945 return Err(DecodeError::ExtraAddressesPerType);
947 let mut addr = [0; 16];
948 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
949 addresses.push(NetAddress::IPv6 {
951 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
956 if v.len() < read_pos + 1 + 12 {
957 return Err(DecodeError::WrongLength);
959 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
960 return Err(DecodeError::ExtraAddressesPerType);
962 let mut addr = [0; 10];
963 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
964 addresses.push(NetAddress::OnionV2 {
966 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
971 if v.len() < read_pos + 1 + 37 {
972 return Err(DecodeError::WrongLength);
974 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
975 return Err(DecodeError::ExtraAddressesPerType);
977 let mut ed25519_pubkey = [0; 32];
978 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
979 addresses.push(NetAddress::OnionV3 {
981 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
982 version: v[read_pos + 35],
983 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
987 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
991 let secp_ctx = Secp256k1::without_caps();
994 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
995 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1002 impl MsgEncodable for UnsignedNodeAnnouncement {
1003 fn encode(&self) -> Vec<u8> {
1004 let features = self.features.encode();
1005 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1006 res.extend_from_slice(&features[..]);
1007 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1008 res.extend_from_slice(&self.node_id.serialize());
1009 res.extend_from_slice(&self.rgb);
1010 res.extend_from_slice(&self.alias);
1011 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1012 let mut addrs_to_encode = self.addresses.clone();
1013 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1014 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1015 for addr in addrs_to_encode.iter() {
1017 &NetAddress::IPv4{addr, port} => {
1019 addr_slice.extend_from_slice(&addr);
1020 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1022 &NetAddress::IPv6{addr, port} => {
1024 addr_slice.extend_from_slice(&addr);
1025 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1027 &NetAddress::OnionV2{addr, port} => {
1029 addr_slice.extend_from_slice(&addr);
1030 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1032 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1034 addr_slice.extend_from_slice(&ed25519_pubkey);
1035 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1036 addr_slice.push(version);
1037 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1041 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1042 res.extend_from_slice(&addr_slice[..]);
1047 impl MsgDecodable for NodeAnnouncement {
1048 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1050 return Err(DecodeError::WrongLength);
1052 let secp_ctx = Secp256k1::without_caps();
1054 signature: secp_signature!(&secp_ctx, &v[0..64]),
1055 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1059 impl MsgEncodable for NodeAnnouncement {
1060 fn encode(&self) -> Vec<u8> {
1065 impl MsgDecodable for UnsignedChannelAnnouncement {
1066 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1067 let features = GlobalFeatures::decode(&v[..])?;
1068 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1069 return Err(DecodeError::WrongLength);
1071 let start = features.encoded_len();
1072 let secp_ctx = Secp256k1::without_caps();
1075 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1076 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1077 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1078 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1079 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1080 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1084 impl MsgEncodable for UnsignedChannelAnnouncement {
1085 fn encode(&self) -> Vec<u8> {
1086 let features = self.features.encode();
1087 let mut res = Vec::with_capacity(172 + features.len());
1088 res.extend_from_slice(&features[..]);
1089 res.extend_from_slice(&self.chain_hash[..]);
1090 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1091 res.extend_from_slice(&self.node_id_1.serialize());
1092 res.extend_from_slice(&self.node_id_2.serialize());
1093 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1094 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1099 impl MsgDecodable for ChannelAnnouncement {
1100 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1102 return Err(DecodeError::WrongLength);
1104 let secp_ctx = Secp256k1::without_caps();
1106 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1107 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1108 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1109 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1110 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1114 impl MsgEncodable for ChannelAnnouncement {
1115 fn encode(&self) -> Vec<u8> {
1120 impl MsgDecodable for UnsignedChannelUpdate {
1121 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1122 if v.len() < 32+8+4+2+2+8+4+4 {
1123 return Err(DecodeError::WrongLength);
1126 chain_hash: deserialize(&v[0..32]).unwrap(),
1127 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1128 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1129 flags: byte_utils::slice_to_be16(&v[44..46]),
1130 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1131 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1132 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1133 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1137 impl MsgEncodable for UnsignedChannelUpdate {
1138 fn encode(&self) -> Vec<u8> {
1139 let mut res = Vec::with_capacity(64);
1140 res.extend_from_slice(&self.chain_hash[..]);
1141 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1142 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1143 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1144 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1145 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1146 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1147 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1152 impl MsgDecodable for ChannelUpdate {
1153 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1155 return Err(DecodeError::WrongLength);
1157 let secp_ctx = Secp256k1::without_caps();
1159 signature: secp_signature!(&secp_ctx, &v[0..64]),
1160 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1164 impl MsgEncodable for ChannelUpdate {
1165 fn encode(&self) -> Vec<u8> {
1166 let mut res = Vec::with_capacity(128);
1167 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1168 res.extend_from_slice(&self.contents.encode()[..]);
1173 impl MsgDecodable for OnionRealm0HopData {
1174 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1176 return Err(DecodeError::WrongLength);
1178 Ok(OnionRealm0HopData {
1179 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1180 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1181 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1185 impl MsgEncodable for OnionRealm0HopData {
1186 fn encode(&self) -> Vec<u8> {
1187 let mut res = Vec::with_capacity(32);
1188 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1189 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1190 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1196 impl MsgDecodable for OnionHopData {
1197 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1199 return Err(DecodeError::WrongLength);
1203 return Err(DecodeError::UnknownRealmByte);
1205 let mut hmac = [0; 32];
1206 hmac[..].copy_from_slice(&v[33..65]);
1209 data: OnionRealm0HopData::decode(&v[1..33])?,
1214 impl MsgEncodable for OnionHopData {
1215 fn encode(&self) -> Vec<u8> {
1216 let mut res = Vec::with_capacity(65);
1217 res.push(self.realm);
1218 res.extend_from_slice(&self.data.encode()[..]);
1219 res.extend_from_slice(&self.hmac);
1224 impl MsgDecodable for OnionPacket {
1225 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1226 if v.len() < 1+33+20*65+32 {
1227 return Err(DecodeError::WrongLength);
1229 let mut hop_data = [0; 20*65];
1230 hop_data.copy_from_slice(&v[34..1334]);
1231 let mut hmac = [0; 32];
1232 hmac.copy_from_slice(&v[1334..1366]);
1233 let secp_ctx = Secp256k1::without_caps();
1236 public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1242 impl MsgEncodable for OnionPacket {
1243 fn encode(&self) -> Vec<u8> {
1244 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1245 res.push(self.version);
1246 res.extend_from_slice(&self.public_key.serialize());
1247 res.extend_from_slice(&self.hop_data);
1248 res.extend_from_slice(&self.hmac);
1253 impl MsgDecodable for DecodedOnionErrorPacket {
1254 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1258 impl MsgEncodable for DecodedOnionErrorPacket {
1259 fn encode(&self) -> Vec<u8> {
1260 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1261 res.extend_from_slice(&self.hmac);
1262 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1263 res.extend_from_slice(&self.failuremsg);
1264 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1265 res.extend_from_slice(&self.pad);
1270 impl MsgDecodable for OnionErrorPacket {
1271 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1273 return Err(DecodeError::WrongLength);
1275 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1276 if v.len() < 2 + len {
1277 return Err(DecodeError::WrongLength);
1280 data: v[2..len+2].to_vec(),
1284 impl MsgEncodable for OnionErrorPacket {
1285 fn encode(&self) -> Vec<u8> {