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 /// Buffer not of right length (either too short or too long)
36 /// node_announcement included more than one address of a given type!
37 ExtraAddressesPerType,
39 pub trait MsgDecodable: Sized {
40 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
43 /// Tracks localfeatures which are only in init messages
44 #[derive(Clone, PartialEq)]
45 pub struct LocalFeatures {
50 pub fn new() -> LocalFeatures {
56 pub fn supports_data_loss_protect(&self) -> bool {
57 self.flags.len() > 0 && (self.flags[0] & 3) != 0
59 pub fn requires_data_loss_protect(&self) -> bool {
60 self.flags.len() > 0 && (self.flags[0] & 1) != 0
63 pub fn initial_routing_sync(&self) -> bool {
64 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
66 pub fn set_initial_routing_sync(&mut self) {
67 if self.flags.len() == 0 {
68 self.flags.resize(1, 1 << 3);
70 self.flags[0] |= 1 << 3;
74 pub fn supports_upfront_shutdown_script(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
77 pub fn requires_upfront_shutdown_script(&self) -> bool {
78 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
81 pub fn requires_unknown_bits(&self) -> bool {
82 for (idx, &byte) in self.flags.iter().enumerate() {
83 if idx != 0 && (byte & 0x55) != 0 {
85 } else if idx == 0 && (byte & 0x14) != 0 {
92 pub fn supports_unknown_bits(&self) -> bool {
93 for (idx, &byte) in self.flags.iter().enumerate() {
94 if idx != 0 && byte != 0 {
96 } else if idx == 0 && (byte & 0xc4) != 0 {
104 /// Tracks globalfeatures which are in init messages and routing announcements
105 #[derive(Clone, PartialEq)]
106 pub struct GlobalFeatures {
110 impl GlobalFeatures {
111 pub fn new() -> GlobalFeatures {
117 pub fn requires_unknown_bits(&self) -> bool {
118 for &byte in self.flags.iter() {
119 if (byte & 0x55) != 0 {
126 pub fn supports_unknown_bits(&self) -> bool {
127 for &byte in self.flags.iter() {
137 pub global_features: GlobalFeatures,
138 pub local_features: LocalFeatures,
150 pub struct OpenChannel {
151 pub chain_hash: Sha256dHash,
152 pub temporary_channel_id: [u8; 32],
153 pub funding_satoshis: u64,
155 pub dust_limit_satoshis: u64,
156 pub max_htlc_value_in_flight_msat: u64,
157 pub channel_reserve_satoshis: u64,
158 pub htlc_minimum_msat: u64,
159 pub feerate_per_kw: u32,
160 pub to_self_delay: u16,
161 pub max_accepted_htlcs: u16,
162 pub funding_pubkey: PublicKey,
163 pub revocation_basepoint: PublicKey,
164 pub payment_basepoint: PublicKey,
165 pub delayed_payment_basepoint: PublicKey,
166 pub htlc_basepoint: PublicKey,
167 pub first_per_commitment_point: PublicKey,
168 pub channel_flags: u8,
169 pub shutdown_scriptpubkey: Option<Script>,
172 pub struct AcceptChannel {
173 pub temporary_channel_id: [u8; 32],
174 pub dust_limit_satoshis: u64,
175 pub max_htlc_value_in_flight_msat: u64,
176 pub channel_reserve_satoshis: u64,
177 pub htlc_minimum_msat: u64,
178 pub minimum_depth: u32,
179 pub to_self_delay: u16,
180 pub max_accepted_htlcs: u16,
181 pub funding_pubkey: PublicKey,
182 pub revocation_basepoint: PublicKey,
183 pub payment_basepoint: PublicKey,
184 pub delayed_payment_basepoint: PublicKey,
185 pub htlc_basepoint: PublicKey,
186 pub first_per_commitment_point: PublicKey,
187 pub shutdown_scriptpubkey: Option<Script>,
190 pub struct FundingCreated {
191 pub temporary_channel_id: [u8; 32],
192 pub funding_txid: Sha256dHash,
193 pub funding_output_index: u16,
194 pub signature: Signature,
197 pub struct FundingSigned {
198 pub channel_id: [u8; 32],
199 pub signature: Signature,
202 pub struct FundingLocked {
203 pub channel_id: [u8; 32],
204 pub next_per_commitment_point: PublicKey,
207 pub struct Shutdown {
208 pub channel_id: [u8; 32],
209 pub scriptpubkey: Script,
212 pub struct ClosingSigned {
213 pub channel_id: [u8; 32],
214 pub fee_satoshis: u64,
215 pub signature: Signature,
219 pub struct UpdateAddHTLC {
220 pub channel_id: [u8; 32],
222 pub amount_msat: u64,
223 pub payment_hash: [u8; 32],
224 pub cltv_expiry: u32,
225 pub onion_routing_packet: OnionPacket,
229 pub struct UpdateFulfillHTLC {
230 pub channel_id: [u8; 32],
232 pub payment_preimage: [u8; 32],
236 pub struct UpdateFailHTLC {
237 pub channel_id: [u8; 32],
239 pub reason: OnionErrorPacket,
243 pub struct UpdateFailMalformedHTLC {
244 pub channel_id: [u8; 32],
246 pub sha256_of_onion: [u8; 32],
247 pub failure_code: u16,
251 pub struct CommitmentSigned {
252 pub channel_id: [u8; 32],
253 pub signature: Signature,
254 pub htlc_signatures: Vec<Signature>,
257 pub struct RevokeAndACK {
258 pub channel_id: [u8; 32],
259 pub per_commitment_secret: [u8; 32],
260 pub next_per_commitment_point: PublicKey,
263 pub struct UpdateFee {
264 pub channel_id: [u8; 32],
265 pub feerate_per_kw: u32,
268 pub struct ChannelReestablish {
269 pub channel_id: [u8; 32],
270 pub next_local_commitment_number: u64,
271 pub next_remote_commitment_number: u64,
272 pub your_last_per_commitment_secret: Option<[u8; 32]>,
273 pub my_current_per_commitment_point: PublicKey,
277 pub struct AnnouncementSignatures {
278 pub channel_id: [u8; 32],
279 pub short_channel_id: u64,
280 pub node_signature: Signature,
281 pub bitcoin_signature: Signature,
285 pub enum NetAddress {
299 ed25519_pubkey: [u8; 32],
306 fn get_id(&self) -> u8 {
308 &NetAddress::IPv4 {..} => { 1 },
309 &NetAddress::IPv6 {..} => { 2 },
310 &NetAddress::OnionV2 {..} => { 3 },
311 &NetAddress::OnionV3 {..} => { 4 },
316 pub struct UnsignedNodeAnnouncement {
317 pub features: GlobalFeatures,
319 pub node_id: PublicKey,
322 /// List of addresses on which this node is reachable. Note that you may only have up to one
323 /// address of each type, if you have more, they may be silently discarded or we may panic!
324 pub addresses: Vec<NetAddress>,
326 pub struct NodeAnnouncement {
327 pub signature: Signature,
328 pub contents: UnsignedNodeAnnouncement,
331 #[derive(PartialEq, Clone)]
332 pub struct UnsignedChannelAnnouncement {
333 pub features: GlobalFeatures,
334 pub chain_hash: Sha256dHash,
335 pub short_channel_id: u64,
336 pub node_id_1: PublicKey,
337 pub node_id_2: PublicKey,
338 pub bitcoin_key_1: PublicKey,
339 pub bitcoin_key_2: PublicKey,
341 #[derive(PartialEq, Clone)]
342 pub struct ChannelAnnouncement {
343 pub node_signature_1: Signature,
344 pub node_signature_2: Signature,
345 pub bitcoin_signature_1: Signature,
346 pub bitcoin_signature_2: Signature,
347 pub contents: UnsignedChannelAnnouncement,
350 #[derive(PartialEq, Clone)]
351 pub struct UnsignedChannelUpdate {
352 pub chain_hash: Sha256dHash,
353 pub short_channel_id: u64,
356 pub cltv_expiry_delta: u16,
357 pub htlc_minimum_msat: u64,
358 pub fee_base_msat: u32,
359 pub fee_proportional_millionths: u32,
361 #[derive(PartialEq, Clone)]
362 pub struct ChannelUpdate {
363 pub signature: Signature,
364 pub contents: UnsignedChannelUpdate,
367 /// Used to put an error message in a HandleError
368 pub enum ErrorAction {
369 /// Indicates an inbound HTLC add resulted in a failure, and the UpdateFailHTLC provided in msg
370 /// should be sent back to the sender.
374 /// The peer took some action which made us think they were useless. Disconnect them.
376 /// The peer did something harmless that we weren't able to process, just log and ignore
380 pub struct HandleError { //TODO: rename me
381 pub err: &'static str,
382 pub action: Option<ErrorAction>, //TODO: Make this required
385 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
386 /// transaction updates if they were pending.
387 pub struct CommitmentUpdate {
388 pub update_add_htlcs: Vec<UpdateAddHTLC>,
389 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
390 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
391 pub commitment_signed: CommitmentSigned,
394 pub enum HTLCFailChannelUpdate {
395 ChannelUpdateMessage {
399 short_channel_id: u64,
403 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
404 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
405 /// paralell when the two calls have the same their_node_id.
406 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
408 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
409 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
410 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
411 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
412 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
415 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
416 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
419 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
420 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
421 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
422 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
423 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
424 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
426 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
428 // Channel-to-announce:
429 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
432 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
433 /// is believed to be possible in the future (eg they're sending us messages we don't
434 /// understand or indicate they require unknown feature bits), no_connection_possible is set
435 /// and any outstanding channels should be failed.
436 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
439 pub trait RoutingMessageHandler : Send + Sync {
440 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
441 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
442 /// or returning an Err otherwise.
443 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
444 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
445 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
448 pub struct OnionRealm0HopData {
449 pub short_channel_id: u64,
450 pub amt_to_forward: u64,
451 pub outgoing_cltv_value: u32,
452 // 12 bytes of 0-padding
455 pub struct OnionHopData {
457 pub data: OnionRealm0HopData,
460 unsafe impl internal_traits::NoDealloc for OnionHopData{}
463 pub struct OnionPacket {
465 pub public_key: PublicKey,
466 pub hop_data: [u8; 20*65],
470 pub struct DecodedOnionErrorPacket {
472 pub failuremsg: Vec<u8>,
477 pub struct OnionErrorPacket {
478 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
479 // (TODO) We limit it in decode to much lower...
483 impl Error for DecodeError {
484 fn description(&self) -> &str {
486 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
487 DecodeError::BadPublicKey => "Invalid public key in packet",
488 DecodeError::BadSignature => "Invalid signature in packet",
489 DecodeError::WrongLength => "Data was wrong length for packet",
490 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
494 impl fmt::Display for DecodeError {
495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
496 f.write_str(self.description())
500 impl fmt::Debug for HandleError {
501 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
502 f.write_str(self.err)
506 macro_rules! secp_pubkey {
507 ( $ctx: expr, $slice: expr ) => {
508 match PublicKey::from_slice($ctx, $slice) {
510 Err(_) => return Err(DecodeError::BadPublicKey)
515 macro_rules! secp_signature {
516 ( $ctx: expr, $slice: expr ) => {
517 match Signature::from_compact($ctx, $slice) {
519 Err(_) => return Err(DecodeError::BadSignature)
524 impl MsgDecodable for LocalFeatures {
525 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
526 if v.len() < 2 { return Err(DecodeError::WrongLength); }
527 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
528 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
529 let mut flags = Vec::with_capacity(len);
530 flags.extend_from_slice(&v[2..2 + len]);
536 impl MsgEncodable for LocalFeatures {
537 fn encode(&self) -> Vec<u8> {
538 let mut res = Vec::with_capacity(self.flags.len() + 2);
539 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
540 res.extend_from_slice(&self.flags[..]);
543 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
546 impl MsgDecodable for GlobalFeatures {
547 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
548 if v.len() < 2 { return Err(DecodeError::WrongLength); }
549 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
550 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
551 let mut flags = Vec::with_capacity(len);
552 flags.extend_from_slice(&v[2..2 + len]);
558 impl MsgEncodable for GlobalFeatures {
559 fn encode(&self) -> Vec<u8> {
560 let mut res = Vec::with_capacity(self.flags.len() + 2);
561 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
562 res.extend_from_slice(&self.flags[..]);
565 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
568 impl MsgDecodable for Init {
569 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
570 let global_features = GlobalFeatures::decode(v)?;
571 if v.len() < global_features.flags.len() + 4 {
572 return Err(DecodeError::WrongLength);
574 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
576 global_features: global_features,
577 local_features: local_features,
581 impl MsgEncodable for Init {
582 fn encode(&self) -> Vec<u8> {
583 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
584 res.extend_from_slice(&self.global_features.encode()[..]);
585 res.extend_from_slice(&self.local_features.encode()[..]);
590 impl MsgDecodable for Ping {
591 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
593 return Err(DecodeError::WrongLength);
595 let ponglen = byte_utils::slice_to_be16(&v[0..2]);
596 let byteslen = byte_utils::slice_to_be16(&v[2..4]);
597 if v.len() < 4 + byteslen as usize {
598 return Err(DecodeError::WrongLength);
606 impl MsgEncodable for Ping {
607 fn encode(&self) -> Vec<u8> {
608 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
609 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
610 res.resize(2 + self.byteslen as usize, 0);
615 impl MsgDecodable for Pong {
616 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
618 return Err(DecodeError::WrongLength);
620 let byteslen = byte_utils::slice_to_be16(&v[0..2]);
621 if v.len() < 2 + byteslen as usize {
622 return Err(DecodeError::WrongLength);
629 impl MsgEncodable for Pong {
630 fn encode(&self) -> Vec<u8> {
631 let mut res = Vec::with_capacity(self.byteslen as usize + 2);
632 res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen));
633 res.resize(2 + self.byteslen as usize, 0);
638 impl MsgDecodable for OpenChannel {
639 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
640 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
641 return Err(DecodeError::WrongLength);
643 let ctx = Secp256k1::without_caps();
645 let mut shutdown_scriptpubkey = None;
647 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
648 if v.len() < 321+len {
649 return Err(DecodeError::WrongLength);
651 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
652 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
653 return Err(DecodeError::WrongLength);
657 chain_hash: deserialize(&v[0..32]).unwrap(),
658 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
659 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
660 push_msat: byte_utils::slice_to_be64(&v[72..80]),
661 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
662 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
663 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
664 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
665 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
666 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
667 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
668 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
669 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
670 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
671 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
672 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
673 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
674 channel_flags: v[318],
675 shutdown_scriptpubkey: shutdown_scriptpubkey
679 impl MsgEncodable for OpenChannel {
680 fn encode(&self) -> Vec<u8> {
681 let mut res = match &self.shutdown_scriptpubkey {
682 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
683 &None => Vec::with_capacity(319),
685 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
686 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
687 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
688 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
689 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
690 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
691 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
692 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
693 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
694 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
695 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
696 res.extend_from_slice(&self.funding_pubkey.serialize());
697 res.extend_from_slice(&self.revocation_basepoint.serialize());
698 res.extend_from_slice(&self.payment_basepoint.serialize());
699 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
700 res.extend_from_slice(&self.htlc_basepoint.serialize());
701 res.extend_from_slice(&self.first_per_commitment_point.serialize());
702 res.push(self.channel_flags);
703 if let &Some(ref script) = &self.shutdown_scriptpubkey {
704 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
705 res.extend_from_slice(&script[..]);
711 impl MsgDecodable for AcceptChannel {
712 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
713 if v.len() < 32+4*8+4+2*2+6*33 {
714 return Err(DecodeError::WrongLength);
716 let ctx = Secp256k1::without_caps();
718 let mut shutdown_scriptpubkey = None;
720 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
721 if v.len() < 272+len {
722 return Err(DecodeError::WrongLength);
724 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
725 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
726 return Err(DecodeError::WrongLength);
729 let mut temporary_channel_id = [0; 32];
730 temporary_channel_id[..].copy_from_slice(&v[0..32]);
732 temporary_channel_id,
733 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
734 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
735 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
736 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
737 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
738 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
739 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
740 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
741 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
742 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
743 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
744 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
745 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
746 shutdown_scriptpubkey: shutdown_scriptpubkey
750 impl MsgEncodable for AcceptChannel {
751 fn encode(&self) -> Vec<u8> {
752 let mut res = match &self.shutdown_scriptpubkey {
753 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
754 &None => Vec::with_capacity(270),
756 res.extend_from_slice(&self.temporary_channel_id);
757 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
758 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
759 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
760 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
761 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
762 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
763 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
764 res.extend_from_slice(&self.funding_pubkey.serialize());
765 res.extend_from_slice(&self.revocation_basepoint.serialize());
766 res.extend_from_slice(&self.payment_basepoint.serialize());
767 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
768 res.extend_from_slice(&self.htlc_basepoint.serialize());
769 res.extend_from_slice(&self.first_per_commitment_point.serialize());
770 if let &Some(ref script) = &self.shutdown_scriptpubkey {
771 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
772 res.extend_from_slice(&script[..]);
778 impl MsgDecodable for FundingCreated {
779 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
780 if v.len() < 32+32+2+64 {
781 return Err(DecodeError::WrongLength);
783 let ctx = Secp256k1::without_caps();
784 let mut temporary_channel_id = [0; 32];
785 temporary_channel_id[..].copy_from_slice(&v[0..32]);
787 temporary_channel_id,
788 funding_txid: deserialize(&v[32..64]).unwrap(),
789 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
790 signature: secp_signature!(&ctx, &v[66..130]),
794 impl MsgEncodable for FundingCreated {
795 fn encode(&self) -> Vec<u8> {
796 let mut res = Vec::with_capacity(32+32+2+64);
797 res.extend_from_slice(&self.temporary_channel_id);
798 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
799 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
800 let secp_ctx = Secp256k1::without_caps();
801 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
806 impl MsgDecodable for FundingSigned {
807 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
809 return Err(DecodeError::WrongLength);
811 let ctx = Secp256k1::without_caps();
812 let mut channel_id = [0; 32];
813 channel_id[..].copy_from_slice(&v[0..32]);
816 signature: secp_signature!(&ctx, &v[32..96]),
820 impl MsgEncodable for FundingSigned {
821 fn encode(&self) -> Vec<u8> {
822 let mut res = Vec::with_capacity(32+64);
823 res.extend_from_slice(&self.channel_id);
824 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
829 impl MsgDecodable for FundingLocked {
830 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
832 return Err(DecodeError::WrongLength);
834 let ctx = Secp256k1::without_caps();
835 let mut channel_id = [0; 32];
836 channel_id[..].copy_from_slice(&v[0..32]);
839 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
843 impl MsgEncodable for FundingLocked {
844 fn encode(&self) -> Vec<u8> {
845 let mut res = Vec::with_capacity(32+33);
846 res.extend_from_slice(&self.channel_id);
847 res.extend_from_slice(&self.next_per_commitment_point.serialize());
852 impl MsgDecodable for Shutdown {
853 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
854 if v.len() < 32 + 2 {
855 return Err(DecodeError::WrongLength);
857 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
858 if v.len() < 32 + 2 + scriptlen {
859 return Err(DecodeError::WrongLength);
861 let mut channel_id = [0; 32];
862 channel_id[..].copy_from_slice(&v[0..32]);
865 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
869 impl MsgEncodable for Shutdown {
870 fn encode(&self) -> Vec<u8> {
871 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
872 res.extend_from_slice(&self.channel_id);
873 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
874 res.extend_from_slice(&self.scriptpubkey[..]);
879 impl MsgDecodable for ClosingSigned {
880 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
881 if v.len() < 32 + 8 + 64 {
882 return Err(DecodeError::WrongLength);
884 let secp_ctx = Secp256k1::without_caps();
885 let mut channel_id = [0; 32];
886 channel_id[..].copy_from_slice(&v[0..32]);
889 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
890 signature: secp_signature!(&secp_ctx, &v[40..104]),
894 impl MsgEncodable for ClosingSigned {
895 fn encode(&self) -> Vec<u8> {
896 let mut res = Vec::with_capacity(32+8+64);
897 res.extend_from_slice(&self.channel_id);
898 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
899 let secp_ctx = Secp256k1::without_caps();
900 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
905 impl MsgDecodable for UpdateAddHTLC {
906 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
907 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
908 return Err(DecodeError::WrongLength);
910 let mut channel_id = [0; 32];
911 channel_id[..].copy_from_slice(&v[0..32]);
912 let mut payment_hash = [0; 32];
913 payment_hash.copy_from_slice(&v[48..80]);
916 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
917 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
919 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
920 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
924 impl MsgEncodable for UpdateAddHTLC {
925 fn encode(&self) -> Vec<u8> {
926 let mut res = Vec::with_capacity(32+8+8+32+4+1+1366);
927 res.extend_from_slice(&self.channel_id);
928 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
929 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
930 res.extend_from_slice(&self.payment_hash);
931 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
932 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
937 impl MsgDecodable for UpdateFulfillHTLC {
938 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
939 if v.len() < 32+8+32 {
940 return Err(DecodeError::WrongLength);
942 let mut channel_id = [0; 32];
943 channel_id[..].copy_from_slice(&v[0..32]);
944 let mut payment_preimage = [0; 32];
945 payment_preimage.copy_from_slice(&v[40..72]);
948 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
953 impl MsgEncodable for UpdateFulfillHTLC {
954 fn encode(&self) -> Vec<u8> {
955 let mut res = Vec::with_capacity(32+8+32);
956 res.extend_from_slice(&self.channel_id);
957 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
958 res.extend_from_slice(&self.payment_preimage);
963 impl MsgDecodable for UpdateFailHTLC {
964 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
966 return Err(DecodeError::WrongLength);
968 let mut channel_id = [0; 32];
969 channel_id[..].copy_from_slice(&v[0..32]);
972 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
973 reason: OnionErrorPacket::decode(&v[40..])?,
977 impl MsgEncodable for UpdateFailHTLC {
978 fn encode(&self) -> Vec<u8> {
979 let reason = self.reason.encode();
980 let mut res = Vec::with_capacity(32+8+reason.len());
981 res.extend_from_slice(&self.channel_id);
982 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
983 res.extend_from_slice(&reason[..]);
988 impl MsgDecodable for UpdateFailMalformedHTLC {
989 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
990 if v.len() < 32+8+32+2 {
991 return Err(DecodeError::WrongLength);
993 let mut channel_id = [0; 32];
994 channel_id[..].copy_from_slice(&v[0..32]);
995 let mut sha256_of_onion = [0; 32];
996 sha256_of_onion.copy_from_slice(&v[40..72]);
999 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
1001 failure_code: byte_utils::slice_to_be16(&v[72..74]),
1005 impl MsgEncodable for UpdateFailMalformedHTLC {
1006 fn encode(&self) -> Vec<u8> {
1007 let mut res = Vec::with_capacity(32+8+32+2);
1008 res.extend_from_slice(&self.channel_id);
1009 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
1010 res.extend_from_slice(&self.sha256_of_onion);
1011 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
1016 impl MsgDecodable for CommitmentSigned {
1017 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1018 if v.len() < 32+64+2 {
1019 return Err(DecodeError::WrongLength);
1021 let mut channel_id = [0; 32];
1022 channel_id[..].copy_from_slice(&v[0..32]);
1024 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
1025 if v.len() < 32+64+2+htlcs*64 {
1026 return Err(DecodeError::WrongLength);
1028 let mut htlc_signatures = Vec::with_capacity(htlcs);
1029 let secp_ctx = Secp256k1::without_caps();
1031 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
1035 signature: secp_signature!(&secp_ctx, &v[32..96]),
1040 impl MsgEncodable for CommitmentSigned {
1041 fn encode(&self) -> Vec<u8> {
1042 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
1043 res.extend_from_slice(&self.channel_id);
1044 let secp_ctx = Secp256k1::without_caps();
1045 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1046 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
1047 for i in 0..self.htlc_signatures.len() {
1048 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
1054 impl MsgDecodable for RevokeAndACK {
1055 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1056 if v.len() < 32+32+33 {
1057 return Err(DecodeError::WrongLength);
1059 let mut channel_id = [0; 32];
1060 channel_id[..].copy_from_slice(&v[0..32]);
1061 let mut per_commitment_secret = [0; 32];
1062 per_commitment_secret.copy_from_slice(&v[32..64]);
1063 let secp_ctx = Secp256k1::without_caps();
1066 per_commitment_secret,
1067 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
1071 impl MsgEncodable for RevokeAndACK {
1072 fn encode(&self) -> Vec<u8> {
1073 let mut res = Vec::with_capacity(32+32+33);
1074 res.extend_from_slice(&self.channel_id);
1075 res.extend_from_slice(&self.per_commitment_secret);
1076 res.extend_from_slice(&self.next_per_commitment_point.serialize());
1081 impl MsgDecodable for UpdateFee {
1082 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1084 return Err(DecodeError::WrongLength);
1086 let mut channel_id = [0; 32];
1087 channel_id[..].copy_from_slice(&v[0..32]);
1090 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1094 impl MsgEncodable for UpdateFee {
1095 fn encode(&self) -> Vec<u8> {
1096 let mut res = Vec::with_capacity(32+4);
1097 res.extend_from_slice(&self.channel_id);
1098 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1103 impl MsgDecodable for ChannelReestablish {
1104 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1108 impl MsgEncodable for ChannelReestablish {
1109 fn encode(&self) -> Vec<u8> {
1114 impl MsgDecodable for AnnouncementSignatures {
1115 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1116 if v.len() < 32+8+64*2 {
1117 return Err(DecodeError::WrongLength);
1119 let secp_ctx = Secp256k1::without_caps();
1120 let mut channel_id = [0; 32];
1121 channel_id[..].copy_from_slice(&v[0..32]);
1124 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1125 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1126 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1130 impl MsgEncodable for AnnouncementSignatures {
1131 fn encode(&self) -> Vec<u8> {
1132 let mut res = Vec::with_capacity(32+8+64*2);
1133 res.extend_from_slice(&self.channel_id);
1134 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1135 let secp_ctx = Secp256k1::without_caps();
1136 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1137 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1142 impl MsgDecodable for UnsignedNodeAnnouncement {
1143 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1144 let features = GlobalFeatures::decode(&v[..])?;
1145 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1146 return Err(DecodeError::WrongLength);
1148 let start = features.encoded_len();
1150 let mut rgb = [0; 3];
1151 rgb.copy_from_slice(&v[start + 37..start + 40]);
1153 let mut alias = [0; 32];
1154 alias.copy_from_slice(&v[start + 40..start + 72]);
1156 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1157 if v.len() < start + 74 + addrlen {
1158 return Err(DecodeError::WrongLength);
1161 let mut addresses = Vec::with_capacity(4);
1162 let mut read_pos = start + 74;
1164 if v.len() <= read_pos { break; }
1166 0 => { read_pos += 1; },
1168 if v.len() < read_pos + 1 + 6 {
1169 return Err(DecodeError::WrongLength);
1171 if addresses.len() > 0 {
1172 return Err(DecodeError::ExtraAddressesPerType);
1174 let mut addr = [0; 4];
1175 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1176 addresses.push(NetAddress::IPv4 {
1178 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1183 if v.len() < read_pos + 1 + 18 {
1184 return Err(DecodeError::WrongLength);
1186 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1187 return Err(DecodeError::ExtraAddressesPerType);
1189 let mut addr = [0; 16];
1190 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1191 addresses.push(NetAddress::IPv6 {
1193 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1198 if v.len() < read_pos + 1 + 12 {
1199 return Err(DecodeError::WrongLength);
1201 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1202 return Err(DecodeError::ExtraAddressesPerType);
1204 let mut addr = [0; 10];
1205 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1206 addresses.push(NetAddress::OnionV2 {
1208 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1213 if v.len() < read_pos + 1 + 37 {
1214 return Err(DecodeError::WrongLength);
1216 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1217 return Err(DecodeError::ExtraAddressesPerType);
1219 let mut ed25519_pubkey = [0; 32];
1220 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1221 addresses.push(NetAddress::OnionV3 {
1223 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1224 version: v[read_pos + 35],
1225 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1229 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1233 let secp_ctx = Secp256k1::without_caps();
1236 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1237 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1244 impl MsgEncodable for UnsignedNodeAnnouncement {
1245 fn encode(&self) -> Vec<u8> {
1246 let features = self.features.encode();
1247 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1248 res.extend_from_slice(&features[..]);
1249 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1250 res.extend_from_slice(&self.node_id.serialize());
1251 res.extend_from_slice(&self.rgb);
1252 res.extend_from_slice(&self.alias);
1253 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1254 let mut addrs_to_encode = self.addresses.clone();
1255 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1256 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1257 for addr in addrs_to_encode.iter() {
1259 &NetAddress::IPv4{addr, port} => {
1261 addr_slice.extend_from_slice(&addr);
1262 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1264 &NetAddress::IPv6{addr, port} => {
1266 addr_slice.extend_from_slice(&addr);
1267 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1269 &NetAddress::OnionV2{addr, port} => {
1271 addr_slice.extend_from_slice(&addr);
1272 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1274 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1276 addr_slice.extend_from_slice(&ed25519_pubkey);
1277 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1278 addr_slice.push(version);
1279 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1283 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1284 res.extend_from_slice(&addr_slice[..]);
1289 impl MsgDecodable for NodeAnnouncement {
1290 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1292 return Err(DecodeError::WrongLength);
1294 let secp_ctx = Secp256k1::without_caps();
1296 signature: secp_signature!(&secp_ctx, &v[0..64]),
1297 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1301 impl MsgEncodable for NodeAnnouncement {
1302 fn encode(&self) -> Vec<u8> {
1303 let contents = self.contents.encode();
1304 let mut res = Vec::with_capacity(64 + contents.len());
1305 let secp_ctx = Secp256k1::without_caps();
1306 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1307 res.extend_from_slice(&contents);
1312 impl MsgDecodable for UnsignedChannelAnnouncement {
1313 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1314 let features = GlobalFeatures::decode(&v[..])?;
1315 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1316 return Err(DecodeError::WrongLength);
1318 let start = features.encoded_len();
1319 let secp_ctx = Secp256k1::without_caps();
1322 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1323 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1324 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1325 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1326 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1327 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1331 impl MsgEncodable for UnsignedChannelAnnouncement {
1332 fn encode(&self) -> Vec<u8> {
1333 let features = self.features.encode();
1334 let mut res = Vec::with_capacity(172 + features.len());
1335 res.extend_from_slice(&features[..]);
1336 res.extend_from_slice(&self.chain_hash[..]);
1337 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1338 res.extend_from_slice(&self.node_id_1.serialize());
1339 res.extend_from_slice(&self.node_id_2.serialize());
1340 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1341 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1346 impl MsgDecodable for ChannelAnnouncement {
1347 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1349 return Err(DecodeError::WrongLength);
1351 let secp_ctx = Secp256k1::without_caps();
1353 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1354 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1355 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1356 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1357 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1361 impl MsgEncodable for ChannelAnnouncement {
1362 fn encode(&self) -> Vec<u8> {
1363 let secp_ctx = Secp256k1::without_caps();
1364 let contents = self.contents.encode();
1365 let mut res = Vec::with_capacity(64 + contents.len());
1366 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1367 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1368 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1369 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1370 res.extend_from_slice(&contents);
1375 impl MsgDecodable for UnsignedChannelUpdate {
1376 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1377 if v.len() < 32+8+4+2+2+8+4+4 {
1378 return Err(DecodeError::WrongLength);
1381 chain_hash: deserialize(&v[0..32]).unwrap(),
1382 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1383 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1384 flags: byte_utils::slice_to_be16(&v[44..46]),
1385 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1386 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1387 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1388 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1392 impl MsgEncodable for UnsignedChannelUpdate {
1393 fn encode(&self) -> Vec<u8> {
1394 let mut res = Vec::with_capacity(64);
1395 res.extend_from_slice(&self.chain_hash[..]);
1396 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1397 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1398 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1399 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1400 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1401 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1402 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1407 impl MsgDecodable for ChannelUpdate {
1408 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1410 return Err(DecodeError::WrongLength);
1412 let secp_ctx = Secp256k1::without_caps();
1414 signature: secp_signature!(&secp_ctx, &v[0..64]),
1415 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1419 impl MsgEncodable for ChannelUpdate {
1420 fn encode(&self) -> Vec<u8> {
1421 let mut res = Vec::with_capacity(128);
1422 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1423 res.extend_from_slice(&self.contents.encode()[..]);
1428 impl MsgDecodable for OnionRealm0HopData {
1429 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1431 return Err(DecodeError::WrongLength);
1433 Ok(OnionRealm0HopData {
1434 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1435 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1436 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1440 impl MsgEncodable for OnionRealm0HopData {
1441 fn encode(&self) -> Vec<u8> {
1442 let mut res = Vec::with_capacity(32);
1443 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1444 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1445 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1451 impl MsgDecodable for OnionHopData {
1452 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1454 return Err(DecodeError::WrongLength);
1458 return Err(DecodeError::UnknownRealmByte);
1460 let mut hmac = [0; 32];
1461 hmac[..].copy_from_slice(&v[33..65]);
1464 data: OnionRealm0HopData::decode(&v[1..33])?,
1469 impl MsgEncodable for OnionHopData {
1470 fn encode(&self) -> Vec<u8> {
1471 let mut res = Vec::with_capacity(65);
1472 res.push(self.realm);
1473 res.extend_from_slice(&self.data.encode()[..]);
1474 res.extend_from_slice(&self.hmac);
1479 impl MsgDecodable for OnionPacket {
1480 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1481 if v.len() < 1+33+20*65+32 {
1482 return Err(DecodeError::WrongLength);
1484 let mut hop_data = [0; 20*65];
1485 hop_data.copy_from_slice(&v[34..1334]);
1486 let mut hmac = [0; 32];
1487 hmac.copy_from_slice(&v[1334..1366]);
1488 let secp_ctx = Secp256k1::without_caps();
1491 public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1497 impl MsgEncodable for OnionPacket {
1498 fn encode(&self) -> Vec<u8> {
1499 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1500 res.push(self.version);
1501 res.extend_from_slice(&self.public_key.serialize());
1502 res.extend_from_slice(&self.hop_data);
1503 res.extend_from_slice(&self.hmac);
1508 impl MsgDecodable for DecodedOnionErrorPacket {
1509 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1510 if v.len() < 32 + 4 {
1511 return Err(DecodeError::WrongLength);
1513 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1514 if v.len() < 32 + 4 + failuremsg_len {
1515 return Err(DecodeError::WrongLength);
1517 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1518 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1519 return Err(DecodeError::WrongLength);
1522 let mut hmac = [0; 32];
1523 hmac.copy_from_slice(&v[0..32]);
1526 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1527 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1531 impl MsgEncodable for DecodedOnionErrorPacket {
1532 fn encode(&self) -> Vec<u8> {
1533 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1534 res.extend_from_slice(&self.hmac);
1535 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1536 res.extend_from_slice(&self.failuremsg);
1537 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1538 res.extend_from_slice(&self.pad);
1543 impl MsgDecodable for OnionErrorPacket {
1544 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1546 return Err(DecodeError::WrongLength);
1548 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1549 if v.len() < 2 + len {
1550 return Err(DecodeError::WrongLength);
1553 data: v[2..len+2].to_vec(),
1557 impl MsgEncodable for OnionErrorPacket {
1558 fn encode(&self) -> Vec<u8> {
1559 let mut res = Vec::with_capacity(2 + self.data.len());
1560 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1561 res.extend_from_slice(&self.data);