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
36 /// Buffer not of right length (either too short or too long)
38 /// node_announcement included more than one address of a given type!
39 ExtraAddressesPerType,
41 pub trait MsgDecodable: Sized {
42 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
45 /// Tracks localfeatures which are only in init messages
46 #[derive(Clone, PartialEq)]
47 pub struct LocalFeatures {
52 pub fn new() -> LocalFeatures {
58 pub fn supports_data_loss_protect(&self) -> bool {
59 self.flags.len() > 0 && (self.flags[0] & 3) != 0
61 pub fn requires_data_loss_protect(&self) -> bool {
62 self.flags.len() > 0 && (self.flags[0] & 1) != 0
65 pub fn initial_routing_sync(&self) -> bool {
66 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
68 pub fn set_initial_routing_sync(&mut self) {
69 if self.flags.len() == 0 {
70 self.flags.resize(1, 1 << 3);
72 self.flags[0] |= 1 << 3;
76 pub fn supports_upfront_shutdown_script(&self) -> bool {
77 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
79 pub fn requires_upfront_shutdown_script(&self) -> bool {
80 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
83 pub fn requires_unknown_bits(&self) -> bool {
84 for (idx, &byte) in self.flags.iter().enumerate() {
85 if idx != 0 && (byte & 0x55) != 0 {
87 } else if idx == 0 && (byte & 0x14) != 0 {
94 pub fn supports_unknown_bits(&self) -> bool {
95 for (idx, &byte) in self.flags.iter().enumerate() {
96 if idx != 0 && byte != 0 {
98 } else if idx == 0 && (byte & 0xc4) != 0 {
106 /// Tracks globalfeatures which are in init messages and routing announcements
107 #[derive(Clone, PartialEq)]
108 pub struct GlobalFeatures {
112 impl GlobalFeatures {
113 pub fn new() -> GlobalFeatures {
119 pub fn requires_unknown_bits(&self) -> bool {
120 for &byte in self.flags.iter() {
121 if (byte & 0x55) != 0 {
128 pub fn supports_unknown_bits(&self) -> bool {
129 for &byte in self.flags.iter() {
139 pub global_features: GlobalFeatures,
140 pub local_features: LocalFeatures,
143 pub struct ErrorMessage {
144 pub channel_id: [u8; 32],
157 pub struct OpenChannel {
158 pub chain_hash: Sha256dHash,
159 pub temporary_channel_id: [u8; 32],
160 pub funding_satoshis: u64,
162 pub dust_limit_satoshis: u64,
163 pub max_htlc_value_in_flight_msat: u64,
164 pub channel_reserve_satoshis: u64,
165 pub htlc_minimum_msat: u64,
166 pub feerate_per_kw: u32,
167 pub to_self_delay: u16,
168 pub max_accepted_htlcs: u16,
169 pub funding_pubkey: PublicKey,
170 pub revocation_basepoint: PublicKey,
171 pub payment_basepoint: PublicKey,
172 pub delayed_payment_basepoint: PublicKey,
173 pub htlc_basepoint: PublicKey,
174 pub first_per_commitment_point: PublicKey,
175 pub channel_flags: u8,
176 pub shutdown_scriptpubkey: Option<Script>,
179 pub struct AcceptChannel {
180 pub temporary_channel_id: [u8; 32],
181 pub dust_limit_satoshis: u64,
182 pub max_htlc_value_in_flight_msat: u64,
183 pub channel_reserve_satoshis: u64,
184 pub htlc_minimum_msat: u64,
185 pub minimum_depth: u32,
186 pub to_self_delay: u16,
187 pub max_accepted_htlcs: u16,
188 pub funding_pubkey: PublicKey,
189 pub revocation_basepoint: PublicKey,
190 pub payment_basepoint: PublicKey,
191 pub delayed_payment_basepoint: PublicKey,
192 pub htlc_basepoint: PublicKey,
193 pub first_per_commitment_point: PublicKey,
194 pub shutdown_scriptpubkey: Option<Script>,
197 pub struct FundingCreated {
198 pub temporary_channel_id: [u8; 32],
199 pub funding_txid: Sha256dHash,
200 pub funding_output_index: u16,
201 pub signature: Signature,
204 pub struct FundingSigned {
205 pub channel_id: [u8; 32],
206 pub signature: Signature,
209 pub struct FundingLocked {
210 pub channel_id: [u8; 32],
211 pub next_per_commitment_point: PublicKey,
214 pub struct Shutdown {
215 pub channel_id: [u8; 32],
216 pub scriptpubkey: Script,
219 pub struct ClosingSigned {
220 pub channel_id: [u8; 32],
221 pub fee_satoshis: u64,
222 pub signature: Signature,
226 pub struct UpdateAddHTLC {
227 pub channel_id: [u8; 32],
229 pub amount_msat: u64,
230 pub payment_hash: [u8; 32],
231 pub cltv_expiry: u32,
232 pub onion_routing_packet: OnionPacket,
236 pub struct UpdateFulfillHTLC {
237 pub channel_id: [u8; 32],
239 pub payment_preimage: [u8; 32],
243 pub struct UpdateFailHTLC {
244 pub channel_id: [u8; 32],
246 pub reason: OnionErrorPacket,
250 pub struct UpdateFailMalformedHTLC {
251 pub channel_id: [u8; 32],
253 pub sha256_of_onion: [u8; 32],
254 pub failure_code: u16,
258 pub struct CommitmentSigned {
259 pub channel_id: [u8; 32],
260 pub signature: Signature,
261 pub htlc_signatures: Vec<Signature>,
264 pub struct RevokeAndACK {
265 pub channel_id: [u8; 32],
266 pub per_commitment_secret: [u8; 32],
267 pub next_per_commitment_point: PublicKey,
270 pub struct UpdateFee {
271 pub channel_id: [u8; 32],
272 pub feerate_per_kw: u32,
275 pub struct ChannelReestablish {
276 pub channel_id: [u8; 32],
277 pub next_local_commitment_number: u64,
278 pub next_remote_commitment_number: u64,
279 pub your_last_per_commitment_secret: Option<[u8; 32]>,
280 pub my_current_per_commitment_point: PublicKey,
284 pub struct AnnouncementSignatures {
285 pub channel_id: [u8; 32],
286 pub short_channel_id: u64,
287 pub node_signature: Signature,
288 pub bitcoin_signature: Signature,
292 pub enum NetAddress {
306 ed25519_pubkey: [u8; 32],
313 fn get_id(&self) -> u8 {
315 &NetAddress::IPv4 {..} => { 1 },
316 &NetAddress::IPv6 {..} => { 2 },
317 &NetAddress::OnionV2 {..} => { 3 },
318 &NetAddress::OnionV3 {..} => { 4 },
323 pub struct UnsignedNodeAnnouncement {
324 pub features: GlobalFeatures,
326 pub node_id: PublicKey,
329 /// List of addresses on which this node is reachable. Note that you may only have up to one
330 /// address of each type, if you have more, they may be silently discarded or we may panic!
331 pub addresses: Vec<NetAddress>,
333 pub struct NodeAnnouncement {
334 pub signature: Signature,
335 pub contents: UnsignedNodeAnnouncement,
338 #[derive(PartialEq, Clone)]
339 pub struct UnsignedChannelAnnouncement {
340 pub features: GlobalFeatures,
341 pub chain_hash: Sha256dHash,
342 pub short_channel_id: u64,
343 pub node_id_1: PublicKey,
344 pub node_id_2: PublicKey,
345 pub bitcoin_key_1: PublicKey,
346 pub bitcoin_key_2: PublicKey,
348 #[derive(PartialEq, Clone)]
349 pub struct ChannelAnnouncement {
350 pub node_signature_1: Signature,
351 pub node_signature_2: Signature,
352 pub bitcoin_signature_1: Signature,
353 pub bitcoin_signature_2: Signature,
354 pub contents: UnsignedChannelAnnouncement,
357 #[derive(PartialEq, Clone)]
358 pub struct UnsignedChannelUpdate {
359 pub chain_hash: Sha256dHash,
360 pub short_channel_id: u64,
363 pub cltv_expiry_delta: u16,
364 pub htlc_minimum_msat: u64,
365 pub fee_base_msat: u32,
366 pub fee_proportional_millionths: u32,
368 #[derive(PartialEq, Clone)]
369 pub struct ChannelUpdate {
370 pub signature: Signature,
371 pub contents: UnsignedChannelUpdate,
374 /// Used to put an error message in a HandleError
375 pub enum ErrorAction {
376 /// Indicates an inbound HTLC add resulted in a failure, and the UpdateFailHTLC provided in msg
377 /// should be sent back to the sender.
381 /// The peer took some action which made us think they were useless. Disconnect them.
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);
450 pub trait RoutingMessageHandler : Send + Sync {
451 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
452 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
453 /// or returning an Err otherwise.
454 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
455 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
456 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
459 pub struct OnionRealm0HopData {
460 pub short_channel_id: u64,
461 pub amt_to_forward: u64,
462 pub outgoing_cltv_value: u32,
463 // 12 bytes of 0-padding
466 pub struct OnionHopData {
468 pub data: OnionRealm0HopData,
471 unsafe impl internal_traits::NoDealloc for OnionHopData{}
474 pub struct OnionPacket {
476 pub public_key: PublicKey,
477 pub hop_data: [u8; 20*65],
481 pub struct DecodedOnionErrorPacket {
483 pub failuremsg: Vec<u8>,
488 pub struct OnionErrorPacket {
489 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
490 // (TODO) We limit it in decode to much lower...
494 impl Error for DecodeError {
495 fn description(&self) -> &str {
497 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
498 DecodeError::BadPublicKey => "Invalid public key in packet",
499 DecodeError::BadSignature => "Invalid signature in packet",
500 DecodeError::BadText => "Invalid text in packet",
501 DecodeError::WrongLength => "Data was wrong length for packet",
502 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
506 impl fmt::Display for DecodeError {
507 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
508 f.write_str(self.description())
512 impl fmt::Debug for HandleError {
513 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514 f.write_str(self.err)
518 macro_rules! secp_pubkey {
519 ( $ctx: expr, $slice: expr ) => {
520 match PublicKey::from_slice($ctx, $slice) {
522 Err(_) => return Err(DecodeError::BadPublicKey)
527 macro_rules! secp_signature {
528 ( $ctx: expr, $slice: expr ) => {
529 match Signature::from_compact($ctx, $slice) {
531 Err(_) => return Err(DecodeError::BadSignature)
536 impl MsgDecodable for LocalFeatures {
537 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
538 if v.len() < 2 { return Err(DecodeError::WrongLength); }
539 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
540 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
541 let mut flags = Vec::with_capacity(len);
542 flags.extend_from_slice(&v[2..2 + len]);
548 impl MsgEncodable for LocalFeatures {
549 fn encode(&self) -> Vec<u8> {
550 let mut res = Vec::with_capacity(self.flags.len() + 2);
551 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
552 res.extend_from_slice(&self.flags[..]);
555 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
558 impl MsgDecodable for GlobalFeatures {
559 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
560 if v.len() < 2 { return Err(DecodeError::WrongLength); }
561 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
562 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
563 let mut flags = Vec::with_capacity(len);
564 flags.extend_from_slice(&v[2..2 + len]);
570 impl MsgEncodable for GlobalFeatures {
571 fn encode(&self) -> Vec<u8> {
572 let mut res = Vec::with_capacity(self.flags.len() + 2);
573 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
574 res.extend_from_slice(&self.flags[..]);
577 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
580 impl MsgDecodable for Init {
581 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
582 let global_features = GlobalFeatures::decode(v)?;
583 if v.len() < global_features.flags.len() + 4 {
584 return Err(DecodeError::WrongLength);
586 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
588 global_features: global_features,
589 local_features: local_features,
593 impl MsgEncodable for Init {
594 fn encode(&self) -> Vec<u8> {
595 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
596 res.extend_from_slice(&self.global_features.encode()[..]);
597 res.extend_from_slice(&self.local_features.encode()[..]);
602 impl MsgDecodable for Ping {
603 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
605 return Err(DecodeError::WrongLength);
607 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
608 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
609 if v.len() < 4 + byteslen as usize {
610 return Err(DecodeError::WrongLength);
618 impl MsgEncodable for Ping {
619 fn encode(&self) -> Vec<u8> {
620 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
621 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
622 res.resize(2 + self.byteslen as usize, 0);
627 impl MsgDecodable for Pong {
628 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
630 return Err(DecodeError::WrongLength);
632 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
633 if v.len() < 2 + byteslen as usize {
634 return Err(DecodeError::WrongLength);
641 impl MsgEncodable for Pong {
642 fn encode(&self) -> Vec<u8> {
643 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
644 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
645 res.resize(2 + self.byteslen as usize, 0);
650 impl MsgDecodable for OpenChannel {
651 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
652 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
653 return Err(DecodeError::WrongLength);
655 let ctx = Secp256k1::without_caps();
657 let mut shutdown_scriptpubkey = None;
659 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
660 if v.len() < 321+len {
661 return Err(DecodeError::WrongLength);
663 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
664 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
665 return Err(DecodeError::WrongLength);
669 chain_hash: deserialize(&v[0..32]).unwrap(),
670 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
671 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
672 push_msat: byte_utils::slice_to_be64(&v[72..80]),
673 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
674 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
675 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
676 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
677 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
678 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
679 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
680 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
681 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
682 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
683 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
684 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
685 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
686 channel_flags: v[318],
687 shutdown_scriptpubkey: shutdown_scriptpubkey
691 impl MsgEncodable for OpenChannel {
692 fn encode(&self) -> Vec<u8> {
693 let mut res = match &self.shutdown_scriptpubkey {
694 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
695 &None => Vec::with_capacity(319),
697 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
698 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
699 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
700 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
701 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
702 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
703 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
704 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
705 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
706 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
707 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
708 res.extend_from_slice(&self.funding_pubkey.serialize());
709 res.extend_from_slice(&self.revocation_basepoint.serialize());
710 res.extend_from_slice(&self.payment_basepoint.serialize());
711 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
712 res.extend_from_slice(&self.htlc_basepoint.serialize());
713 res.extend_from_slice(&self.first_per_commitment_point.serialize());
714 res.push(self.channel_flags);
715 if let &Some(ref script) = &self.shutdown_scriptpubkey {
716 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
717 res.extend_from_slice(&script[..]);
723 impl MsgDecodable for AcceptChannel {
724 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
725 if v.len() < 32+4*8+4+2*2+6*33 {
726 return Err(DecodeError::WrongLength);
728 let ctx = Secp256k1::without_caps();
730 let mut shutdown_scriptpubkey = None;
732 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
733 if v.len() < 272+len {
734 return Err(DecodeError::WrongLength);
736 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
737 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
738 return Err(DecodeError::WrongLength);
741 let mut temporary_channel_id = [0; 32];
742 temporary_channel_id[..].copy_from_slice(&v[0..32]);
744 temporary_channel_id,
745 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
746 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
747 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
748 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
749 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
750 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
751 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
752 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
753 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
754 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
755 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
756 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
757 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
758 shutdown_scriptpubkey: shutdown_scriptpubkey
762 impl MsgEncodable for AcceptChannel {
763 fn encode(&self) -> Vec<u8> {
764 let mut res = match &self.shutdown_scriptpubkey {
765 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
766 &None => Vec::with_capacity(270),
768 res.extend_from_slice(&self.temporary_channel_id);
769 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
770 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
771 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
772 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
773 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
774 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
775 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
776 res.extend_from_slice(&self.funding_pubkey.serialize());
777 res.extend_from_slice(&self.revocation_basepoint.serialize());
778 res.extend_from_slice(&self.payment_basepoint.serialize());
779 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
780 res.extend_from_slice(&self.htlc_basepoint.serialize());
781 res.extend_from_slice(&self.first_per_commitment_point.serialize());
782 if let &Some(ref script) = &self.shutdown_scriptpubkey {
783 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
784 res.extend_from_slice(&script[..]);
790 impl MsgDecodable for FundingCreated {
791 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
792 if v.len() < 32+32+2+64 {
793 return Err(DecodeError::WrongLength);
795 let ctx = Secp256k1::without_caps();
796 let mut temporary_channel_id = [0; 32];
797 temporary_channel_id[..].copy_from_slice(&v[0..32]);
799 temporary_channel_id,
800 funding_txid: deserialize(&v[32..64]).unwrap(),
801 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
802 signature: secp_signature!(&ctx, &v[66..130]),
806 impl MsgEncodable for FundingCreated {
807 fn encode(&self) -> Vec<u8> {
808 let mut res = Vec::with_capacity(32+32+2+64);
809 res.extend_from_slice(&self.temporary_channel_id);
810 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
811 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
812 let secp_ctx = Secp256k1::without_caps();
813 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
818 impl MsgDecodable for FundingSigned {
819 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
821 return Err(DecodeError::WrongLength);
823 let ctx = Secp256k1::without_caps();
824 let mut channel_id = [0; 32];
825 channel_id[..].copy_from_slice(&v[0..32]);
828 signature: secp_signature!(&ctx, &v[32..96]),
832 impl MsgEncodable for FundingSigned {
833 fn encode(&self) -> Vec<u8> {
834 let mut res = Vec::with_capacity(32+64);
835 res.extend_from_slice(&self.channel_id);
836 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
841 impl MsgDecodable for FundingLocked {
842 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
844 return Err(DecodeError::WrongLength);
846 let ctx = Secp256k1::without_caps();
847 let mut channel_id = [0; 32];
848 channel_id[..].copy_from_slice(&v[0..32]);
851 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
855 impl MsgEncodable for FundingLocked {
856 fn encode(&self) -> Vec<u8> {
857 let mut res = Vec::with_capacity(32+33);
858 res.extend_from_slice(&self.channel_id);
859 res.extend_from_slice(&self.next_per_commitment_point.serialize());
864 impl MsgDecodable for Shutdown {
865 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
866 if v.len() < 32 + 2 {
867 return Err(DecodeError::WrongLength);
869 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
870 if v.len() < 32 + 2 + scriptlen {
871 return Err(DecodeError::WrongLength);
873 let mut channel_id = [0; 32];
874 channel_id[..].copy_from_slice(&v[0..32]);
877 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
881 impl MsgEncodable for Shutdown {
882 fn encode(&self) -> Vec<u8> {
883 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
884 res.extend_from_slice(&self.channel_id);
885 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
886 res.extend_from_slice(&self.scriptpubkey[..]);
891 impl MsgDecodable for ClosingSigned {
892 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
893 if v.len() < 32 + 8 + 64 {
894 return Err(DecodeError::WrongLength);
896 let secp_ctx = Secp256k1::without_caps();
897 let mut channel_id = [0; 32];
898 channel_id[..].copy_from_slice(&v[0..32]);
901 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
902 signature: secp_signature!(&secp_ctx, &v[40..104]),
906 impl MsgEncodable for ClosingSigned {
907 fn encode(&self) -> Vec<u8> {
908 let mut res = Vec::with_capacity(32+8+64);
909 res.extend_from_slice(&self.channel_id);
910 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
911 let secp_ctx = Secp256k1::without_caps();
912 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
917 impl MsgDecodable for UpdateAddHTLC {
918 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
919 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
920 return Err(DecodeError::WrongLength);
922 let mut channel_id = [0; 32];
923 channel_id[..].copy_from_slice(&v[0..32]);
924 let mut payment_hash = [0; 32];
925 payment_hash.copy_from_slice(&v[48..80]);
928 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
929 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
931 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
932 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
936 impl MsgEncodable for UpdateAddHTLC {
937 fn encode(&self) -> Vec<u8> {
938 let mut res = Vec::with_capacity(32+8+8+32+4+1+1366);
939 res.extend_from_slice(&self.channel_id);
940 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
941 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
942 res.extend_from_slice(&self.payment_hash);
943 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
944 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
949 impl MsgDecodable for UpdateFulfillHTLC {
950 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
951 if v.len() < 32+8+32 {
952 return Err(DecodeError::WrongLength);
954 let mut channel_id = [0; 32];
955 channel_id[..].copy_from_slice(&v[0..32]);
956 let mut payment_preimage = [0; 32];
957 payment_preimage.copy_from_slice(&v[40..72]);
960 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
965 impl MsgEncodable for UpdateFulfillHTLC {
966 fn encode(&self) -> Vec<u8> {
967 let mut res = Vec::with_capacity(32+8+32);
968 res.extend_from_slice(&self.channel_id);
969 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
970 res.extend_from_slice(&self.payment_preimage);
975 impl MsgDecodable for UpdateFailHTLC {
976 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
978 return Err(DecodeError::WrongLength);
980 let mut channel_id = [0; 32];
981 channel_id[..].copy_from_slice(&v[0..32]);
984 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
985 reason: OnionErrorPacket::decode(&v[40..])?,
989 impl MsgEncodable for UpdateFailHTLC {
990 fn encode(&self) -> Vec<u8> {
991 let reason = self.reason.encode();
992 let mut res = Vec::with_capacity(32+8+reason.len());
993 res.extend_from_slice(&self.channel_id);
994 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
995 res.extend_from_slice(&reason[..]);
1000 impl MsgDecodable for UpdateFailMalformedHTLC {
1001 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1002 if v.len() < 32+8+32+2 {
1003 return Err(DecodeError::WrongLength);
1005 let mut channel_id = [0; 32];
1006 channel_id[..].copy_from_slice(&v[0..32]);
1007 let mut sha256_of_onion = [0; 32];
1008 sha256_of_onion.copy_from_slice(&v[40..72]);
1011 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1013 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1017 impl MsgEncodable for UpdateFailMalformedHTLC {
1018 fn encode(&self) -> Vec<u8> {
1019 let mut res = Vec::with_capacity(32+8+32+2);
1020 res.extend_from_slice(&self.channel_id);
1021 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1022 res.extend_from_slice(&self.sha256_of_onion);
1023 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1028 impl MsgDecodable for CommitmentSigned {
1029 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1030 if v.len() < 32+64+2 {
1031 return Err(DecodeError::WrongLength);
1033 let mut channel_id = [0; 32];
1034 channel_id[..].copy_from_slice(&v[0..32]);
1036 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1037 if v.len() < 32+64+2+htlcs*64 {
1038 return Err(DecodeError::WrongLength);
1040 let mut htlc_signatures = Vec::with_capacity(htlcs);
1041 let secp_ctx = Secp256k1::without_caps();
1043 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1047 signature: secp_signature!(&secp_ctx, &v[32..96]),
1052 impl MsgEncodable for CommitmentSigned {
1053 fn encode(&self) -> Vec<u8> {
1054 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1055 res.extend_from_slice(&self.channel_id);
1056 let secp_ctx = Secp256k1::without_caps();
1057 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1058 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1059 for i in 0..self.htlc_signatures.len() {
1060 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1066 impl MsgDecodable for RevokeAndACK {
1067 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1068 if v.len() < 32+32+33 {
1069 return Err(DecodeError::WrongLength);
1071 let mut channel_id = [0; 32];
1072 channel_id[..].copy_from_slice(&v[0..32]);
1073 let mut per_commitment_secret = [0; 32];
1074 per_commitment_secret.copy_from_slice(&v[32..64]);
1075 let secp_ctx = Secp256k1::without_caps();
1078 per_commitment_secret,
1079 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1083 impl MsgEncodable for RevokeAndACK {
1084 fn encode(&self) -> Vec<u8> {
1085 let mut res = Vec::with_capacity(32+32+33);
1086 res.extend_from_slice(&self.channel_id);
1087 res.extend_from_slice(&self.per_commitment_secret);
1088 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1093 impl MsgDecodable for UpdateFee {
1094 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1096 return Err(DecodeError::WrongLength);
1098 let mut channel_id = [0; 32];
1099 channel_id[..].copy_from_slice(&v[0..32]);
1102 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1106 impl MsgEncodable for UpdateFee {
1107 fn encode(&self) -> Vec<u8> {
1108 let mut res = Vec::with_capacity(32+4);
1109 res.extend_from_slice(&self.channel_id);
1110 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1115 impl MsgDecodable for ChannelReestablish {
1116 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1117 if v.len() < 32+2*8+33 {
1118 return Err(DecodeError::WrongLength);
1121 let your_last_per_commitment_secret = if v.len() > 32+2*8+33 {
1122 if v.len() < 32+2*8+33 + 32 {
1123 return Err(DecodeError::WrongLength);
1125 let mut inner_array = [0; 32];
1126 inner_array.copy_from_slice(&v[48..48+32]);
1130 let option_size = match &your_last_per_commitment_secret {
1131 &Some(ref _ary) => 32,
1135 channel_id: deserialize(&v[0..32]).unwrap(),
1136 next_local_commitment_number: byte_utils::slice_to_be64(&v[32..40]),
1137 next_remote_commitment_number: byte_utils::slice_to_be64(&v[40..48]),
1138 your_last_per_commitment_secret: your_last_per_commitment_secret,
1139 my_current_per_commitment_point: {
1140 let ctx = Secp256k1::without_caps();
1141 secp_pubkey!(&ctx, &v[48+option_size..48+option_size+33])
1146 impl MsgEncodable for ChannelReestablish {
1147 fn encode(&self) -> Vec<u8> {
1148 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 });
1150 res.extend_from_slice(&serialize(&self.channel_id).unwrap()[..]);
1151 res.extend_from_slice(&byte_utils::be64_to_array(self.next_local_commitment_number));
1152 res.extend_from_slice(&byte_utils::be64_to_array(self.next_remote_commitment_number));
1154 if let &Some(ref ary) = &self.your_last_per_commitment_secret {
1155 res.extend_from_slice(&ary[..]);
1158 res.extend_from_slice(&self.my_current_per_commitment_point.serialize());
1163 impl MsgDecodable for AnnouncementSignatures {
1164 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1165 if v.len() < 32+8+64*2 {
1166 return Err(DecodeError::WrongLength);
1168 let secp_ctx = Secp256k1::without_caps();
1169 let mut channel_id = [0; 32];
1170 channel_id[..].copy_from_slice(&v[0..32]);
1173 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1174 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1175 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1179 impl MsgEncodable for AnnouncementSignatures {
1180 fn encode(&self) -> Vec<u8> {
1181 let mut res = Vec::with_capacity(32+8+64*2);
1182 res.extend_from_slice(&self.channel_id);
1183 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1184 let secp_ctx = Secp256k1::without_caps();
1185 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1186 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1191 impl MsgDecodable for UnsignedNodeAnnouncement {
1192 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1193 let features = GlobalFeatures::decode(&v[..])?;
1194 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1195 return Err(DecodeError::WrongLength);
1197 let start = features.encoded_len();
1199 let mut rgb = [0; 3];
1200 rgb.copy_from_slice(&v[start + 37..start + 40]);
1202 let mut alias = [0; 32];
1203 alias.copy_from_slice(&v[start + 40..start + 72]);
1205 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1206 if v.len() < start + 74 + addrlen {
1207 return Err(DecodeError::WrongLength);
1210 let mut addresses = Vec::with_capacity(4);
1211 let mut read_pos = start + 74;
1213 if v.len() <= read_pos { break; }
1215 0 => { read_pos += 1; },
1217 if v.len() < read_pos + 1 + 6 {
1218 return Err(DecodeError::WrongLength);
1220 if addresses.len() > 0 {
1221 return Err(DecodeError::ExtraAddressesPerType);
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 v.len() < read_pos + 1 + 18 {
1233 return Err(DecodeError::WrongLength);
1235 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1236 return Err(DecodeError::ExtraAddressesPerType);
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 v.len() < read_pos + 1 + 12 {
1248 return Err(DecodeError::WrongLength);
1250 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1251 return Err(DecodeError::ExtraAddressesPerType);
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 v.len() < read_pos + 1 + 37 {
1263 return Err(DecodeError::WrongLength);
1265 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1266 return Err(DecodeError::ExtraAddressesPerType);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
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::WrongLength);
1597 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1598 if v.len() < 2 + len {
1599 return Err(DecodeError::WrongLength);
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::WrongLength);
1629 let len = byte_utils::slice_to_be16(&v[32..34]);
1630 if v.len() < 34 + len as usize {
1631 return Err(DecodeError::WrongLength);
1633 let data = match String::from_utf8(v[34..34 + len as usize].to_vec()) {
1635 Err(_) => return Err(DecodeError::BadText),
1637 let mut channel_id = [0; 32];
1638 channel_id[..].copy_from_slice(&v[0..32]);
1648 use bitcoin::util::misc::hex_bytes;
1649 use ln::msgs::MsgEncodable;
1651 use secp256k1::key::{PublicKey,SecretKey};
1652 use secp256k1::Secp256k1;
1655 fn encoding_channel_reestablish_no_secret() {
1657 let secp_ctx = Secp256k1::new();
1658 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap()
1661 let cr = msgs::ChannelReestablish {
1662 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],
1663 next_local_commitment_number: 3,
1664 next_remote_commitment_number: 4,
1665 your_last_per_commitment_secret: None,
1666 my_current_per_commitment_point: public_key,
1669 let encoded_value = cr.encode();
1672 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]
1677 fn encoding_channel_reestablish_with_secret() {
1679 let secp_ctx = Secp256k1::new();
1680 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap()
1683 let cr = msgs::ChannelReestablish {
1684 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],
1685 next_local_commitment_number: 3,
1686 next_remote_commitment_number: 4,
1687 your_last_per_commitment_secret: Some([9; 32]),
1688 my_current_per_commitment_point: public_key,
1691 let encoded_value = cr.encode();
1694 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]