1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use bitcoin::util::uint::Uint256;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::{deserialize,serialize};
6 use bitcoin::blockdata::script::Script;
10 use std::result::Result;
12 use util::{byte_utils, internal_traits, events};
14 pub trait MsgEncodable {
15 fn encode(&self) -> Vec<u8>;
17 fn encoded_len(&self) -> usize { self.encode().len() }
19 fn encode_with_len(&self) -> Vec<u8> {
20 let enc = self.encode();
21 let mut res = Vec::with_capacity(enc.len() + 2);
22 res.extend_from_slice(&byte_utils::be16_to_array(enc.len() as u16));
23 res.extend_from_slice(&enc);
28 pub enum DecodeError {
29 /// Unknown realm byte in an OnionHopData packet
31 /// Failed to decode a public key (ie it's invalid)
33 /// Failed to decode a signature (ie it's invalid)
35 /// Buffer not of right length (either too short or too long)
37 /// node_announcement included more than one address of a given type!
38 ExtraAddressesPerType,
40 pub trait MsgDecodable: Sized {
41 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
44 /// Tracks localfeatures which are only in init messages
45 #[derive(Clone, PartialEq)]
46 pub struct LocalFeatures {
51 pub fn new() -> LocalFeatures {
57 pub fn supports_data_loss_protect(&self) -> bool {
58 self.flags.len() > 0 && (self.flags[0] & 3) != 0
60 pub fn requires_data_loss_protect(&self) -> bool {
61 self.flags.len() > 0 && (self.flags[0] & 1) != 0
64 pub fn supports_initial_routing_sync(&self) -> bool {
65 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
68 pub fn supports_upfront_shutdown_script(&self) -> bool {
69 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
71 pub fn requires_upfront_shutdown_script(&self) -> bool {
72 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
75 pub fn requires_unknown_bits(&self) -> bool {
76 for (idx, &byte) in self.flags.iter().enumerate() {
77 if idx != 0 && (byte & 0x55) != 0 {
79 } else if idx == 0 && (byte & 0x14) != 0 {
86 pub fn supports_unknown_bits(&self) -> bool {
87 for (idx, &byte) in self.flags.iter().enumerate() {
88 if idx != 0 && byte != 0 {
90 } else if idx == 0 && (byte & 0xc4) != 0 {
98 /// Tracks globalfeatures which are in init messages and routing announcements
99 #[derive(Clone, PartialEq)]
100 pub struct GlobalFeatures {
104 impl GlobalFeatures {
105 pub fn new() -> GlobalFeatures {
111 pub fn requires_unknown_bits(&self) -> bool {
112 for &byte in self.flags.iter() {
113 if (byte & 0x55) != 0 {
120 pub fn supports_unknown_bits(&self) -> bool {
121 for &byte in self.flags.iter() {
131 pub global_features: GlobalFeatures,
132 pub local_features: LocalFeatures,
135 pub struct OpenChannel {
136 pub chain_hash: Sha256dHash,
137 pub temporary_channel_id: Uint256,
138 pub funding_satoshis: u64,
140 pub dust_limit_satoshis: u64,
141 pub max_htlc_value_in_flight_msat: u64,
142 pub channel_reserve_satoshis: u64,
143 pub htlc_minimum_msat: u64,
144 pub feerate_per_kw: u32,
145 pub to_self_delay: u16,
146 pub max_accepted_htlcs: u16,
147 pub funding_pubkey: PublicKey,
148 pub revocation_basepoint: PublicKey,
149 pub payment_basepoint: PublicKey,
150 pub delayed_payment_basepoint: PublicKey,
151 pub htlc_basepoint: PublicKey,
152 pub first_per_commitment_point: PublicKey,
153 pub channel_flags: u8,
154 pub shutdown_scriptpubkey: Option<Script>,
157 pub struct AcceptChannel {
158 pub temporary_channel_id: Uint256,
159 pub dust_limit_satoshis: u64,
160 pub max_htlc_value_in_flight_msat: u64,
161 pub channel_reserve_satoshis: u64,
162 pub htlc_minimum_msat: u64,
163 pub minimum_depth: u32,
164 pub to_self_delay: u16,
165 pub max_accepted_htlcs: u16,
166 pub funding_pubkey: PublicKey,
167 pub revocation_basepoint: PublicKey,
168 pub payment_basepoint: PublicKey,
169 pub delayed_payment_basepoint: PublicKey,
170 pub htlc_basepoint: PublicKey,
171 pub first_per_commitment_point: PublicKey,
172 pub shutdown_scriptpubkey: Option<Script>,
175 pub struct FundingCreated {
176 pub temporary_channel_id: Uint256,
177 pub funding_txid: Sha256dHash,
178 pub funding_output_index: u16,
179 pub signature: Signature,
182 pub struct FundingSigned {
183 pub channel_id: Uint256,
184 pub signature: Signature,
187 pub struct FundingLocked {
188 pub channel_id: Uint256,
189 pub next_per_commitment_point: PublicKey,
192 pub struct Shutdown {
193 pub channel_id: Uint256,
194 pub scriptpubkey: Script,
197 pub struct ClosingSigned {
198 pub channel_id: Uint256,
199 pub fee_satoshis: u64,
200 pub signature: Signature,
204 pub struct UpdateAddHTLC {
205 pub channel_id: Uint256,
207 pub amount_msat: u64,
208 pub payment_hash: [u8; 32],
209 pub cltv_expiry: u32,
210 pub onion_routing_packet: OnionPacket,
214 pub struct UpdateFulfillHTLC {
215 pub channel_id: Uint256,
217 pub payment_preimage: [u8; 32],
221 pub struct UpdateFailHTLC {
222 pub channel_id: Uint256,
224 pub reason: OnionErrorPacket,
228 pub struct UpdateFailMalformedHTLC {
229 pub channel_id: Uint256,
231 pub sha256_of_onion: [u8; 32],
232 pub failure_code: u16,
236 pub struct CommitmentSigned {
237 pub channel_id: Uint256,
238 pub signature: Signature,
239 pub htlc_signatures: Vec<Signature>,
242 pub struct RevokeAndACK {
243 pub channel_id: Uint256,
244 pub per_commitment_secret: [u8; 32],
245 pub next_per_commitment_point: PublicKey,
248 pub struct UpdateFee {
249 pub channel_id: Uint256,
250 pub feerate_per_kw: u32,
253 pub struct ChannelReestablish {
254 pub channel_id: Uint256,
255 pub next_local_commitment_number: u64,
256 pub next_remote_commitment_number: u64,
257 pub your_last_per_commitment_secret: Option<[u8; 32]>,
258 pub my_current_per_commitment_point: PublicKey,
262 pub struct AnnouncementSignatures {
263 pub channel_id: Uint256,
264 pub short_channel_id: u64,
265 pub node_signature: Signature,
266 pub bitcoin_signature: Signature,
270 pub enum NetAddress {
284 ed25519_pubkey: [u8; 32],
291 fn get_id(&self) -> u8 {
293 &NetAddress::IPv4 {..} => { 1 },
294 &NetAddress::IPv6 {..} => { 2 },
295 &NetAddress::OnionV2 {..} => { 3 },
296 &NetAddress::OnionV3 {..} => { 4 },
301 pub struct UnsignedNodeAnnouncement {
302 pub features: GlobalFeatures,
304 pub node_id: PublicKey,
307 /// List of addresses on which this node is reachable. Note that you may only have up to one
308 /// address of each type, if you have more, they may be silently discarded or we may panic!
309 pub addresses: Vec<NetAddress>,
311 pub struct NodeAnnouncement {
312 pub signature: Signature,
313 pub contents: UnsignedNodeAnnouncement,
316 #[derive(PartialEq, Clone)]
317 pub struct UnsignedChannelAnnouncement {
318 pub features: GlobalFeatures,
319 pub chain_hash: Sha256dHash,
320 pub short_channel_id: u64,
321 pub node_id_1: PublicKey,
322 pub node_id_2: PublicKey,
323 pub bitcoin_key_1: PublicKey,
324 pub bitcoin_key_2: PublicKey,
326 #[derive(PartialEq, Clone)]
327 pub struct ChannelAnnouncement {
328 pub node_signature_1: Signature,
329 pub node_signature_2: Signature,
330 pub bitcoin_signature_1: Signature,
331 pub bitcoin_signature_2: Signature,
332 pub contents: UnsignedChannelAnnouncement,
335 #[derive(PartialEq, Clone)]
336 pub struct UnsignedChannelUpdate {
337 pub chain_hash: Sha256dHash,
338 pub short_channel_id: u64,
341 pub cltv_expiry_delta: u16,
342 pub htlc_minimum_msat: u64,
343 pub fee_base_msat: u32,
344 pub fee_proportional_millionths: u32,
346 #[derive(PartialEq, Clone)]
347 pub struct ChannelUpdate {
348 pub signature: Signature,
349 pub contents: UnsignedChannelUpdate,
352 /// Used to put an error message in a HandleError
353 pub enum ErrorAction {
354 /// Indicates an inbound HTLC add resulted in a failure, and the UpdateFailHTLC provided in msg
355 /// should be sent back to the sender.
359 /// The peer took some action which made us think they were useless. Disconnect them.
363 pub struct HandleError { //TODO: rename me
364 pub err: &'static str,
365 pub msg: Option<ErrorAction>, //TODO: Make this required and rename it
368 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
369 /// transaction updates if they were pending.
370 pub struct CommitmentUpdate {
371 pub update_add_htlcs: Vec<UpdateAddHTLC>,
372 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
373 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
374 pub commitment_signed: CommitmentSigned,
377 pub enum HTLCFailChannelUpdate {
378 ChannelUpdateMessage {
382 short_channel_id: u64,
386 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
387 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
388 /// paralell when the two calls have the same their_node_id.
389 pub trait ChannelMessageHandler : events::EventsProvider {
391 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
392 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
393 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
394 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
395 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
398 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
399 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
402 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
403 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
404 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
405 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
406 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
407 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
409 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
411 // Channel-to-announce:
412 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
415 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
416 /// is believed to be possible in the future (eg they're sending us messages we don't
417 /// understand or indicate they require unknown feature bits), no_connection_possible is set
418 /// and any outstanding channels should be failed.
419 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
422 pub trait RoutingMessageHandler {
423 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
424 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
425 /// or returning an Err otherwise.
426 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
427 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
428 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
431 pub struct OnionRealm0HopData {
432 pub short_channel_id: u64,
433 pub amt_to_forward: u64,
434 pub outgoing_cltv_value: u32,
435 // 12 bytes of 0-padding
438 pub struct OnionHopData {
440 pub data: OnionRealm0HopData,
443 unsafe impl internal_traits::NoDealloc for OnionHopData{}
446 pub struct OnionPacket {
448 pub public_key: PublicKey,
449 pub hop_data: [u8; 20*65],
453 pub struct DecodedOnionErrorPacket {
455 pub failuremsg: Vec<u8>,
460 pub struct OnionErrorPacket {
461 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
462 // (TODO) We limit it in decode to much lower...
466 impl Error for DecodeError {
467 fn description(&self) -> &str {
469 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
470 DecodeError::BadPublicKey => "Invalid public key in packet",
471 DecodeError::BadSignature => "Invalid signature in packet",
472 DecodeError::WrongLength => "Data was wrong length for packet",
473 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
477 impl fmt::Display for DecodeError {
478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
479 f.write_str(self.description())
483 impl fmt::Debug for HandleError {
484 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
485 f.write_str(self.err)
489 macro_rules! secp_pubkey {
490 ( $ctx: expr, $slice: expr ) => {
491 match PublicKey::from_slice($ctx, $slice) {
493 Err(_) => return Err(DecodeError::BadPublicKey)
498 macro_rules! secp_signature {
499 ( $ctx: expr, $slice: expr ) => {
500 match Signature::from_compact($ctx, $slice) {
502 Err(_) => return Err(DecodeError::BadSignature)
507 impl MsgDecodable for LocalFeatures {
508 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
509 if v.len() < 3 { return Err(DecodeError::WrongLength); }
510 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
511 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
512 let mut flags = Vec::with_capacity(len);
513 flags.extend_from_slice(&v[2..2 + len]);
519 impl MsgEncodable for LocalFeatures {
520 fn encode(&self) -> Vec<u8> {
521 let mut res = Vec::with_capacity(self.flags.len() + 2);
522 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
523 res.extend_from_slice(&self.flags[..]);
526 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
529 impl MsgDecodable for GlobalFeatures {
530 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
531 if v.len() < 3 { return Err(DecodeError::WrongLength); }
532 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
533 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
534 let mut flags = Vec::with_capacity(len);
535 flags.extend_from_slice(&v[2..2 + len]);
541 impl MsgEncodable for GlobalFeatures {
542 fn encode(&self) -> Vec<u8> {
543 let mut res = Vec::with_capacity(self.flags.len() + 2);
544 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
545 res.extend_from_slice(&self.flags[..]);
548 fn encoded_len(&self) -> usize { self.flags.len() + 2 }
551 impl MsgDecodable for Init {
552 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
553 let global_features = GlobalFeatures::decode(v)?;
554 if v.len() < global_features.flags.len() + 4 {
555 return Err(DecodeError::WrongLength);
557 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
559 global_features: global_features,
560 local_features: local_features,
564 impl MsgEncodable for Init {
565 fn encode(&self) -> Vec<u8> {
566 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
567 res.extend_from_slice(&self.global_features.encode()[..]);
568 res.extend_from_slice(&self.local_features.encode()[..]);
573 impl MsgDecodable for OpenChannel {
574 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
575 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
576 return Err(DecodeError::WrongLength);
578 let ctx = Secp256k1::without_caps();
580 let mut shutdown_scriptpubkey = None;
582 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
583 if v.len() < 321+len {
584 return Err(DecodeError::WrongLength);
586 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
587 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
588 return Err(DecodeError::WrongLength);
592 chain_hash: deserialize(&v[0..32]).unwrap(),
593 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
594 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
595 push_msat: byte_utils::slice_to_be64(&v[72..80]),
596 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
597 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
598 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
599 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
600 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
601 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
602 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
603 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
604 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
605 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
606 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
607 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
608 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
609 channel_flags: v[318],
610 shutdown_scriptpubkey: shutdown_scriptpubkey
614 impl MsgEncodable for OpenChannel {
615 fn encode(&self) -> Vec<u8> {
616 let mut res = match &self.shutdown_scriptpubkey {
617 &Some(ref script) => Vec::with_capacity(319 + 2 + script.len()),
618 &None => Vec::with_capacity(319),
620 res.extend_from_slice(&serialize(&self.chain_hash).unwrap());
621 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap());
622 res.extend_from_slice(&byte_utils::be64_to_array(self.funding_satoshis));
623 res.extend_from_slice(&byte_utils::be64_to_array(self.push_msat));
624 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
625 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
626 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
627 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
628 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
629 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
630 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
631 res.extend_from_slice(&self.funding_pubkey.serialize());
632 res.extend_from_slice(&self.revocation_basepoint.serialize());
633 res.extend_from_slice(&self.payment_basepoint.serialize());
634 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
635 res.extend_from_slice(&self.htlc_basepoint.serialize());
636 res.extend_from_slice(&self.first_per_commitment_point.serialize());
637 res.push(self.channel_flags);
638 if let &Some(ref script) = &self.shutdown_scriptpubkey {
639 res.extend_from_slice(&byte_utils::be16_to_array(script.len() as u16));
640 res.extend_from_slice(&script[..]);
646 impl MsgDecodable for AcceptChannel {
647 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
648 if v.len() < 32+4*8+4+2*2+6*33 {
649 return Err(DecodeError::WrongLength);
651 let ctx = Secp256k1::without_caps();
653 let mut shutdown_scriptpubkey = None;
655 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
656 if v.len() < 272+len {
657 return Err(DecodeError::WrongLength);
659 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
660 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
661 return Err(DecodeError::WrongLength);
665 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
666 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
667 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
668 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
669 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
670 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
671 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
672 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
673 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
674 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
675 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
676 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
677 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
678 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
679 shutdown_scriptpubkey: shutdown_scriptpubkey
683 impl MsgEncodable for AcceptChannel {
684 fn encode(&self) -> Vec<u8> {
685 let mut res = match &self.shutdown_scriptpubkey {
686 &Some(ref script) => Vec::with_capacity(270 + 2 + script.len()),
687 &None => Vec::with_capacity(270),
689 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
690 res.extend_from_slice(&byte_utils::be64_to_array(self.dust_limit_satoshis));
691 res.extend_from_slice(&byte_utils::be64_to_array(self.max_htlc_value_in_flight_msat));
692 res.extend_from_slice(&byte_utils::be64_to_array(self.channel_reserve_satoshis));
693 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
694 res.extend_from_slice(&byte_utils::be32_to_array(self.minimum_depth));
695 res.extend_from_slice(&byte_utils::be16_to_array(self.to_self_delay));
696 res.extend_from_slice(&byte_utils::be16_to_array(self.max_accepted_htlcs));
697 res.extend_from_slice(&self.funding_pubkey.serialize());
698 res.extend_from_slice(&self.revocation_basepoint.serialize());
699 res.extend_from_slice(&self.payment_basepoint.serialize());
700 res.extend_from_slice(&self.delayed_payment_basepoint.serialize());
701 res.extend_from_slice(&self.htlc_basepoint.serialize());
702 res.extend_from_slice(&self.first_per_commitment_point.serialize());
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 FundingCreated {
712 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
713 if v.len() < 32+32+2+64 {
714 return Err(DecodeError::WrongLength);
716 let ctx = Secp256k1::without_caps();
718 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
719 funding_txid: deserialize(&v[32..64]).unwrap(),
720 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
721 signature: secp_signature!(&ctx, &v[66..130]),
725 impl MsgEncodable for FundingCreated {
726 fn encode(&self) -> Vec<u8> {
727 let mut res = Vec::with_capacity(32+32+2+64);
728 res.extend_from_slice(&serialize(&self.temporary_channel_id).unwrap()[..]);
729 res.extend_from_slice(&serialize(&self.funding_txid).unwrap()[..]);
730 res.extend_from_slice(&byte_utils::be16_to_array(self.funding_output_index));
731 let secp_ctx = Secp256k1::without_caps();
732 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
737 impl MsgDecodable for FundingSigned {
738 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
740 return Err(DecodeError::WrongLength);
742 let ctx = Secp256k1::without_caps();
744 channel_id: deserialize(&v[0..32]).unwrap(),
745 signature: secp_signature!(&ctx, &v[32..96]),
749 impl MsgEncodable for FundingSigned {
750 fn encode(&self) -> Vec<u8> {
751 let mut res = Vec::with_capacity(32+64);
752 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
753 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps()));
758 impl MsgDecodable for FundingLocked {
759 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
761 return Err(DecodeError::WrongLength);
763 let ctx = Secp256k1::without_caps();
765 channel_id: deserialize(&v[0..32]).unwrap(),
766 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
770 impl MsgEncodable for FundingLocked {
771 fn encode(&self) -> Vec<u8> {
772 let mut res = Vec::with_capacity(32+33);
773 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
774 res.extend_from_slice(&self.next_per_commitment_point.serialize());
779 impl MsgDecodable for Shutdown {
780 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
781 if v.len() < 32 + 2 {
782 return Err(DecodeError::WrongLength);
784 let scriptlen = byte_utils::slice_to_be16(&v[32..34]) as usize;
785 if v.len() < 32 + 2 + scriptlen {
786 return Err(DecodeError::WrongLength);
789 channel_id: deserialize(&v[0..32]).unwrap(),
790 scriptpubkey: Script::from(v[34..34 + scriptlen].to_vec()),
794 impl MsgEncodable for Shutdown {
795 fn encode(&self) -> Vec<u8> {
796 let mut res = Vec::with_capacity(32 + 2 + self.scriptpubkey.len());
797 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
798 res.extend_from_slice(&byte_utils::be16_to_array(self.scriptpubkey.len() as u16));
799 res.extend_from_slice(&self.scriptpubkey[..]);
804 impl MsgDecodable for ClosingSigned {
805 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
806 if v.len() < 32 + 8 + 64 {
807 return Err(DecodeError::WrongLength);
809 let secp_ctx = Secp256k1::without_caps();
811 channel_id: deserialize(&v[0..32]).unwrap(),
812 fee_satoshis: byte_utils::slice_to_be64(&v[32..40]),
813 signature: secp_signature!(&secp_ctx, &v[40..104]),
817 impl MsgEncodable for ClosingSigned {
818 fn encode(&self) -> Vec<u8> {
819 let mut res = Vec::with_capacity(32+8+64);
820 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
821 res.extend_from_slice(&byte_utils::be64_to_array(self.fee_satoshis));
822 let secp_ctx = Secp256k1::without_caps();
823 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
828 impl MsgDecodable for UpdateAddHTLC {
829 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
830 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
831 return Err(DecodeError::WrongLength);
833 let mut payment_hash = [0; 32];
834 payment_hash.copy_from_slice(&v[48..80]);
836 channel_id: deserialize(&v[0..32]).unwrap(),
837 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
838 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
840 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
841 onion_routing_packet: OnionPacket::decode(&v[84..84+1366])?,
845 impl MsgEncodable for UpdateAddHTLC {
846 fn encode(&self) -> Vec<u8> {
847 let mut res = Vec::with_capacity(32+8+8+32+4+1+1366);
848 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
849 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
850 res.extend_from_slice(&byte_utils::be64_to_array(self.amount_msat));
851 res.extend_from_slice(&self.payment_hash);
852 res.extend_from_slice(&byte_utils::be32_to_array(self.cltv_expiry));
853 res.extend_from_slice(&self.onion_routing_packet.encode()[..]);
858 impl MsgDecodable for UpdateFulfillHTLC {
859 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
860 if v.len() < 32+8+32 {
861 return Err(DecodeError::WrongLength);
863 let mut payment_preimage = [0; 32];
864 payment_preimage.copy_from_slice(&v[40..72]);
866 channel_id: deserialize(&v[0..32]).unwrap(),
867 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
872 impl MsgEncodable for UpdateFulfillHTLC {
873 fn encode(&self) -> Vec<u8> {
874 let mut res = Vec::with_capacity(32+8+32);
875 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
876 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
877 res.extend_from_slice(&self.payment_preimage);
882 impl MsgDecodable for UpdateFailHTLC {
883 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
885 return Err(DecodeError::WrongLength);
888 channel_id: deserialize(&v[0..32]).unwrap(),
889 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
890 reason: OnionErrorPacket::decode(&v[40..])?,
894 impl MsgEncodable for UpdateFailHTLC {
895 fn encode(&self) -> Vec<u8> {
896 let reason = self.reason.encode();
897 let mut res = Vec::with_capacity(32+8+reason.len());
898 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
899 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
900 res.extend_from_slice(&reason[..]);
905 impl MsgDecodable for UpdateFailMalformedHTLC {
906 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
907 if v.len() < 32+8+32+2 {
908 return Err(DecodeError::WrongLength);
910 let mut sha256_of_onion = [0; 32];
911 sha256_of_onion.copy_from_slice(&v[40..72]);
913 channel_id: deserialize(&v[0..32]).unwrap(),
914 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
916 failure_code: byte_utils::slice_to_be16(&v[72..74]),
920 impl MsgEncodable for UpdateFailMalformedHTLC {
921 fn encode(&self) -> Vec<u8> {
922 let mut res = Vec::with_capacity(32+8+32+2);
923 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
924 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_id));
925 res.extend_from_slice(&self.sha256_of_onion);
926 res.extend_from_slice(&byte_utils::be16_to_array(self.failure_code));
931 impl MsgDecodable for CommitmentSigned {
932 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
933 if v.len() < 32+64+2 {
934 return Err(DecodeError::WrongLength);
936 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
937 if v.len() < 32+64+2+htlcs*64 {
938 return Err(DecodeError::WrongLength);
940 let mut htlc_signatures = Vec::with_capacity(htlcs);
941 let secp_ctx = Secp256k1::without_caps();
943 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
946 channel_id: deserialize(&v[0..32]).unwrap(),
947 signature: secp_signature!(&secp_ctx, &v[32..96]),
952 impl MsgEncodable for CommitmentSigned {
953 fn encode(&self) -> Vec<u8> {
954 let mut res = Vec::with_capacity(32+64+2+self.htlc_signatures.len()*64);
955 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
956 let secp_ctx = Secp256k1::without_caps();
957 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
958 res.extend_from_slice(&byte_utils::be16_to_array(self.htlc_signatures.len() as u16));
959 for i in 0..self.htlc_signatures.len() {
960 res.extend_from_slice(&self.htlc_signatures[i].serialize_compact(&secp_ctx));
966 impl MsgDecodable for RevokeAndACK {
967 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
968 if v.len() < 32+32+33 {
969 return Err(DecodeError::WrongLength);
971 let mut per_commitment_secret = [0; 32];
972 per_commitment_secret.copy_from_slice(&v[32..64]);
973 let secp_ctx = Secp256k1::without_caps();
975 channel_id: deserialize(&v[0..32]).unwrap(),
976 per_commitment_secret,
977 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
981 impl MsgEncodable for RevokeAndACK {
982 fn encode(&self) -> Vec<u8> {
983 let mut res = Vec::with_capacity(32+32+33);
984 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
985 res.extend_from_slice(&self.per_commitment_secret);
986 res.extend_from_slice(&self.next_per_commitment_point.serialize());
991 impl MsgDecodable for UpdateFee {
992 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
994 return Err(DecodeError::WrongLength);
997 channel_id: deserialize(&v[0..32]).unwrap(),
998 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
1002 impl MsgEncodable for UpdateFee {
1003 fn encode(&self) -> Vec<u8> {
1004 let mut res = Vec::with_capacity(32+4);
1005 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
1006 res.extend_from_slice(&byte_utils::be32_to_array(self.feerate_per_kw));
1011 impl MsgDecodable for ChannelReestablish {
1012 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1016 impl MsgEncodable for ChannelReestablish {
1017 fn encode(&self) -> Vec<u8> {
1022 impl MsgDecodable for AnnouncementSignatures {
1023 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1024 if v.len() < 32+8+64*2 {
1025 return Err(DecodeError::WrongLength);
1027 let secp_ctx = Secp256k1::without_caps();
1029 channel_id: deserialize(&v[0..32]).unwrap(),
1030 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1031 node_signature: secp_signature!(&secp_ctx, &v[40..104]),
1032 bitcoin_signature: secp_signature!(&secp_ctx, &v[104..168]),
1036 impl MsgEncodable for AnnouncementSignatures {
1037 fn encode(&self) -> Vec<u8> {
1038 let mut res = Vec::with_capacity(32+8+64*2);
1039 res.extend_from_slice(&serialize(&self.channel_id).unwrap());
1040 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1041 let secp_ctx = Secp256k1::without_caps();
1042 res.extend_from_slice(&self.node_signature.serialize_compact(&secp_ctx));
1043 res.extend_from_slice(&self.bitcoin_signature.serialize_compact(&secp_ctx));
1048 impl MsgDecodable for UnsignedNodeAnnouncement {
1049 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1050 let features = GlobalFeatures::decode(&v[..])?;
1051 if v.len() < features.encoded_len() + 4 + 33 + 3 + 32 + 2 {
1052 return Err(DecodeError::WrongLength);
1054 let start = features.encoded_len();
1056 let mut rgb = [0; 3];
1057 rgb.copy_from_slice(&v[start + 37..start + 40]);
1059 let mut alias = [0; 32];
1060 alias.copy_from_slice(&v[start + 40..start + 72]);
1062 let addrlen = byte_utils::slice_to_be16(&v[start + 72..start + 74]) as usize;
1063 if v.len() < start + 74 + addrlen {
1064 return Err(DecodeError::WrongLength);
1067 let mut addresses = Vec::with_capacity(4);
1068 let mut read_pos = start + 74;
1070 if v.len() <= read_pos { break; }
1072 0 => { read_pos += 1; },
1074 if v.len() < read_pos + 1 + 6 {
1075 return Err(DecodeError::WrongLength);
1077 if addresses.len() > 0 {
1078 return Err(DecodeError::ExtraAddressesPerType);
1080 let mut addr = [0; 4];
1081 addr.copy_from_slice(&v[read_pos + 1..read_pos + 5]);
1082 addresses.push(NetAddress::IPv4 {
1084 port: byte_utils::slice_to_be16(&v[read_pos + 5..read_pos + 7]),
1089 if v.len() < read_pos + 1 + 18 {
1090 return Err(DecodeError::WrongLength);
1092 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1093 return Err(DecodeError::ExtraAddressesPerType);
1095 let mut addr = [0; 16];
1096 addr.copy_from_slice(&v[read_pos + 1..read_pos + 17]);
1097 addresses.push(NetAddress::IPv6 {
1099 port: byte_utils::slice_to_be16(&v[read_pos + 17..read_pos + 19]),
1104 if v.len() < read_pos + 1 + 12 {
1105 return Err(DecodeError::WrongLength);
1107 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1108 return Err(DecodeError::ExtraAddressesPerType);
1110 let mut addr = [0; 10];
1111 addr.copy_from_slice(&v[read_pos + 1..read_pos + 11]);
1112 addresses.push(NetAddress::OnionV2 {
1114 port: byte_utils::slice_to_be16(&v[read_pos + 11..read_pos + 13]),
1119 if v.len() < read_pos + 1 + 37 {
1120 return Err(DecodeError::WrongLength);
1122 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1123 return Err(DecodeError::ExtraAddressesPerType);
1125 let mut ed25519_pubkey = [0; 32];
1126 ed25519_pubkey.copy_from_slice(&v[read_pos + 1..read_pos + 33]);
1127 addresses.push(NetAddress::OnionV3 {
1129 checksum: byte_utils::slice_to_be16(&v[read_pos + 33..read_pos + 35]),
1130 version: v[read_pos + 35],
1131 port: byte_utils::slice_to_be16(&v[read_pos + 36..read_pos + 38]),
1135 _ => { break; } // We've read all we can, we dont understand anything higher (and they're sorted)
1139 let secp_ctx = Secp256k1::without_caps();
1142 timestamp: byte_utils::slice_to_be32(&v[start..start + 4]),
1143 node_id: secp_pubkey!(&secp_ctx, &v[start + 4..start + 37]),
1150 impl MsgEncodable for UnsignedNodeAnnouncement {
1151 fn encode(&self) -> Vec<u8> {
1152 let features = self.features.encode();
1153 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
1154 res.extend_from_slice(&features[..]);
1155 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1156 res.extend_from_slice(&self.node_id.serialize());
1157 res.extend_from_slice(&self.rgb);
1158 res.extend_from_slice(&self.alias);
1159 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1160 let mut addrs_to_encode = self.addresses.clone();
1161 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1162 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1163 for addr in addrs_to_encode.iter() {
1165 &NetAddress::IPv4{addr, port} => {
1167 addr_slice.extend_from_slice(&addr);
1168 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1170 &NetAddress::IPv6{addr, port} => {
1172 addr_slice.extend_from_slice(&addr);
1173 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1175 &NetAddress::OnionV2{addr, port} => {
1177 addr_slice.extend_from_slice(&addr);
1178 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1180 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1182 addr_slice.extend_from_slice(&ed25519_pubkey);
1183 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1184 addr_slice.push(version);
1185 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1189 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
1190 res.extend_from_slice(&addr_slice[..]);
1195 impl MsgDecodable for NodeAnnouncement {
1196 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1198 return Err(DecodeError::WrongLength);
1200 let secp_ctx = Secp256k1::without_caps();
1202 signature: secp_signature!(&secp_ctx, &v[0..64]),
1203 contents: UnsignedNodeAnnouncement::decode(&v[64..])?,
1207 impl MsgEncodable for NodeAnnouncement {
1208 fn encode(&self) -> Vec<u8> {
1209 let contents = self.contents.encode();
1210 let mut res = Vec::with_capacity(64 + contents.len());
1211 let secp_ctx = Secp256k1::without_caps();
1212 res.extend_from_slice(&self.signature.serialize_compact(&secp_ctx));
1213 res.extend_from_slice(&contents);
1218 impl MsgDecodable for UnsignedChannelAnnouncement {
1219 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1220 let features = GlobalFeatures::decode(&v[..])?;
1221 if v.len() < features.encoded_len() + 32 + 8 + 33*4 {
1222 return Err(DecodeError::WrongLength);
1224 let start = features.encoded_len();
1225 let secp_ctx = Secp256k1::without_caps();
1228 chain_hash: deserialize(&v[start..start + 32]).unwrap(),
1229 short_channel_id: byte_utils::slice_to_be64(&v[start + 32..start + 40]),
1230 node_id_1: secp_pubkey!(&secp_ctx, &v[start + 40..start + 73]),
1231 node_id_2: secp_pubkey!(&secp_ctx, &v[start + 73..start + 106]),
1232 bitcoin_key_1: secp_pubkey!(&secp_ctx, &v[start + 106..start + 139]),
1233 bitcoin_key_2: secp_pubkey!(&secp_ctx, &v[start + 139..start + 172]),
1237 impl MsgEncodable for UnsignedChannelAnnouncement {
1238 fn encode(&self) -> Vec<u8> {
1239 let features = self.features.encode();
1240 let mut res = Vec::with_capacity(172 + features.len());
1241 res.extend_from_slice(&features[..]);
1242 res.extend_from_slice(&self.chain_hash[..]);
1243 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1244 res.extend_from_slice(&self.node_id_1.serialize());
1245 res.extend_from_slice(&self.node_id_2.serialize());
1246 res.extend_from_slice(&self.bitcoin_key_1.serialize());
1247 res.extend_from_slice(&self.bitcoin_key_2.serialize());
1252 impl MsgDecodable for ChannelAnnouncement {
1253 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1255 return Err(DecodeError::WrongLength);
1257 let secp_ctx = Secp256k1::without_caps();
1259 node_signature_1: secp_signature!(&secp_ctx, &v[0..64]),
1260 node_signature_2: secp_signature!(&secp_ctx, &v[64..128]),
1261 bitcoin_signature_1: secp_signature!(&secp_ctx, &v[128..192]),
1262 bitcoin_signature_2: secp_signature!(&secp_ctx, &v[192..256]),
1263 contents: UnsignedChannelAnnouncement::decode(&v[256..])?,
1267 impl MsgEncodable for ChannelAnnouncement {
1268 fn encode(&self) -> Vec<u8> {
1269 let secp_ctx = Secp256k1::without_caps();
1270 let contents = self.contents.encode();
1271 let mut res = Vec::with_capacity(64 + contents.len());
1272 res.extend_from_slice(&self.node_signature_1.serialize_compact(&secp_ctx));
1273 res.extend_from_slice(&self.node_signature_2.serialize_compact(&secp_ctx));
1274 res.extend_from_slice(&self.bitcoin_signature_1.serialize_compact(&secp_ctx));
1275 res.extend_from_slice(&self.bitcoin_signature_2.serialize_compact(&secp_ctx));
1276 res.extend_from_slice(&contents);
1281 impl MsgDecodable for UnsignedChannelUpdate {
1282 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1283 if v.len() < 32+8+4+2+2+8+4+4 {
1284 return Err(DecodeError::WrongLength);
1287 chain_hash: deserialize(&v[0..32]).unwrap(),
1288 short_channel_id: byte_utils::slice_to_be64(&v[32..40]),
1289 timestamp: byte_utils::slice_to_be32(&v[40..44]),
1290 flags: byte_utils::slice_to_be16(&v[44..46]),
1291 cltv_expiry_delta: byte_utils::slice_to_be16(&v[46..48]),
1292 htlc_minimum_msat: byte_utils::slice_to_be64(&v[48..56]),
1293 fee_base_msat: byte_utils::slice_to_be32(&v[56..60]),
1294 fee_proportional_millionths: byte_utils::slice_to_be32(&v[60..64]),
1298 impl MsgEncodable for UnsignedChannelUpdate {
1299 fn encode(&self) -> Vec<u8> {
1300 let mut res = Vec::with_capacity(64);
1301 res.extend_from_slice(&self.chain_hash[..]);
1302 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1303 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
1304 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
1305 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
1306 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
1307 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
1308 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
1313 impl MsgDecodable for ChannelUpdate {
1314 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1316 return Err(DecodeError::WrongLength);
1318 let secp_ctx = Secp256k1::without_caps();
1320 signature: secp_signature!(&secp_ctx, &v[0..64]),
1321 contents: UnsignedChannelUpdate::decode(&v[64..])?,
1325 impl MsgEncodable for ChannelUpdate {
1326 fn encode(&self) -> Vec<u8> {
1327 let mut res = Vec::with_capacity(128);
1328 res.extend_from_slice(&self.signature.serialize_compact(&Secp256k1::without_caps())[..]);
1329 res.extend_from_slice(&self.contents.encode()[..]);
1334 impl MsgDecodable for OnionRealm0HopData {
1335 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1337 return Err(DecodeError::WrongLength);
1339 Ok(OnionRealm0HopData {
1340 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
1341 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
1342 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
1346 impl MsgEncodable for OnionRealm0HopData {
1347 fn encode(&self) -> Vec<u8> {
1348 let mut res = Vec::with_capacity(32);
1349 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
1350 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
1351 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
1357 impl MsgDecodable for OnionHopData {
1358 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1360 return Err(DecodeError::WrongLength);
1364 return Err(DecodeError::UnknownRealmByte);
1366 let mut hmac = [0; 32];
1367 hmac[..].copy_from_slice(&v[33..65]);
1370 data: OnionRealm0HopData::decode(&v[1..33])?,
1375 impl MsgEncodable for OnionHopData {
1376 fn encode(&self) -> Vec<u8> {
1377 let mut res = Vec::with_capacity(65);
1378 res.push(self.realm);
1379 res.extend_from_slice(&self.data.encode()[..]);
1380 res.extend_from_slice(&self.hmac);
1385 impl MsgDecodable for OnionPacket {
1386 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1387 if v.len() < 1+33+20*65+32 {
1388 return Err(DecodeError::WrongLength);
1390 let mut hop_data = [0; 20*65];
1391 hop_data.copy_from_slice(&v[34..1334]);
1392 let mut hmac = [0; 32];
1393 hmac.copy_from_slice(&v[1334..1366]);
1394 let secp_ctx = Secp256k1::without_caps();
1397 public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1403 impl MsgEncodable for OnionPacket {
1404 fn encode(&self) -> Vec<u8> {
1405 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1406 res.push(self.version);
1407 res.extend_from_slice(&self.public_key.serialize());
1408 res.extend_from_slice(&self.hop_data);
1409 res.extend_from_slice(&self.hmac);
1414 impl MsgDecodable for DecodedOnionErrorPacket {
1415 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1416 if v.len() < 32 + 4 {
1417 return Err(DecodeError::WrongLength);
1419 let failuremsg_len = byte_utils::slice_to_be16(&v[32..34]) as usize;
1420 if v.len() < 32 + 4 + failuremsg_len {
1421 return Err(DecodeError::WrongLength);
1423 let padding_len = byte_utils::slice_to_be16(&v[34 + failuremsg_len..]) as usize;
1424 if v.len() < 32 + 4 + failuremsg_len + padding_len {
1425 return Err(DecodeError::WrongLength);
1428 let mut hmac = [0; 32];
1429 hmac.copy_from_slice(&v[0..32]);
1432 failuremsg: v[34..34 + failuremsg_len].to_vec(),
1433 pad: v[36 + failuremsg_len..36 + failuremsg_len + padding_len].to_vec(),
1437 impl MsgEncodable for DecodedOnionErrorPacket {
1438 fn encode(&self) -> Vec<u8> {
1439 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1440 res.extend_from_slice(&self.hmac);
1441 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1442 res.extend_from_slice(&self.failuremsg);
1443 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1444 res.extend_from_slice(&self.pad);
1449 impl MsgDecodable for OnionErrorPacket {
1450 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1452 return Err(DecodeError::WrongLength);
1454 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1455 if v.len() < 2 + len {
1456 return Err(DecodeError::WrongLength);
1459 data: v[2..len+2].to_vec(),
1463 impl MsgEncodable for OnionErrorPacket {
1464 fn encode(&self) -> Vec<u8> {
1465 let mut res = Vec::with_capacity(2 + self.data.len());
1466 res.extend_from_slice(&byte_utils::be16_to_array(self.data.len() as u16));
1467 res.extend_from_slice(&self.data);