1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1, Signature};
3 use bitcoin::util::uint::Uint256;
4 use bitcoin::util::hash::Sha256dHash;
5 use bitcoin::network::serialize::deserialize;
6 use bitcoin::blockdata::script::Script;
10 use std::result::Result;
12 use util::{byte_utils, internal_traits, events};
14 pub trait MsgEncodable {
15 fn encode(&self) -> Vec<u8>;
18 pub enum DecodeError {
19 /// Unknown realm byte in an OnionHopData packet
21 /// Failed to decode a public key (ie it's invalid)
23 /// Failed to decode a signature (ie it's invalid)
25 /// Buffer not of right length (either too short or too long)
28 pub trait MsgDecodable: Sized {
29 fn decode(v: &[u8]) -> Result<Self, DecodeError>;
32 /// Tracks localfeatures which are only in init messages
33 #[derive(Clone, PartialEq)]
34 pub struct LocalFeatures {
39 pub fn new() -> LocalFeatures {
45 pub fn supports_data_loss_protect(&self) -> bool {
46 self.flags.len() > 0 && (self.flags[0] & 3) != 0
48 pub fn requires_data_loss_protect(&self) -> bool {
49 self.flags.len() > 0 && (self.flags[0] & 1) != 0
52 pub fn supports_initial_routing_sync(&self) -> bool {
53 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
56 pub fn supports_upfront_shutdown_script(&self) -> bool {
57 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
59 pub fn requires_upfront_shutdown_script(&self) -> bool {
60 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
63 pub fn requires_unknown_bits(&self) -> bool {
64 for (idx, &byte) in self.flags.iter().enumerate() {
65 if idx != 0 && (byte & 0x55) != 0 {
67 } else if idx == 0 && (byte & 0x14) != 0 {
74 pub fn supports_unknown_bits(&self) -> bool {
75 for (idx, &byte) in self.flags.iter().enumerate() {
76 if idx != 0 && byte != 0 {
78 } else if idx == 0 && (byte & 0xc4) != 0 {
86 /// Tracks globalfeatures which are in init messages and routing announcements
87 #[derive(Clone, PartialEq)]
88 pub struct GlobalFeatures {
93 pub fn new() -> GlobalFeatures {
99 pub fn requires_unknown_bits(&self) -> bool {
100 for &byte in self.flags.iter() {
101 if (byte & 0x55) != 0 {
108 pub fn supports_unknown_bits(&self) -> bool {
109 for &byte in self.flags.iter() {
119 pub global_features: GlobalFeatures,
120 pub local_features: LocalFeatures,
123 pub struct OpenChannel {
124 pub chain_hash: Sha256dHash,
125 pub temporary_channel_id: Uint256,
126 pub funding_satoshis: u64,
128 pub dust_limit_satoshis: u64,
129 pub max_htlc_value_in_flight_msat: u64,
130 pub channel_reserve_satoshis: u64,
131 pub htlc_minimum_msat: u64,
132 pub feerate_per_kw: u32,
133 pub to_self_delay: u16,
134 pub max_accepted_htlcs: u16,
135 pub funding_pubkey: PublicKey,
136 pub revocation_basepoint: PublicKey,
137 pub payment_basepoint: PublicKey,
138 pub delayed_payment_basepoint: PublicKey,
139 pub htlc_basepoint: PublicKey,
140 pub first_per_commitment_point: PublicKey,
141 pub channel_flags: u8,
142 pub shutdown_scriptpubkey: Option<Script>,
145 pub struct AcceptChannel {
146 pub temporary_channel_id: Uint256,
147 pub dust_limit_satoshis: u64,
148 pub max_htlc_value_in_flight_msat: u64,
149 pub channel_reserve_satoshis: u64,
150 pub htlc_minimum_msat: u64,
151 pub minimum_depth: u32,
152 pub to_self_delay: u16,
153 pub max_accepted_htlcs: u16,
154 pub funding_pubkey: PublicKey,
155 pub revocation_basepoint: PublicKey,
156 pub payment_basepoint: PublicKey,
157 pub delayed_payment_basepoint: PublicKey,
158 pub htlc_basepoint: PublicKey,
159 pub first_per_commitment_point: PublicKey,
160 pub shutdown_scriptpubkey: Option<Script>,
163 pub struct FundingCreated {
164 pub temporary_channel_id: Uint256,
165 pub funding_txid: Sha256dHash,
166 pub funding_output_index: u16,
167 pub signature: Signature,
170 pub struct FundingSigned {
171 pub channel_id: Uint256,
172 pub signature: Signature,
175 pub struct FundingLocked {
176 pub channel_id: Uint256,
177 pub next_per_commitment_point: PublicKey,
180 pub struct Shutdown {
181 pub channel_id: Uint256,
182 pub scriptpubkey: Script,
185 pub struct ClosingSigned {
186 pub channel_id: Uint256,
187 pub fee_satoshis: u64,
188 pub signature: Signature,
192 pub struct UpdateAddHTLC {
193 pub channel_id: Uint256,
195 pub amount_msat: u64,
196 pub payment_hash: [u8; 32],
197 pub cltv_expiry: u32,
198 pub onion_routing_packet: OnionPacket,
202 pub struct UpdateFulfillHTLC {
203 pub channel_id: Uint256,
205 pub payment_preimage: [u8; 32],
209 pub struct UpdateFailHTLC {
210 pub channel_id: Uint256,
212 pub reason: OnionErrorPacket,
216 pub struct UpdateFailMalformedHTLC {
217 pub channel_id: Uint256,
219 pub sha256_of_onion: [u8; 32],
220 pub failure_code: u16,
224 pub struct CommitmentSigned {
225 pub channel_id: Uint256,
226 pub signature: Signature,
227 pub htlc_signatures: Vec<Signature>,
230 pub struct RevokeAndACK {
231 pub channel_id: Uint256,
232 pub per_commitment_secret: [u8; 32],
233 pub next_per_commitment_point: PublicKey,
236 pub struct UpdateFee {
237 pub channel_id: Uint256,
238 pub feerate_per_kw: u32,
241 pub struct ChannelReestablish {
242 pub channel_id: Uint256,
243 pub next_local_commitment_number: u64,
244 pub next_remote_commitment_number: u64,
245 pub your_last_per_commitment_secret: Option<[u8; 32]>,
246 pub my_current_per_commitment_point: PublicKey,
250 pub struct AnnouncementSignatures {
251 pub channel_id: Uint256,
252 pub short_channel_id: u64,
253 pub node_signature: Signature,
254 pub bitcoin_signature: Signature,
258 pub enum NetAddress {
273 ed25519_pubkey: [u8; 32],
276 //TODO: Do we need a port number here???
280 pub struct UnsignedNodeAnnouncement {
281 pub features: GlobalFeatures,
283 pub node_id: PublicKey,
286 pub addresses: Vec<NetAddress>,
288 pub struct NodeAnnouncement {
289 pub signature: Signature,
290 pub contents: UnsignedNodeAnnouncement,
293 #[derive(PartialEq, Clone)]
294 pub struct UnsignedChannelAnnouncement {
295 pub features: GlobalFeatures,
296 pub chain_hash: Sha256dHash,
297 pub short_channel_id: u64,
298 pub node_id_1: PublicKey,
299 pub node_id_2: PublicKey,
300 pub bitcoin_key_1: PublicKey,
301 pub bitcoin_key_2: PublicKey,
303 #[derive(PartialEq, Clone)]
304 pub struct ChannelAnnouncement {
305 pub node_signature_1: Signature,
306 pub node_signature_2: Signature,
307 pub bitcoin_signature_1: Signature,
308 pub bitcoin_signature_2: Signature,
309 pub contents: UnsignedChannelAnnouncement,
312 #[derive(PartialEq, Clone)]
313 pub struct UnsignedChannelUpdate {
314 pub chain_hash: Sha256dHash,
315 pub short_channel_id: u64,
318 pub cltv_expiry_delta: u16,
319 pub htlc_minimum_msat: u64,
320 pub fee_base_msat: u32,
321 pub fee_proportional_millionths: u32,
323 #[derive(PartialEq, Clone)]
324 pub struct ChannelUpdate {
325 pub signature: Signature,
326 pub contents: UnsignedChannelUpdate,
329 /// Used to put an error message in a HandleError
330 pub enum ErrorMessage {
337 pub struct HandleError { //TODO: rename me
338 pub err: &'static str,
339 pub msg: Option<ErrorMessage>, //TODO: Move into an Action enum and require it!
342 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
343 /// paralell when they originate from different their_node_ids, however they MUST NOT be called in
344 /// paralell when the two calls have the same their_node_id.
345 pub trait ChannelMessageHandler : events::EventsProvider {
347 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
348 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
349 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
350 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
351 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
354 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
355 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
358 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
359 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
360 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
361 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<Option<(Vec<UpdateAddHTLC>, CommitmentSigned)>, HandleError>;
362 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<RevokeAndACK, HandleError>;
363 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
365 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
367 // Channel-to-announce:
368 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
371 pub trait RoutingMessageHandler {
372 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<(), HandleError>;
373 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
374 /// or returning an Err otherwise.
375 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
376 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<(), HandleError>;
379 pub struct OnionRealm0HopData {
380 pub short_channel_id: u64,
381 pub amt_to_forward: u64,
382 pub outgoing_cltv_value: u32,
383 // 12 bytes of 0-padding
386 pub struct OnionHopData {
388 pub data: OnionRealm0HopData,
391 unsafe impl internal_traits::NoDealloc for OnionHopData{}
394 pub struct OnionPacket {
396 pub public_key: PublicKey,
397 pub hop_data: [u8; 20*65],
401 pub struct DecodedOnionErrorPacket {
403 pub failuremsg: Vec<u8>,
408 pub struct OnionErrorPacket {
409 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
410 // (TODO) We limit it in decode to much lower...
414 impl Error for DecodeError {
415 fn description(&self) -> &str {
417 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
418 DecodeError::BadPublicKey => "Invalid public key in packet",
419 DecodeError::BadSignature => "Invalid signature in packet",
420 DecodeError::WrongLength => "Data was wrong length for packet",
424 impl fmt::Display for DecodeError {
425 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
426 f.write_str(self.description())
430 impl fmt::Debug for HandleError {
431 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
432 f.write_str(self.err)
436 macro_rules! secp_pubkey {
437 ( $ctx: expr, $slice: expr ) => {
438 match PublicKey::from_slice($ctx, $slice) {
440 Err(_) => return Err(DecodeError::BadPublicKey)
445 macro_rules! secp_signature {
446 ( $ctx: expr, $slice: expr ) => {
447 match Signature::from_compact($ctx, $slice) {
449 Err(_) => return Err(DecodeError::BadSignature)
454 impl MsgDecodable for LocalFeatures {
455 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
456 if v.len() < 3 { return Err(DecodeError::WrongLength); }
457 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
458 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
459 let mut flags = Vec::with_capacity(len);
460 flags.extend_from_slice(&v[2..]);
466 impl MsgEncodable for LocalFeatures {
467 fn encode(&self) -> Vec<u8> {
468 let mut res = Vec::with_capacity(self.flags.len() + 2);
469 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
470 res.extend_from_slice(&self.flags[..]);
475 impl MsgDecodable for GlobalFeatures {
476 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
477 if v.len() < 3 { return Err(DecodeError::WrongLength); }
478 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
479 if v.len() < len + 2 { return Err(DecodeError::WrongLength); }
480 let mut flags = Vec::with_capacity(len);
481 flags.extend_from_slice(&v[2..]);
487 impl MsgEncodable for GlobalFeatures {
488 fn encode(&self) -> Vec<u8> {
489 let mut res = Vec::with_capacity(self.flags.len() + 2);
490 res.extend_from_slice(&byte_utils::be16_to_array(self.flags.len() as u16));
491 res.extend_from_slice(&self.flags[..]);
496 impl MsgDecodable for Init {
497 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
498 let global_features = GlobalFeatures::decode(v)?;
499 if v.len() < global_features.flags.len() + 4 {
500 return Err(DecodeError::WrongLength);
502 let local_features = LocalFeatures::decode(&v[global_features.flags.len() + 2..])?;
504 global_features: global_features,
505 local_features: local_features,
509 impl MsgEncodable for Init {
510 fn encode(&self) -> Vec<u8> {
511 let mut res = Vec::with_capacity(self.global_features.flags.len() + self.local_features.flags.len());
512 res.extend_from_slice(&self.global_features.encode()[..]);
513 res.extend_from_slice(&self.local_features.encode()[..]);
518 impl MsgDecodable for OpenChannel {
519 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
520 if v.len() < 2*32+6*8+4+2*2+6*33+1 {
521 return Err(DecodeError::WrongLength);
523 let ctx = Secp256k1::without_caps();
525 let mut shutdown_scriptpubkey = None;
527 let len = byte_utils::slice_to_be16(&v[319..321]) as usize;
528 if v.len() < 321+len {
529 return Err(DecodeError::WrongLength);
531 shutdown_scriptpubkey = Some(Script::from(v[321..321+len].to_vec()));
532 } else if v.len() != 2*32+6*8+4+2*2+6*33+1 { // Message cant have 1 extra byte
533 return Err(DecodeError::WrongLength);
537 chain_hash: deserialize(&v[0..32]).unwrap(),
538 temporary_channel_id: deserialize(&v[32..64]).unwrap(),
539 funding_satoshis: byte_utils::slice_to_be64(&v[64..72]),
540 push_msat: byte_utils::slice_to_be64(&v[72..80]),
541 dust_limit_satoshis: byte_utils::slice_to_be64(&v[80..88]),
542 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[88..96]),
543 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[96..104]),
544 htlc_minimum_msat: byte_utils::slice_to_be64(&v[104..112]),
545 feerate_per_kw: byte_utils::slice_to_be32(&v[112..116]),
546 to_self_delay: byte_utils::slice_to_be16(&v[116..118]),
547 max_accepted_htlcs: byte_utils::slice_to_be16(&v[118..120]),
548 funding_pubkey: secp_pubkey!(&ctx, &v[120..153]),
549 revocation_basepoint: secp_pubkey!(&ctx, &v[153..186]),
550 payment_basepoint: secp_pubkey!(&ctx, &v[186..219]),
551 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[219..252]),
552 htlc_basepoint: secp_pubkey!(&ctx, &v[252..285]),
553 first_per_commitment_point: secp_pubkey!(&ctx, &v[285..318]),
554 channel_flags: v[318],
555 shutdown_scriptpubkey: shutdown_scriptpubkey
559 impl MsgEncodable for OpenChannel {
560 fn encode(&self) -> Vec<u8> {
565 impl MsgDecodable for AcceptChannel {
566 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
567 if v.len() < 32+4*8+4+2*2+6*33 {
568 return Err(DecodeError::WrongLength);
570 let ctx = Secp256k1::without_caps();
572 let mut shutdown_scriptpubkey = None;
574 let len = byte_utils::slice_to_be16(&v[270..272]) as usize;
575 if v.len() < 272+len {
576 return Err(DecodeError::WrongLength);
578 shutdown_scriptpubkey = Some(Script::from(v[272..272+len].to_vec()));
579 } else if v.len() != 32+4*8+4+2*2+6*33 { // Message cant have 1 extra byte
580 return Err(DecodeError::WrongLength);
584 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
585 dust_limit_satoshis: byte_utils::slice_to_be64(&v[32..40]),
586 max_htlc_value_in_flight_msat: byte_utils::slice_to_be64(&v[40..48]),
587 channel_reserve_satoshis: byte_utils::slice_to_be64(&v[48..56]),
588 htlc_minimum_msat: byte_utils::slice_to_be64(&v[56..64]),
589 minimum_depth: byte_utils::slice_to_be32(&v[64..68]),
590 to_self_delay: byte_utils::slice_to_be16(&v[68..70]),
591 max_accepted_htlcs: byte_utils::slice_to_be16(&v[70..72]),
592 funding_pubkey: secp_pubkey!(&ctx, &v[72..105]),
593 revocation_basepoint: secp_pubkey!(&ctx, &v[105..138]),
594 payment_basepoint: secp_pubkey!(&ctx, &v[138..171]),
595 delayed_payment_basepoint: secp_pubkey!(&ctx, &v[171..204]),
596 htlc_basepoint: secp_pubkey!(&ctx, &v[204..237]),
597 first_per_commitment_point: secp_pubkey!(&ctx, &v[237..270]),
598 shutdown_scriptpubkey: shutdown_scriptpubkey
602 impl MsgEncodable for AcceptChannel {
603 fn encode(&self) -> Vec<u8> {
608 impl MsgDecodable for FundingCreated {
609 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
610 if v.len() < 32+32+2+64 {
611 return Err(DecodeError::WrongLength);
613 let ctx = Secp256k1::without_caps();
615 temporary_channel_id: deserialize(&v[0..32]).unwrap(),
616 funding_txid: deserialize(&v[32..64]).unwrap(),
617 funding_output_index: byte_utils::slice_to_be16(&v[64..66]),
618 signature: secp_signature!(&ctx, &v[66..130]),
622 impl MsgEncodable for FundingCreated {
623 fn encode(&self) -> Vec<u8> {
628 impl MsgDecodable for FundingSigned {
629 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
631 return Err(DecodeError::WrongLength);
633 let ctx = Secp256k1::without_caps();
635 channel_id: deserialize(&v[0..32]).unwrap(),
636 signature: secp_signature!(&ctx, &v[32..96]),
640 impl MsgEncodable for FundingSigned {
641 fn encode(&self) -> Vec<u8> {
646 impl MsgDecodable for FundingLocked {
647 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
649 return Err(DecodeError::WrongLength);
651 let ctx = Secp256k1::without_caps();
653 channel_id: deserialize(&v[0..32]).unwrap(),
654 next_per_commitment_point: secp_pubkey!(&ctx, &v[32..65]),
658 impl MsgEncodable for FundingLocked {
659 fn encode(&self) -> Vec<u8> {
664 impl MsgDecodable for Shutdown {
665 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
669 impl MsgEncodable for Shutdown {
670 fn encode(&self) -> Vec<u8> {
675 impl MsgDecodable for ClosingSigned {
676 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
680 impl MsgEncodable for ClosingSigned {
681 fn encode(&self) -> Vec<u8> {
686 impl MsgDecodable for UpdateAddHTLC {
687 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
688 if v.len() < 32+8+8+32+4+1+33+20*65+32 {
689 return Err(DecodeError::WrongLength);
691 let mut payment_hash = [0; 32];
692 payment_hash.copy_from_slice(&v[48..80]);
694 channel_id: deserialize(&v[0..32]).unwrap(),
695 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
696 amount_msat: byte_utils::slice_to_be64(&v[40..48]),
698 cltv_expiry: byte_utils::slice_to_be32(&v[80..84]),
699 onion_routing_packet: OnionPacket::decode(&v[84..])?,
703 impl MsgEncodable for UpdateAddHTLC {
704 fn encode(&self) -> Vec<u8> {
709 impl MsgDecodable for UpdateFulfillHTLC {
710 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
711 if v.len() < 32+8+32 {
712 return Err(DecodeError::WrongLength);
714 let mut payment_preimage = [0; 32];
715 payment_preimage.copy_from_slice(&v[40..72]);
717 channel_id: deserialize(&v[0..32]).unwrap(),
718 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
723 impl MsgEncodable for UpdateFulfillHTLC {
724 fn encode(&self) -> Vec<u8> {
729 impl MsgDecodable for UpdateFailHTLC {
730 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
732 return Err(DecodeError::WrongLength);
735 channel_id: deserialize(&v[0..32]).unwrap(),
736 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
737 reason: OnionErrorPacket::decode(&v[40..])?,
741 impl MsgEncodable for UpdateFailHTLC {
742 fn encode(&self) -> Vec<u8> {
747 impl MsgDecodable for UpdateFailMalformedHTLC {
748 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
749 if v.len() < 32+8+32+2 {
750 return Err(DecodeError::WrongLength);
752 let mut sha256_of_onion = [0; 32];
753 sha256_of_onion.copy_from_slice(&v[40..72]);
755 channel_id: deserialize(&v[0..32]).unwrap(),
756 htlc_id: byte_utils::slice_to_be64(&v[32..40]),
758 failure_code: byte_utils::slice_to_be16(&v[72..74]),
762 impl MsgEncodable for UpdateFailMalformedHTLC {
763 fn encode(&self) -> Vec<u8> {
768 impl MsgDecodable for CommitmentSigned {
769 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
770 if v.len() < 32+64+2 {
771 return Err(DecodeError::WrongLength);
773 let htlcs = byte_utils::slice_to_be16(&v[96..98]) as usize;
774 if v.len() < 32+64+2+htlcs*64 {
775 return Err(DecodeError::WrongLength);
777 let mut htlc_signatures = Vec::with_capacity(htlcs);
778 let secp_ctx = Secp256k1::without_caps();
780 htlc_signatures.push(secp_signature!(&secp_ctx, &v[98+i*64..98+(i+1)*64]));
783 channel_id: deserialize(&v[0..32]).unwrap(),
784 signature: secp_signature!(&secp_ctx, &v[32..96]),
789 impl MsgEncodable for CommitmentSigned {
790 fn encode(&self) -> Vec<u8> {
795 impl MsgDecodable for RevokeAndACK {
796 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
797 if v.len() < 32+32+33 {
798 return Err(DecodeError::WrongLength);
800 let mut per_commitment_secret = [0; 32];
801 per_commitment_secret.copy_from_slice(&v[32..64]);
802 let secp_ctx = Secp256k1::without_caps();
804 channel_id: deserialize(&v[0..32]).unwrap(),
805 per_commitment_secret,
806 next_per_commitment_point: secp_pubkey!(&secp_ctx, &v[64..97]),
810 impl MsgEncodable for RevokeAndACK {
811 fn encode(&self) -> Vec<u8> {
816 impl MsgDecodable for UpdateFee {
817 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
819 return Err(DecodeError::WrongLength);
822 channel_id: deserialize(&v[0..32]).unwrap(),
823 feerate_per_kw: byte_utils::slice_to_be32(&v[32..36]),
827 impl MsgEncodable for UpdateFee {
828 fn encode(&self) -> Vec<u8> {
833 impl MsgDecodable for ChannelReestablish {
834 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
838 impl MsgEncodable for ChannelReestablish {
839 fn encode(&self) -> Vec<u8> {
844 impl MsgDecodable for AnnouncementSignatures {
845 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
849 impl MsgEncodable for AnnouncementSignatures {
850 fn encode(&self) -> Vec<u8> {
855 impl MsgDecodable for UnsignedNodeAnnouncement {
856 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
860 impl MsgEncodable for UnsignedNodeAnnouncement {
861 fn encode(&self) -> Vec<u8> {
862 let features = self.features.encode();
863 let mut res = Vec::with_capacity(74 + features.len() + self.addresses.len());
864 res.extend_from_slice(&features[..]);
865 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
866 res.extend_from_slice(&self.node_id.serialize());
867 res.extend_from_slice(&self.rgb);
868 res.extend_from_slice(&self.alias);
869 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
870 for addr in self.addresses.iter() {
872 &NetAddress::Dummy => {},
873 &NetAddress::IPv4{addr, port} => {
874 addr_slice.extend_from_slice(&addr);
875 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
877 &NetAddress::IPv6{addr, port} => {
878 addr_slice.extend_from_slice(&addr);
879 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
881 &NetAddress::OnionV2{addr, port} => {
882 addr_slice.extend_from_slice(&addr);
883 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
885 &NetAddress::OnionV3{ed25519_pubkey, checksum, version} => {
886 addr_slice.extend_from_slice(&ed25519_pubkey);
887 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
888 addr_slice.push(version);
892 res.extend_from_slice(&byte_utils::be16_to_array(addr_slice.len() as u16));
893 res.extend_from_slice(&addr_slice[..]);
898 impl MsgDecodable for NodeAnnouncement {
899 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
903 impl MsgEncodable for NodeAnnouncement {
904 fn encode(&self) -> Vec<u8> {
909 impl MsgDecodable for UnsignedChannelAnnouncement {
910 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
914 impl MsgEncodable for UnsignedChannelAnnouncement {
915 fn encode(&self) -> Vec<u8> {
916 let features = self.features.encode();
917 let mut res = Vec::with_capacity(172 + features.len());
918 res.extend_from_slice(&features[..]);
919 res.extend_from_slice(&self.chain_hash[..]);
920 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
921 res.extend_from_slice(&self.node_id_1.serialize());
922 res.extend_from_slice(&self.node_id_2.serialize());
923 res.extend_from_slice(&self.bitcoin_key_1.serialize());
924 res.extend_from_slice(&self.bitcoin_key_2.serialize());
929 impl MsgDecodable for ChannelAnnouncement {
930 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
934 impl MsgEncodable for ChannelAnnouncement {
935 fn encode(&self) -> Vec<u8> {
940 impl MsgDecodable for UnsignedChannelUpdate {
941 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
945 impl MsgEncodable for UnsignedChannelUpdate {
946 fn encode(&self) -> Vec<u8> {
947 let mut res = Vec::with_capacity(64);
948 res.extend_from_slice(&self.chain_hash[..]);
949 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
950 res.extend_from_slice(&byte_utils::be32_to_array(self.timestamp));
951 res.extend_from_slice(&byte_utils::be16_to_array(self.flags));
952 res.extend_from_slice(&byte_utils::be16_to_array(self.cltv_expiry_delta));
953 res.extend_from_slice(&byte_utils::be64_to_array(self.htlc_minimum_msat));
954 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_base_msat));
955 res.extend_from_slice(&byte_utils::be32_to_array(self.fee_proportional_millionths));
960 impl MsgDecodable for ChannelUpdate {
961 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
965 impl MsgEncodable for ChannelUpdate {
966 fn encode(&self) -> Vec<u8> {
967 let mut res = Vec::with_capacity(128);
968 //TODO: Should avoid creating a new secp ctx just for a serialize call :(
969 res.extend_from_slice(&self.signature.serialize_der(&Secp256k1::new())[..]); //TODO: Need in non-der form! (probably elsewhere too)
970 res.extend_from_slice(&self.contents.encode()[..]);
975 impl MsgDecodable for OnionRealm0HopData {
976 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
978 return Err(DecodeError::WrongLength);
980 Ok(OnionRealm0HopData {
981 short_channel_id: byte_utils::slice_to_be64(&v[0..8]),
982 amt_to_forward: byte_utils::slice_to_be64(&v[8..16]),
983 outgoing_cltv_value: byte_utils::slice_to_be32(&v[16..20]),
987 impl MsgEncodable for OnionRealm0HopData {
988 fn encode(&self) -> Vec<u8> {
989 let mut res = Vec::with_capacity(32);
990 res.extend_from_slice(&byte_utils::be64_to_array(self.short_channel_id));
991 res.extend_from_slice(&byte_utils::be64_to_array(self.amt_to_forward));
992 res.extend_from_slice(&byte_utils::be32_to_array(self.outgoing_cltv_value));
998 impl MsgDecodable for OnionHopData {
999 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1001 return Err(DecodeError::WrongLength);
1005 return Err(DecodeError::UnknownRealmByte);
1007 let mut hmac = [0; 32];
1008 hmac[..].copy_from_slice(&v[33..65]);
1011 data: OnionRealm0HopData::decode(&v[1..33])?,
1016 impl MsgEncodable for OnionHopData {
1017 fn encode(&self) -> Vec<u8> {
1018 let mut res = Vec::with_capacity(65);
1019 res.push(self.realm);
1020 res.extend_from_slice(&self.data.encode()[..]);
1021 res.extend_from_slice(&self.hmac);
1026 impl MsgDecodable for OnionPacket {
1027 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1028 if v.len() < 1+33+20*65+32 {
1029 return Err(DecodeError::WrongLength);
1031 let mut hop_data = [0; 20*65];
1032 hop_data.copy_from_slice(&v[34..1334]);
1033 let mut hmac = [0; 32];
1034 hmac.copy_from_slice(&v[1334..1366]);
1035 let secp_ctx = Secp256k1::without_caps();
1038 public_key: secp_pubkey!(&secp_ctx, &v[1..34]),
1044 impl MsgEncodable for OnionPacket {
1045 fn encode(&self) -> Vec<u8> {
1046 let mut res = Vec::with_capacity(1 + 33 + 20*65 + 32);
1047 res.push(self.version);
1048 res.extend_from_slice(&self.public_key.serialize());
1049 res.extend_from_slice(&self.hop_data);
1050 res.extend_from_slice(&self.hmac);
1055 impl MsgDecodable for DecodedOnionErrorPacket {
1056 fn decode(_v: &[u8]) -> Result<Self, DecodeError> {
1060 impl MsgEncodable for DecodedOnionErrorPacket {
1061 fn encode(&self) -> Vec<u8> {
1062 let mut res = Vec::with_capacity(32 + 4 + self.failuremsg.len() + self.pad.len());
1063 res.extend_from_slice(&self.hmac);
1064 res.extend_from_slice(&[((self.failuremsg.len() >> 8) & 0xff) as u8, (self.failuremsg.len() & 0xff) as u8]);
1065 res.extend_from_slice(&self.failuremsg);
1066 res.extend_from_slice(&[((self.pad.len() >> 8) & 0xff) as u8, (self.pad.len() & 0xff) as u8]);
1067 res.extend_from_slice(&self.pad);
1072 impl MsgDecodable for OnionErrorPacket {
1073 fn decode(v: &[u8]) -> Result<Self, DecodeError> {
1075 return Err(DecodeError::WrongLength);
1077 let len = byte_utils::slice_to_be16(&v[0..2]) as usize;
1078 if v.len() < 2 + len {
1079 return Err(DecodeError::WrongLength);
1082 data: v[2..len+2].to_vec(),
1086 impl MsgEncodable for OnionErrorPacket {
1087 fn encode(&self) -> Vec<u8> {