1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
3 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
4 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
5 //! server entirely) which handles only channel-related messages you may wish to implement
6 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
9 //! Note that if you go with such an architecture (instead of passing raw socket events to a
10 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
11 //! source node_id of the mssage, however this does allow you to significantly reduce bandwidth
12 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
13 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
14 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
15 //! raw socket events into your non-internet-facing system and then send routing events back to
16 //! track the network on the less-secure system.
18 use secp256k1::key::PublicKey;
19 use secp256k1::{Secp256k1, Signature};
21 use bitcoin::util::hash::Sha256dHash;
22 use bitcoin::blockdata::script::Script;
24 use std::error::Error;
27 use std::result::Result;
29 use util::{byte_utils, events};
30 use util::ser::{Readable, Writeable, Writer};
32 /// An error in decoding a message or struct.
34 pub enum DecodeError {
35 /// A version byte specified something we don't know how to handle.
36 /// Includes unknown realm byte in an OnionHopData packet
38 /// Unknown feature mandating we fail to parse message
39 UnknownRequiredFeature,
40 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
41 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
45 /// node_announcement included more than one address of a given type!
46 ExtraAddressesPerType,
47 /// A length descriptor in the packet didn't describe the later data correctly
48 /// (currently only generated in node_announcement)
50 /// Error from std::io
54 /// Tracks localfeatures which are only in init messages
55 #[derive(Clone, PartialEq)]
56 pub struct LocalFeatures {
61 pub(crate) fn new() -> LocalFeatures {
67 pub(crate) fn supports_data_loss_protect(&self) -> bool {
68 self.flags.len() > 0 && (self.flags[0] & 3) != 0
70 pub(crate) fn requires_data_loss_protect(&self) -> bool {
71 self.flags.len() > 0 && (self.flags[0] & 1) != 0
74 pub(crate) fn initial_routing_sync(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
77 pub(crate) fn set_initial_routing_sync(&mut self) {
78 if self.flags.len() == 0 {
79 self.flags.resize(1, 1 << 3);
81 self.flags[0] |= 1 << 3;
85 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
86 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
88 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
89 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
92 pub(crate) fn requires_unknown_bits(&self) -> bool {
93 for (idx, &byte) in self.flags.iter().enumerate() {
94 if idx != 0 && (byte & 0x55) != 0 {
96 } else if idx == 0 && (byte & 0x14) != 0 {
103 pub(crate) fn supports_unknown_bits(&self) -> bool {
104 for (idx, &byte) in self.flags.iter().enumerate() {
105 if idx != 0 && byte != 0 {
107 } else if idx == 0 && (byte & 0xc4) != 0 {
115 /// Tracks globalfeatures which are in init messages and routing announcements
116 #[derive(Clone, PartialEq)]
117 pub struct GlobalFeatures {
121 impl GlobalFeatures {
122 pub(crate) fn new() -> GlobalFeatures {
128 pub(crate) fn requires_unknown_bits(&self) -> bool {
129 for &byte in self.flags.iter() {
130 if (byte & 0x55) != 0 {
137 pub(crate) fn supports_unknown_bits(&self) -> bool {
138 for &byte in self.flags.iter() {
147 /// An init message to be sent or received from a peer
149 pub(crate) global_features: GlobalFeatures,
150 pub(crate) local_features: LocalFeatures,
153 /// An error message to be sent or received from a peer
154 pub struct ErrorMessage {
155 pub(crate) channel_id: [u8; 32],
156 pub(crate) data: String,
159 /// A ping message to be sent or received from a peer
161 pub(crate) ponglen: u16,
162 pub(crate) byteslen: u16,
165 /// A pong message to be sent or received from a peer
167 pub(crate) byteslen: u16,
170 /// An open_channel message to be sent or received from a peer
172 pub struct OpenChannel {
173 pub(crate) chain_hash: Sha256dHash,
174 pub(crate) temporary_channel_id: [u8; 32],
175 pub(crate) funding_satoshis: u64,
176 pub(crate) push_msat: u64,
177 pub(crate) dust_limit_satoshis: u64,
178 pub(crate) max_htlc_value_in_flight_msat: u64,
179 pub(crate) channel_reserve_satoshis: u64,
180 pub(crate) htlc_minimum_msat: u64,
181 pub(crate) feerate_per_kw: u32,
182 pub(crate) to_self_delay: u16,
183 pub(crate) max_accepted_htlcs: u16,
184 pub(crate) funding_pubkey: PublicKey,
185 pub(crate) revocation_basepoint: PublicKey,
186 pub(crate) payment_basepoint: PublicKey,
187 pub(crate) delayed_payment_basepoint: PublicKey,
188 pub(crate) htlc_basepoint: PublicKey,
189 pub(crate) first_per_commitment_point: PublicKey,
190 pub(crate) channel_flags: u8,
191 pub(crate) shutdown_scriptpubkey: Option<Script>,
194 /// An accept_channel message to be sent or received from a peer
196 pub struct AcceptChannel {
197 pub(crate) temporary_channel_id: [u8; 32],
198 pub(crate) dust_limit_satoshis: u64,
199 pub(crate) max_htlc_value_in_flight_msat: u64,
200 pub(crate) channel_reserve_satoshis: u64,
201 pub(crate) htlc_minimum_msat: u64,
202 pub(crate) minimum_depth: u32,
203 pub(crate) to_self_delay: u16,
204 pub(crate) max_accepted_htlcs: u16,
205 pub(crate) funding_pubkey: PublicKey,
206 pub(crate) revocation_basepoint: PublicKey,
207 pub(crate) payment_basepoint: PublicKey,
208 pub(crate) delayed_payment_basepoint: PublicKey,
209 pub(crate) htlc_basepoint: PublicKey,
210 pub(crate) first_per_commitment_point: PublicKey,
211 pub(crate) shutdown_scriptpubkey: Option<Script>,
214 /// A funding_created message to be sent or received from a peer
216 pub struct FundingCreated {
217 pub(crate) temporary_channel_id: [u8; 32],
218 pub(crate) funding_txid: Sha256dHash,
219 pub(crate) funding_output_index: u16,
220 pub(crate) signature: Signature,
223 /// A funding_signed message to be sent or received from a peer
225 pub struct FundingSigned {
226 pub(crate) channel_id: [u8; 32],
227 pub(crate) signature: Signature,
230 /// A funding_locked message to be sent or received from a peer
231 #[derive(Clone, PartialEq)]
232 pub struct FundingLocked {
233 pub(crate) channel_id: [u8; 32],
234 pub(crate) next_per_commitment_point: PublicKey,
237 /// A shutdown message to be sent or received from a peer
239 pub struct Shutdown {
240 pub(crate) channel_id: [u8; 32],
241 pub(crate) scriptpubkey: Script,
244 /// A closing_signed message to be sent or received from a peer
246 pub struct ClosingSigned {
247 pub(crate) channel_id: [u8; 32],
248 pub(crate) fee_satoshis: u64,
249 pub(crate) signature: Signature,
252 /// An update_add_htlc message to be sent or received from a peer
253 #[derive(Clone, PartialEq)]
254 pub struct UpdateAddHTLC {
255 pub(crate) channel_id: [u8; 32],
256 pub(crate) htlc_id: u64,
257 pub(crate) amount_msat: u64,
258 pub(crate) payment_hash: [u8; 32],
259 pub(crate) cltv_expiry: u32,
260 pub(crate) onion_routing_packet: OnionPacket,
263 /// An update_fulfill_htlc message to be sent or received from a peer
264 #[derive(Clone, PartialEq)]
265 pub struct UpdateFulfillHTLC {
266 pub(crate) channel_id: [u8; 32],
267 pub(crate) htlc_id: u64,
268 pub(crate) payment_preimage: [u8; 32],
271 /// An update_fail_htlc message to be sent or received from a peer
272 #[derive(Clone, PartialEq)]
273 pub struct UpdateFailHTLC {
274 pub(crate) channel_id: [u8; 32],
275 pub(crate) htlc_id: u64,
276 pub(crate) reason: OnionErrorPacket,
279 /// An update_fail_malformed_htlc message to be sent or received from a peer
280 #[derive(Clone, PartialEq)]
281 pub struct UpdateFailMalformedHTLC {
282 pub(crate) channel_id: [u8; 32],
283 pub(crate) htlc_id: u64,
284 pub(crate) sha256_of_onion: [u8; 32],
285 pub(crate) failure_code: u16,
288 /// A commitment_signed message to be sent or received from a peer
289 #[derive(Clone, PartialEq)]
290 pub struct CommitmentSigned {
291 pub(crate) channel_id: [u8; 32],
292 pub(crate) signature: Signature,
293 pub(crate) htlc_signatures: Vec<Signature>,
296 /// A revoke_and_ack message to be sent or received from a peer
297 #[derive(Clone, PartialEq)]
298 pub struct RevokeAndACK {
299 pub(crate) channel_id: [u8; 32],
300 pub(crate) per_commitment_secret: [u8; 32],
301 pub(crate) next_per_commitment_point: PublicKey,
304 /// An update_fee message to be sent or received from a peer
305 #[derive(PartialEq, Clone)]
306 pub struct UpdateFee {
307 pub(crate) channel_id: [u8; 32],
308 pub(crate) feerate_per_kw: u32,
312 pub(crate) struct DataLossProtect {
313 pub(crate) your_last_per_commitment_secret: [u8; 32],
314 pub(crate) my_current_per_commitment_point: PublicKey,
317 /// A channel_reestablish message to be sent or received from a peer
319 pub struct ChannelReestablish {
320 pub(crate) channel_id: [u8; 32],
321 pub(crate) next_local_commitment_number: u64,
322 pub(crate) next_remote_commitment_number: u64,
323 pub(crate) data_loss_protect: Option<DataLossProtect>,
326 /// An announcement_signatures message to be sent or received from a peer
328 pub struct AnnouncementSignatures {
329 pub(crate) channel_id: [u8; 32],
330 pub(crate) short_channel_id: u64,
331 pub(crate) node_signature: Signature,
332 pub(crate) bitcoin_signature: Signature,
335 /// An address which can be used to connect to a remote peer
337 pub enum NetAddress {
338 /// An IPv4 address/port on which the peer is listenting.
340 /// The 4-byte IPv4 address
342 /// The port on which the node is listenting
345 /// An IPv6 address/port on which the peer is listenting.
347 /// The 16-byte IPv6 address
349 /// The port on which the node is listenting
352 /// An old-style Tor onion address/port on which the peer is listening.
354 /// The bytes (usually encoded in base32 with ".onion" appended)
356 /// The port on which the node is listenting
359 /// A new-style Tor onion address/port on which the peer is listening.
360 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
361 /// wrap as base32 and append ".onion".
363 /// The ed25519 long-term public key of the peer
364 ed25519_pubkey: [u8; 32],
365 /// The checksum of the pubkey and version, as included in the onion address
367 /// The version byte, as defined by the Tor Onion v3 spec.
369 /// The port on which the node is listenting
374 fn get_id(&self) -> u8 {
376 &NetAddress::IPv4 {..} => { 1 },
377 &NetAddress::IPv6 {..} => { 2 },
378 &NetAddress::OnionV2 {..} => { 3 },
379 &NetAddress::OnionV3 {..} => { 4 },
384 // Only exposed as broadcast of node_announcement should be filtered by node_id
385 /// The unsigned part of a node_announcement
386 pub struct UnsignedNodeAnnouncement {
387 pub(crate) features: GlobalFeatures,
388 pub(crate) timestamp: u32,
389 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
391 pub node_id: PublicKey,
392 pub(crate) rgb: [u8; 3],
393 pub(crate) alias: [u8; 32],
394 /// List of addresses on which this node is reachable. Note that you may only have up to one
395 /// address of each type, if you have more, they may be silently discarded or we may panic!
396 pub(crate) addresses: Vec<NetAddress>,
397 pub(crate) excess_address_data: Vec<u8>,
398 pub(crate) excess_data: Vec<u8>,
400 /// A node_announcement message to be sent or received from a peer
401 pub struct NodeAnnouncement {
402 pub(crate) signature: Signature,
403 pub(crate) contents: UnsignedNodeAnnouncement,
406 // Only exposed as broadcast of channel_announcement should be filtered by node_id
407 /// The unsigned part of a channel_announcement
408 #[derive(PartialEq, Clone)]
409 pub struct UnsignedChannelAnnouncement {
410 pub(crate) features: GlobalFeatures,
411 pub(crate) chain_hash: Sha256dHash,
412 pub(crate) short_channel_id: u64,
413 /// One of the two node_ids which are endpoints of this channel
414 pub node_id_1: PublicKey,
415 /// The other of the two node_ids which are endpoints of this channel
416 pub node_id_2: PublicKey,
417 pub(crate) bitcoin_key_1: PublicKey,
418 pub(crate) bitcoin_key_2: PublicKey,
419 pub(crate) excess_data: Vec<u8>,
421 /// A channel_announcement message to be sent or received from a peer
422 #[derive(PartialEq, Clone)]
423 pub struct ChannelAnnouncement {
424 pub(crate) node_signature_1: Signature,
425 pub(crate) node_signature_2: Signature,
426 pub(crate) bitcoin_signature_1: Signature,
427 pub(crate) bitcoin_signature_2: Signature,
428 pub(crate) contents: UnsignedChannelAnnouncement,
431 #[derive(PartialEq, Clone)]
432 pub(crate) struct UnsignedChannelUpdate {
433 pub(crate) chain_hash: Sha256dHash,
434 pub(crate) short_channel_id: u64,
435 pub(crate) timestamp: u32,
436 pub(crate) flags: u16,
437 pub(crate) cltv_expiry_delta: u16,
438 pub(crate) htlc_minimum_msat: u64,
439 pub(crate) fee_base_msat: u32,
440 pub(crate) fee_proportional_millionths: u32,
441 pub(crate) excess_data: Vec<u8>,
443 /// A channel_update message to be sent or received from a peer
444 #[derive(PartialEq, Clone)]
445 pub struct ChannelUpdate {
446 pub(crate) signature: Signature,
447 pub(crate) contents: UnsignedChannelUpdate,
450 /// Used to put an error message in a HandleError
451 pub enum ErrorAction {
452 /// The peer took some action which made us think they were useless. Disconnect them.
454 /// An error message which we should make an effort to send before we disconnect.
455 msg: Option<ErrorMessage>
457 /// The peer did something harmless that we weren't able to process, just log and ignore
459 /// The peer did something incorrect. Tell them.
461 /// The message to send.
466 /// An Err type for failure to process messages.
467 pub struct HandleError { //TODO: rename me
468 /// A human-readable message describing the error
469 pub err: &'static str,
470 /// The action which should be taken against the offending peer.
471 pub action: Option<ErrorAction>, //TODO: Make this required
474 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
475 /// transaction updates if they were pending.
476 #[derive(PartialEq, Clone)]
477 pub struct CommitmentUpdate {
478 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
479 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
480 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
481 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
482 pub(crate) update_fee: Option<UpdateFee>,
483 pub(crate) commitment_signed: CommitmentSigned,
486 /// The information we received from a peer along the route of a payment we originated. This is
487 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
488 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
489 pub enum HTLCFailChannelUpdate {
490 /// We received an error which included a full ChannelUpdate message.
491 ChannelUpdateMessage {
492 /// The unwrapped message we received
495 /// We received an error which indicated only that a channel has been closed
497 /// The short_channel_id which has now closed.
498 short_channel_id: u64,
499 /// when this true, this channel should be permanently removed from the
500 /// consideration. Otherwise, this channel can be restored as new channel_update is received
503 /// We received an error which indicated only that a node has failed
505 /// The node_id that has failed.
507 /// when this true, node should be permanently removed from the
508 /// consideration. Otherwise, the channels connected to this node can be
509 /// restored as new channel_update is received
514 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
515 /// be sent in the order they appear in the return value, however sometimes the order needs to be
516 /// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
517 /// were originally sent). In those cases, this enum is also returned.
518 #[derive(Clone, PartialEq)]
519 pub enum RAACommitmentOrder {
520 /// Send the CommitmentUpdate messages first
522 /// Send the RevokeAndACK message first
526 /// A trait to describe an object which can receive channel messages.
528 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
529 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
530 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
532 /// Handle an incoming open_channel message from the given peer.
533 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
534 /// Handle an incoming accept_channel message from the given peer.
535 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
536 /// Handle an incoming funding_created message from the given peer.
537 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
538 /// Handle an incoming funding_signed message from the given peer.
539 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
540 /// Handle an incoming funding_locked message from the given peer.
541 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
544 /// Handle an incoming shutdown message from the given peer.
545 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
546 /// Handle an incoming closing_signed message from the given peer.
547 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
550 /// Handle an incoming update_add_htlc message from the given peer.
551 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
552 /// Handle an incoming update_fulfill_htlc message from the given peer.
553 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
554 /// Handle an incoming update_fail_htlc message from the given peer.
555 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
556 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
557 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
558 /// Handle an incoming commitment_signed message from the given peer.
559 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
560 /// Handle an incoming revoke_and_ack message from the given peer.
561 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
563 /// Handle an incoming update_fee message from the given peer.
564 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
566 // Channel-to-announce:
567 /// Handle an incoming announcement_signatures message from the given peer.
568 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
570 // Connection loss/reestablish:
571 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
572 /// is believed to be possible in the future (eg they're sending us messages we don't
573 /// understand or indicate they require unknown feature bits), no_connection_possible is set
574 /// and any outstanding channels should be failed.
575 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
577 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
578 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
579 /// Handle an incoming channel_reestablish message from the given peer.
580 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;
583 /// Handle an incoming error message from the given peer.
584 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
587 /// A trait to describe an object which can receive routing messages.
588 pub trait RoutingMessageHandler : Send + Sync {
589 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
590 /// false or returning an Err otherwise.
591 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
592 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
593 /// or returning an Err otherwise.
594 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
595 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
596 /// false or returning an Err otherwise.
597 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
598 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
599 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
602 pub(crate) struct OnionRealm0HopData {
603 pub(crate) short_channel_id: u64,
604 pub(crate) amt_to_forward: u64,
605 pub(crate) outgoing_cltv_value: u32,
606 // 12 bytes of 0-padding
609 mod fuzzy_internal_msgs {
610 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
611 // them from untrusted input):
613 use super::OnionRealm0HopData;
614 pub struct OnionHopData {
615 pub(crate) realm: u8,
616 pub(crate) data: OnionRealm0HopData,
617 pub(crate) hmac: [u8; 32],
619 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
621 pub struct DecodedOnionErrorPacket {
622 pub(crate) hmac: [u8; 32],
623 pub(crate) failuremsg: Vec<u8>,
624 pub(crate) pad: Vec<u8>,
627 #[cfg(feature = "fuzztarget")]
628 pub use self::fuzzy_internal_msgs::*;
629 #[cfg(not(feature = "fuzztarget"))]
630 pub(crate) use self::fuzzy_internal_msgs::*;
633 pub(crate) struct OnionPacket {
634 pub(crate) version: u8,
635 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
636 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
637 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
638 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
639 pub(crate) hop_data: [u8; 20*65],
640 pub(crate) hmac: [u8; 32],
643 impl PartialEq for OnionPacket {
644 fn eq(&self, other: &OnionPacket) -> bool {
645 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
646 if i != j { return false; }
648 self.version == other.version &&
649 self.public_key == other.public_key &&
650 self.hmac == other.hmac
654 #[derive(Clone, PartialEq)]
655 pub(crate) struct OnionErrorPacket {
656 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
657 // (TODO) We limit it in decode to much lower...
658 pub(crate) data: Vec<u8>,
661 impl Error for DecodeError {
662 fn description(&self) -> &str {
664 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
665 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
666 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
667 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
668 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
669 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
670 DecodeError::Io(ref e) => e.description(),
674 impl fmt::Display for DecodeError {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
676 f.write_str(self.description())
680 impl fmt::Debug for HandleError {
681 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
682 f.write_str(self.err)
686 impl From<::std::io::Error> for DecodeError {
687 fn from(e: ::std::io::Error) -> Self {
688 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
689 DecodeError::ShortRead
696 impl_writeable_len_match!(AcceptChannel, {
697 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
700 temporary_channel_id,
702 max_htlc_value_in_flight_msat,
703 channel_reserve_satoshis,
709 revocation_basepoint,
711 delayed_payment_basepoint,
713 first_per_commitment_point,
714 shutdown_scriptpubkey
717 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
724 impl Writeable for ChannelReestablish {
725 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
726 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
727 self.channel_id.write(w)?;
728 self.next_local_commitment_number.write(w)?;
729 self.next_remote_commitment_number.write(w)?;
730 if let Some(ref data_loss_protect) = self.data_loss_protect {
731 data_loss_protect.your_last_per_commitment_secret.write(w)?;
732 data_loss_protect.my_current_per_commitment_point.write(w)?;
738 impl<R: Read> Readable<R> for ChannelReestablish{
739 fn read(r: &mut R) -> Result<Self, DecodeError> {
741 channel_id: Readable::read(r)?,
742 next_local_commitment_number: Readable::read(r)?,
743 next_remote_commitment_number: Readable::read(r)?,
745 match <[u8; 32] as Readable<R>>::read(r) {
746 Ok(your_last_per_commitment_secret) =>
747 Some(DataLossProtect {
748 your_last_per_commitment_secret,
749 my_current_per_commitment_point: Readable::read(r)?,
751 Err(DecodeError::ShortRead) => None,
752 Err(e) => return Err(e)
759 impl_writeable!(ClosingSigned, 32+8+64, {
765 impl_writeable_len_match!(CommitmentSigned, {
766 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
773 impl_writeable_len_match!(DecodedOnionErrorPacket, {
774 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
781 impl_writeable!(FundingCreated, 32+32+2+64, {
782 temporary_channel_id,
784 funding_output_index,
788 impl_writeable!(FundingSigned, 32+64, {
793 impl_writeable!(FundingLocked, 32+33, {
795 next_per_commitment_point
798 impl_writeable_len_match!(GlobalFeatures, {
799 { GlobalFeatures { ref flags }, flags.len() + 2 }
804 impl_writeable_len_match!(LocalFeatures, {
805 { LocalFeatures { ref flags }, flags.len() + 2 }
810 impl_writeable_len_match!(Init, {
811 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
817 impl_writeable_len_match!(OpenChannel, {
818 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
819 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
822 temporary_channel_id,
826 max_htlc_value_in_flight_msat,
827 channel_reserve_satoshis,
833 revocation_basepoint,
835 delayed_payment_basepoint,
837 first_per_commitment_point,
839 shutdown_scriptpubkey
842 impl_writeable!(RevokeAndACK, 32+32+33, {
844 per_commitment_secret,
845 next_per_commitment_point
848 impl_writeable_len_match!(Shutdown, {
849 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
855 impl_writeable_len_match!(UpdateFailHTLC, {
856 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
863 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
870 impl_writeable!(UpdateFee, 32+4, {
875 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
881 impl_writeable_len_match!(OnionErrorPacket, {
882 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
887 impl Writeable for OnionPacket {
888 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
889 w.size_hint(1 + 33 + 20*65 + 32);
890 self.version.write(w)?;
891 match self.public_key {
892 Ok(pubkey) => pubkey.write(w)?,
893 Err(_) => [0u8;33].write(w)?,
895 w.write_all(&self.hop_data)?;
901 impl<R: Read> Readable<R> for OnionPacket {
902 fn read(r: &mut R) -> Result<Self, DecodeError> {
904 version: Readable::read(r)?,
906 let mut buf = [0u8;33];
907 r.read_exact(&mut buf)?;
908 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
910 hop_data: Readable::read(r)?,
911 hmac: Readable::read(r)?,
916 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
925 impl Writeable for OnionRealm0HopData {
926 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
928 self.short_channel_id.write(w)?;
929 self.amt_to_forward.write(w)?;
930 self.outgoing_cltv_value.write(w)?;
931 w.write_all(&[0;12])?;
936 impl<R: Read> Readable<R> for OnionRealm0HopData {
937 fn read(r: &mut R) -> Result<Self, DecodeError> {
938 Ok(OnionRealm0HopData {
939 short_channel_id: Readable::read(r)?,
940 amt_to_forward: Readable::read(r)?,
941 outgoing_cltv_value: {
942 let v: u32 = Readable::read(r)?;
943 r.read_exact(&mut [0; 12])?;
950 impl Writeable for OnionHopData {
951 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
953 self.realm.write(w)?;
960 impl<R: Read> Readable<R> for OnionHopData {
961 fn read(r: &mut R) -> Result<Self, DecodeError> {
964 let r: u8 = Readable::read(r)?;
966 return Err(DecodeError::UnknownVersion);
970 data: Readable::read(r)?,
971 hmac: Readable::read(r)?,
976 impl Writeable for Ping {
977 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
978 w.size_hint(self.byteslen as usize + 4);
979 self.ponglen.write(w)?;
980 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
985 impl<R: Read> Readable<R> for Ping {
986 fn read(r: &mut R) -> Result<Self, DecodeError> {
988 ponglen: Readable::read(r)?,
990 let byteslen = Readable::read(r)?;
991 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
998 impl Writeable for Pong {
999 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1000 w.size_hint(self.byteslen as usize + 2);
1001 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1006 impl<R: Read> Readable<R> for Pong {
1007 fn read(r: &mut R) -> Result<Self, DecodeError> {
1010 let byteslen = Readable::read(r)?;
1011 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1018 impl Writeable for UnsignedChannelAnnouncement {
1019 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1020 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1021 self.features.write(w)?;
1022 self.chain_hash.write(w)?;
1023 self.short_channel_id.write(w)?;
1024 self.node_id_1.write(w)?;
1025 self.node_id_2.write(w)?;
1026 self.bitcoin_key_1.write(w)?;
1027 self.bitcoin_key_2.write(w)?;
1028 w.write_all(&self.excess_data[..])?;
1033 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1034 fn read(r: &mut R) -> Result<Self, DecodeError> {
1037 let f: GlobalFeatures = Readable::read(r)?;
1038 if f.requires_unknown_bits() {
1039 return Err(DecodeError::UnknownRequiredFeature);
1043 chain_hash: Readable::read(r)?,
1044 short_channel_id: Readable::read(r)?,
1045 node_id_1: Readable::read(r)?,
1046 node_id_2: Readable::read(r)?,
1047 bitcoin_key_1: Readable::read(r)?,
1048 bitcoin_key_2: Readable::read(r)?,
1050 let mut excess_data = vec![];
1051 r.read_to_end(&mut excess_data)?;
1058 impl_writeable_len_match!(ChannelAnnouncement, {
1059 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1060 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1064 bitcoin_signature_1,
1065 bitcoin_signature_2,
1069 impl Writeable for UnsignedChannelUpdate {
1070 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1071 w.size_hint(64 + self.excess_data.len());
1072 self.chain_hash.write(w)?;
1073 self.short_channel_id.write(w)?;
1074 self.timestamp.write(w)?;
1075 self.flags.write(w)?;
1076 self.cltv_expiry_delta.write(w)?;
1077 self.htlc_minimum_msat.write(w)?;
1078 self.fee_base_msat.write(w)?;
1079 self.fee_proportional_millionths.write(w)?;
1080 w.write_all(&self.excess_data[..])?;
1085 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1086 fn read(r: &mut R) -> Result<Self, DecodeError> {
1088 chain_hash: Readable::read(r)?,
1089 short_channel_id: Readable::read(r)?,
1090 timestamp: Readable::read(r)?,
1091 flags: Readable::read(r)?,
1092 cltv_expiry_delta: Readable::read(r)?,
1093 htlc_minimum_msat: Readable::read(r)?,
1094 fee_base_msat: Readable::read(r)?,
1095 fee_proportional_millionths: Readable::read(r)?,
1097 let mut excess_data = vec![];
1098 r.read_to_end(&mut excess_data)?;
1105 impl_writeable_len_match!(ChannelUpdate, {
1106 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1107 64 + excess_data.len() + 64 }
1113 impl Writeable for ErrorMessage {
1114 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1115 w.size_hint(32 + 2 + self.data.len());
1116 self.channel_id.write(w)?;
1117 (self.data.len() as u16).write(w)?;
1118 w.write_all(self.data.as_bytes())?;
1123 impl<R: Read> Readable<R> for ErrorMessage {
1124 fn read(r: &mut R) -> Result<Self, DecodeError> {
1126 channel_id: Readable::read(r)?,
1128 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1129 let mut data = vec![];
1130 let data_len = r.read_to_end(&mut data)?;
1131 sz = cmp::min(data_len, sz);
1132 match String::from_utf8(data[..sz as usize].to_vec()) {
1134 Err(_) => return Err(DecodeError::InvalidValue),
1141 impl Writeable for UnsignedNodeAnnouncement {
1142 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1143 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1144 self.features.write(w)?;
1145 self.timestamp.write(w)?;
1146 self.node_id.write(w)?;
1147 w.write_all(&self.rgb)?;
1148 self.alias.write(w)?;
1150 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1151 let mut addrs_to_encode = self.addresses.clone();
1152 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1153 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1154 for addr in addrs_to_encode.iter() {
1156 &NetAddress::IPv4{addr, port} => {
1158 addr_slice.extend_from_slice(&addr);
1159 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1161 &NetAddress::IPv6{addr, port} => {
1163 addr_slice.extend_from_slice(&addr);
1164 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1166 &NetAddress::OnionV2{addr, port} => {
1168 addr_slice.extend_from_slice(&addr);
1169 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1171 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1173 addr_slice.extend_from_slice(&ed25519_pubkey);
1174 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1175 addr_slice.push(version);
1176 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1180 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1181 w.write_all(&addr_slice[..])?;
1182 w.write_all(&self.excess_address_data[..])?;
1183 w.write_all(&self.excess_data[..])?;
1188 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1189 fn read(r: &mut R) -> Result<Self, DecodeError> {
1190 let features: GlobalFeatures = Readable::read(r)?;
1191 if features.requires_unknown_bits() {
1192 return Err(DecodeError::UnknownRequiredFeature);
1194 let timestamp: u32 = Readable::read(r)?;
1195 let node_id: PublicKey = Readable::read(r)?;
1196 let mut rgb = [0; 3];
1197 r.read_exact(&mut rgb)?;
1198 let alias: [u8; 32] = Readable::read(r)?;
1200 let addrlen: u16 = Readable::read(r)?;
1201 let mut addr_readpos = 0;
1202 let mut addresses = Vec::with_capacity(4);
1206 if addrlen <= addr_readpos { break; }
1207 f = Readable::read(r)?;
1210 if addresses.len() > 0 {
1211 return Err(DecodeError::ExtraAddressesPerType);
1213 if addrlen < addr_readpos + 1 + 6 {
1214 return Err(DecodeError::BadLengthDescriptor);
1216 addresses.push(NetAddress::IPv4 {
1218 let mut addr = [0; 4];
1219 r.read_exact(&mut addr)?;
1222 port: Readable::read(r)?,
1224 addr_readpos += 1 + 6
1227 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1228 return Err(DecodeError::ExtraAddressesPerType);
1230 if addrlen < addr_readpos + 1 + 18 {
1231 return Err(DecodeError::BadLengthDescriptor);
1233 addresses.push(NetAddress::IPv6 {
1235 let mut addr = [0; 16];
1236 r.read_exact(&mut addr)?;
1239 port: Readable::read(r)?,
1241 addr_readpos += 1 + 18
1244 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1245 return Err(DecodeError::ExtraAddressesPerType);
1247 if addrlen < addr_readpos + 1 + 12 {
1248 return Err(DecodeError::BadLengthDescriptor);
1250 addresses.push(NetAddress::OnionV2 {
1252 let mut addr = [0; 10];
1253 r.read_exact(&mut addr)?;
1256 port: Readable::read(r)?,
1258 addr_readpos += 1 + 12
1261 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1262 return Err(DecodeError::ExtraAddressesPerType);
1264 if addrlen < addr_readpos + 1 + 37 {
1265 return Err(DecodeError::BadLengthDescriptor);
1267 addresses.push(NetAddress::OnionV3 {
1268 ed25519_pubkey: Readable::read(r)?,
1269 checksum: Readable::read(r)?,
1270 version: Readable::read(r)?,
1271 port: Readable::read(r)?,
1273 addr_readpos += 1 + 37
1275 _ => { excess = 1; break; }
1279 let mut excess_data = vec![];
1280 let excess_address_data = if addr_readpos < addrlen {
1281 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1282 r.read_exact(&mut excess_address_data[excess..])?;
1284 excess_address_data[0] = f;
1289 excess_data.push(f);
1294 Ok(UnsignedNodeAnnouncement {
1296 timestamp: timestamp,
1300 addresses: addresses,
1301 excess_address_data: excess_address_data,
1303 r.read_to_end(&mut excess_data)?;
1310 impl_writeable_len_match!(NodeAnnouncement, {
1311 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1312 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1322 use util::ser::Writeable;
1323 use secp256k1::key::{PublicKey,SecretKey};
1324 use secp256k1::Secp256k1;
1327 fn encoding_channel_reestablish_no_secret() {
1328 let cr = msgs::ChannelReestablish {
1329 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1330 next_local_commitment_number: 3,
1331 next_remote_commitment_number: 4,
1332 data_loss_protect: None,
1335 let encoded_value = cr.encode();
1338 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4]
1343 fn encoding_channel_reestablish_with_secret() {
1345 let secp_ctx = Secp256k1::new();
1346 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1349 let cr = msgs::ChannelReestablish {
1350 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1351 next_local_commitment_number: 3,
1352 next_remote_commitment_number: 4,
1353 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1356 let encoded_value = cr.encode();
1359 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30, 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7, 143]