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 use ln::channelmanager::{PaymentPreimage, PaymentHash};
34 /// An error in decoding a message or struct.
36 pub enum DecodeError {
37 /// A version byte specified something we don't know how to handle.
38 /// Includes unknown realm byte in an OnionHopData packet
40 /// Unknown feature mandating we fail to parse message
41 UnknownRequiredFeature,
42 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
43 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
47 /// node_announcement included more than one address of a given type!
48 ExtraAddressesPerType,
49 /// A length descriptor in the packet didn't describe the later data correctly
50 /// (currently only generated in node_announcement)
52 /// Error from std::io
56 /// Tracks localfeatures which are only in init messages
57 #[derive(Clone, PartialEq)]
58 pub struct LocalFeatures {
63 pub(crate) fn new() -> LocalFeatures {
69 pub(crate) fn supports_data_loss_protect(&self) -> bool {
70 self.flags.len() > 0 && (self.flags[0] & 3) != 0
72 pub(crate) fn requires_data_loss_protect(&self) -> bool {
73 self.flags.len() > 0 && (self.flags[0] & 1) != 0
76 pub(crate) fn initial_routing_sync(&self) -> bool {
77 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
79 pub(crate) fn set_initial_routing_sync(&mut self) {
80 if self.flags.len() == 0 {
81 self.flags.resize(1, 1 << 3);
83 self.flags[0] |= 1 << 3;
87 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
88 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
90 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
91 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
94 pub(crate) fn requires_unknown_bits(&self) -> bool {
95 for (idx, &byte) in self.flags.iter().enumerate() {
96 if idx != 0 && (byte & 0x55) != 0 {
98 } else if idx == 0 && (byte & 0x14) != 0 {
105 pub(crate) fn supports_unknown_bits(&self) -> bool {
106 for (idx, &byte) in self.flags.iter().enumerate() {
107 if idx != 0 && byte != 0 {
109 } else if idx == 0 && (byte & 0xc4) != 0 {
117 /// Tracks globalfeatures which are in init messages and routing announcements
118 #[derive(Clone, PartialEq)]
119 pub struct GlobalFeatures {
123 impl GlobalFeatures {
124 pub(crate) fn new() -> GlobalFeatures {
130 pub(crate) fn requires_unknown_bits(&self) -> bool {
131 for &byte in self.flags.iter() {
132 if (byte & 0x55) != 0 {
139 pub(crate) fn supports_unknown_bits(&self) -> bool {
140 for &byte in self.flags.iter() {
149 /// An init message to be sent or received from a peer
151 pub(crate) global_features: GlobalFeatures,
152 pub(crate) local_features: LocalFeatures,
155 /// An error message to be sent or received from a peer
157 pub struct ErrorMessage {
158 pub(crate) channel_id: [u8; 32],
159 pub(crate) data: String,
162 /// A ping message to be sent or received from a peer
164 pub(crate) ponglen: u16,
165 pub(crate) byteslen: u16,
168 /// A pong message to be sent or received from a peer
170 pub(crate) byteslen: u16,
173 /// An open_channel message to be sent or received from a peer
175 pub struct OpenChannel {
176 pub(crate) chain_hash: Sha256dHash,
177 pub(crate) temporary_channel_id: [u8; 32],
178 pub(crate) funding_satoshis: u64,
179 pub(crate) push_msat: u64,
180 pub(crate) dust_limit_satoshis: u64,
181 pub(crate) max_htlc_value_in_flight_msat: u64,
182 pub(crate) channel_reserve_satoshis: u64,
183 pub(crate) htlc_minimum_msat: u64,
184 pub(crate) feerate_per_kw: u32,
185 pub(crate) to_self_delay: u16,
186 pub(crate) max_accepted_htlcs: u16,
187 pub(crate) funding_pubkey: PublicKey,
188 pub(crate) revocation_basepoint: PublicKey,
189 pub(crate) payment_basepoint: PublicKey,
190 pub(crate) delayed_payment_basepoint: PublicKey,
191 pub(crate) htlc_basepoint: PublicKey,
192 pub(crate) first_per_commitment_point: PublicKey,
193 pub(crate) channel_flags: u8,
194 pub(crate) shutdown_scriptpubkey: Option<Script>,
197 /// An accept_channel message to be sent or received from a peer
199 pub struct AcceptChannel {
200 pub(crate) temporary_channel_id: [u8; 32],
201 pub(crate) dust_limit_satoshis: u64,
202 pub(crate) max_htlc_value_in_flight_msat: u64,
203 pub(crate) channel_reserve_satoshis: u64,
204 pub(crate) htlc_minimum_msat: u64,
205 pub(crate) minimum_depth: u32,
206 pub(crate) to_self_delay: u16,
207 pub(crate) max_accepted_htlcs: u16,
208 pub(crate) funding_pubkey: PublicKey,
209 pub(crate) revocation_basepoint: PublicKey,
210 pub(crate) payment_basepoint: PublicKey,
211 pub(crate) delayed_payment_basepoint: PublicKey,
212 pub(crate) htlc_basepoint: PublicKey,
213 pub(crate) first_per_commitment_point: PublicKey,
214 pub(crate) shutdown_scriptpubkey: Option<Script>,
217 /// A funding_created message to be sent or received from a peer
219 pub struct FundingCreated {
220 pub(crate) temporary_channel_id: [u8; 32],
221 pub(crate) funding_txid: Sha256dHash,
222 pub(crate) funding_output_index: u16,
223 pub(crate) signature: Signature,
226 /// A funding_signed message to be sent or received from a peer
228 pub struct FundingSigned {
229 pub(crate) channel_id: [u8; 32],
230 pub(crate) signature: Signature,
233 /// A funding_locked message to be sent or received from a peer
234 #[derive(Clone, PartialEq)]
235 pub struct FundingLocked {
236 pub(crate) channel_id: [u8; 32],
237 pub(crate) next_per_commitment_point: PublicKey,
240 /// A shutdown message to be sent or received from a peer
241 #[derive(Clone, PartialEq)]
242 pub struct Shutdown {
243 pub(crate) channel_id: [u8; 32],
244 pub(crate) scriptpubkey: Script,
247 /// A closing_signed message to be sent or received from a peer
248 #[derive(Clone, PartialEq)]
249 pub struct ClosingSigned {
250 pub(crate) channel_id: [u8; 32],
251 pub(crate) fee_satoshis: u64,
252 pub(crate) signature: Signature,
255 /// An update_add_htlc message to be sent or received from a peer
256 #[derive(Clone, PartialEq)]
257 pub struct UpdateAddHTLC {
258 pub(crate) channel_id: [u8; 32],
259 pub(crate) htlc_id: u64,
260 pub(crate) amount_msat: u64,
261 pub(crate) payment_hash: PaymentHash,
262 pub(crate) cltv_expiry: u32,
263 pub(crate) onion_routing_packet: OnionPacket,
266 /// An update_fulfill_htlc message to be sent or received from a peer
267 #[derive(Clone, PartialEq)]
268 pub struct UpdateFulfillHTLC {
269 pub(crate) channel_id: [u8; 32],
270 pub(crate) htlc_id: u64,
271 pub(crate) payment_preimage: PaymentPreimage,
274 /// An update_fail_htlc message to be sent or received from a peer
275 #[derive(Clone, PartialEq)]
276 pub struct UpdateFailHTLC {
277 pub(crate) channel_id: [u8; 32],
278 pub(crate) htlc_id: u64,
279 pub(crate) reason: OnionErrorPacket,
282 /// An update_fail_malformed_htlc message to be sent or received from a peer
283 #[derive(Clone, PartialEq)]
284 pub struct UpdateFailMalformedHTLC {
285 pub(crate) channel_id: [u8; 32],
286 pub(crate) htlc_id: u64,
287 pub(crate) sha256_of_onion: [u8; 32],
288 pub(crate) failure_code: u16,
291 /// A commitment_signed message to be sent or received from a peer
292 #[derive(Clone, PartialEq)]
293 pub struct CommitmentSigned {
294 pub(crate) channel_id: [u8; 32],
295 pub(crate) signature: Signature,
296 pub(crate) htlc_signatures: Vec<Signature>,
299 /// A revoke_and_ack message to be sent or received from a peer
300 #[derive(Clone, PartialEq)]
301 pub struct RevokeAndACK {
302 pub(crate) channel_id: [u8; 32],
303 pub(crate) per_commitment_secret: [u8; 32],
304 pub(crate) next_per_commitment_point: PublicKey,
307 /// An update_fee message to be sent or received from a peer
308 #[derive(PartialEq, Clone)]
309 pub struct UpdateFee {
310 pub(crate) channel_id: [u8; 32],
311 pub(crate) feerate_per_kw: u32,
314 #[derive(PartialEq, Clone)]
315 pub(crate) struct DataLossProtect {
316 pub(crate) your_last_per_commitment_secret: [u8; 32],
317 pub(crate) my_current_per_commitment_point: PublicKey,
320 /// A channel_reestablish message to be sent or received from a peer
321 #[derive(PartialEq, Clone)]
322 pub struct ChannelReestablish {
323 pub(crate) channel_id: [u8; 32],
324 pub(crate) next_local_commitment_number: u64,
325 pub(crate) next_remote_commitment_number: u64,
326 pub(crate) data_loss_protect: Option<DataLossProtect>,
329 /// An announcement_signatures message to be sent or received from a peer
331 pub struct AnnouncementSignatures {
332 pub(crate) channel_id: [u8; 32],
333 pub(crate) short_channel_id: u64,
334 pub(crate) node_signature: Signature,
335 pub(crate) bitcoin_signature: Signature,
338 /// An address which can be used to connect to a remote peer
340 pub enum NetAddress {
341 /// An IPv4 address/port on which the peer is listenting.
343 /// The 4-byte IPv4 address
345 /// The port on which the node is listenting
348 /// An IPv6 address/port on which the peer is listenting.
350 /// The 16-byte IPv6 address
352 /// The port on which the node is listenting
355 /// An old-style Tor onion address/port on which the peer is listening.
357 /// The bytes (usually encoded in base32 with ".onion" appended)
359 /// The port on which the node is listenting
362 /// A new-style Tor onion address/port on which the peer is listening.
363 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
364 /// wrap as base32 and append ".onion".
366 /// The ed25519 long-term public key of the peer
367 ed25519_pubkey: [u8; 32],
368 /// The checksum of the pubkey and version, as included in the onion address
370 /// The version byte, as defined by the Tor Onion v3 spec.
372 /// The port on which the node is listenting
377 fn get_id(&self) -> u8 {
379 &NetAddress::IPv4 {..} => { 1 },
380 &NetAddress::IPv6 {..} => { 2 },
381 &NetAddress::OnionV2 {..} => { 3 },
382 &NetAddress::OnionV3 {..} => { 4 },
388 // Only exposed as broadcast of node_announcement should be filtered by node_id
389 /// The unsigned part of a node_announcement
390 pub struct UnsignedNodeAnnouncement {
391 pub(crate) features: GlobalFeatures,
392 pub(crate) timestamp: u32,
393 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
395 pub node_id: PublicKey,
396 pub(crate) rgb: [u8; 3],
397 pub(crate) alias: [u8; 32],
398 /// List of addresses on which this node is reachable. Note that you may only have up to one
399 /// address of each type, if you have more, they may be silently discarded or we may panic!
400 pub(crate) addresses: Vec<NetAddress>,
401 pub(crate) excess_address_data: Vec<u8>,
402 pub(crate) excess_data: Vec<u8>,
405 /// A node_announcement message to be sent or received from a peer
406 pub struct NodeAnnouncement {
407 pub(crate) signature: Signature,
408 pub(crate) contents: UnsignedNodeAnnouncement,
411 // Only exposed as broadcast of channel_announcement should be filtered by node_id
412 /// The unsigned part of a channel_announcement
413 #[derive(PartialEq, Clone)]
414 pub struct UnsignedChannelAnnouncement {
415 pub(crate) features: GlobalFeatures,
416 pub(crate) chain_hash: Sha256dHash,
417 pub(crate) short_channel_id: u64,
418 /// One of the two node_ids which are endpoints of this channel
419 pub node_id_1: PublicKey,
420 /// The other of the two node_ids which are endpoints of this channel
421 pub node_id_2: PublicKey,
422 pub(crate) bitcoin_key_1: PublicKey,
423 pub(crate) bitcoin_key_2: PublicKey,
424 pub(crate) excess_data: Vec<u8>,
426 /// A channel_announcement message to be sent or received from a peer
427 #[derive(PartialEq, Clone)]
428 pub struct ChannelAnnouncement {
429 pub(crate) node_signature_1: Signature,
430 pub(crate) node_signature_2: Signature,
431 pub(crate) bitcoin_signature_1: Signature,
432 pub(crate) bitcoin_signature_2: Signature,
433 pub(crate) contents: UnsignedChannelAnnouncement,
436 #[derive(PartialEq, Clone)]
437 pub(crate) struct UnsignedChannelUpdate {
438 pub(crate) chain_hash: Sha256dHash,
439 pub(crate) short_channel_id: u64,
440 pub(crate) timestamp: u32,
441 pub(crate) flags: u16,
442 pub(crate) cltv_expiry_delta: u16,
443 pub(crate) htlc_minimum_msat: u64,
444 pub(crate) fee_base_msat: u32,
445 pub(crate) fee_proportional_millionths: u32,
446 pub(crate) excess_data: Vec<u8>,
448 /// A channel_update message to be sent or received from a peer
449 #[derive(PartialEq, Clone)]
450 pub struct ChannelUpdate {
451 pub(crate) signature: Signature,
452 pub(crate) contents: UnsignedChannelUpdate,
455 /// Used to put an error message in a HandleError
457 pub enum ErrorAction {
458 /// The peer took some action which made us think they were useless. Disconnect them.
460 /// An error message which we should make an effort to send before we disconnect.
461 msg: Option<ErrorMessage>
463 /// The peer did something harmless that we weren't able to process, just log and ignore
465 /// The peer did something incorrect. Tell them.
467 /// The message to send.
472 /// An Err type for failure to process messages.
473 pub struct HandleError { //TODO: rename me
474 /// A human-readable message describing the error
475 pub err: &'static str,
476 /// The action which should be taken against the offending peer.
477 pub action: Option<ErrorAction>, //TODO: Make this required
480 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
481 /// transaction updates if they were pending.
482 #[derive(PartialEq, Clone)]
483 pub struct CommitmentUpdate {
484 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
485 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
486 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
487 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
488 pub(crate) update_fee: Option<UpdateFee>,
489 pub(crate) commitment_signed: CommitmentSigned,
492 /// The information we received from a peer along the route of a payment we originated. This is
493 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
494 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
496 pub enum HTLCFailChannelUpdate {
497 /// We received an error which included a full ChannelUpdate message.
498 ChannelUpdateMessage {
499 /// The unwrapped message we received
502 /// We received an error which indicated only that a channel has been closed
504 /// The short_channel_id which has now closed.
505 short_channel_id: u64,
506 /// when this true, this channel should be permanently removed from the
507 /// consideration. Otherwise, this channel can be restored as new channel_update is received
510 /// We received an error which indicated only that a node has failed
512 /// The node_id that has failed.
514 /// when this true, node should be permanently removed from the
515 /// consideration. Otherwise, the channels connected to this node can be
516 /// restored as new channel_update is received
521 /// A trait to describe an object which can receive channel messages.
523 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
524 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
525 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
527 /// Handle an incoming open_channel message from the given peer.
528 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
529 /// Handle an incoming accept_channel message from the given peer.
530 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
531 /// Handle an incoming funding_created message from the given peer.
532 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
533 /// Handle an incoming funding_signed message from the given peer.
534 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
535 /// Handle an incoming funding_locked message from the given peer.
536 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
539 /// Handle an incoming shutdown message from the given peer.
540 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
541 /// Handle an incoming closing_signed message from the given peer.
542 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
545 /// Handle an incoming update_add_htlc message from the given peer.
546 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
547 /// Handle an incoming update_fulfill_htlc message from the given peer.
548 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
549 /// Handle an incoming update_fail_htlc message from the given peer.
550 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
551 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
552 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
553 /// Handle an incoming commitment_signed message from the given peer.
554 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
555 /// Handle an incoming revoke_and_ack message from the given peer.
556 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
558 /// Handle an incoming update_fee message from the given peer.
559 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
561 // Channel-to-announce:
562 /// Handle an incoming announcement_signatures message from the given peer.
563 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
565 // Connection loss/reestablish:
566 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
567 /// is believed to be possible in the future (eg they're sending us messages we don't
568 /// understand or indicate they require unknown feature bits), no_connection_possible is set
569 /// and any outstanding channels should be failed.
570 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
572 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
573 fn peer_connected(&self, their_node_id: &PublicKey);
574 /// Handle an incoming channel_reestablish message from the given peer.
575 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
578 /// Handle an incoming error message from the given peer.
579 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
582 /// A trait to describe an object which can receive routing messages.
583 pub trait RoutingMessageHandler : Send + Sync {
584 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
585 /// false or returning an Err otherwise.
586 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
587 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
588 /// or returning an Err otherwise.
589 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
590 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
591 /// false or returning an Err otherwise.
592 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
593 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
594 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
595 /// Gets a subset of the channel announcements and updates required to dump our routing table
596 /// to a remote node, starting at the short_channel_id indicated by starting_point and
597 /// including batch_amount entries.
598 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
599 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
600 /// starting at the node *after* the provided publickey and including batch_amount entries.
601 /// If None is provided for starting_point, we start at the first node.
602 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
605 pub(crate) struct OnionRealm0HopData {
606 pub(crate) short_channel_id: u64,
607 pub(crate) amt_to_forward: u64,
608 pub(crate) outgoing_cltv_value: u32,
609 // 12 bytes of 0-padding
612 mod fuzzy_internal_msgs {
613 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
614 // them from untrusted input):
616 use super::OnionRealm0HopData;
617 pub struct OnionHopData {
618 pub(crate) realm: u8,
619 pub(crate) data: OnionRealm0HopData,
620 pub(crate) hmac: [u8; 32],
622 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
624 pub struct DecodedOnionErrorPacket {
625 pub(crate) hmac: [u8; 32],
626 pub(crate) failuremsg: Vec<u8>,
627 pub(crate) pad: Vec<u8>,
630 #[cfg(feature = "fuzztarget")]
631 pub use self::fuzzy_internal_msgs::*;
632 #[cfg(not(feature = "fuzztarget"))]
633 pub(crate) use self::fuzzy_internal_msgs::*;
636 pub(crate) struct OnionPacket {
637 pub(crate) version: u8,
638 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
639 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
640 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
641 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
642 pub(crate) hop_data: [u8; 20*65],
643 pub(crate) hmac: [u8; 32],
646 impl PartialEq for OnionPacket {
647 fn eq(&self, other: &OnionPacket) -> bool {
648 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
649 if i != j { return false; }
651 self.version == other.version &&
652 self.public_key == other.public_key &&
653 self.hmac == other.hmac
657 #[derive(Clone, PartialEq)]
658 pub(crate) struct OnionErrorPacket {
659 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
660 // (TODO) We limit it in decode to much lower...
661 pub(crate) data: Vec<u8>,
664 impl Error for DecodeError {
665 fn description(&self) -> &str {
667 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
668 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
669 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
670 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
671 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
672 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
673 DecodeError::Io(ref e) => e.description(),
677 impl fmt::Display for DecodeError {
678 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
679 f.write_str(self.description())
683 impl fmt::Debug for HandleError {
684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
685 f.write_str(self.err)
689 impl From<::std::io::Error> for DecodeError {
690 fn from(e: ::std::io::Error) -> Self {
691 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
692 DecodeError::ShortRead
699 impl_writeable_len_match!(AcceptChannel, {
700 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
703 temporary_channel_id,
705 max_htlc_value_in_flight_msat,
706 channel_reserve_satoshis,
712 revocation_basepoint,
714 delayed_payment_basepoint,
716 first_per_commitment_point,
717 shutdown_scriptpubkey
720 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
727 impl Writeable for ChannelReestablish {
728 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
729 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
730 self.channel_id.write(w)?;
731 self.next_local_commitment_number.write(w)?;
732 self.next_remote_commitment_number.write(w)?;
733 if let Some(ref data_loss_protect) = self.data_loss_protect {
734 data_loss_protect.your_last_per_commitment_secret.write(w)?;
735 data_loss_protect.my_current_per_commitment_point.write(w)?;
741 impl<R: Read> Readable<R> for ChannelReestablish{
742 fn read(r: &mut R) -> Result<Self, DecodeError> {
744 channel_id: Readable::read(r)?,
745 next_local_commitment_number: Readable::read(r)?,
746 next_remote_commitment_number: Readable::read(r)?,
748 match <[u8; 32] as Readable<R>>::read(r) {
749 Ok(your_last_per_commitment_secret) =>
750 Some(DataLossProtect {
751 your_last_per_commitment_secret,
752 my_current_per_commitment_point: Readable::read(r)?,
754 Err(DecodeError::ShortRead) => None,
755 Err(e) => return Err(e)
762 impl_writeable!(ClosingSigned, 32+8+64, {
768 impl_writeable_len_match!(CommitmentSigned, {
769 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
776 impl_writeable_len_match!(DecodedOnionErrorPacket, {
777 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
784 impl_writeable!(FundingCreated, 32+32+2+64, {
785 temporary_channel_id,
787 funding_output_index,
791 impl_writeable!(FundingSigned, 32+64, {
796 impl_writeable!(FundingLocked, 32+33, {
798 next_per_commitment_point
801 impl_writeable_len_match!(GlobalFeatures, {
802 { GlobalFeatures { ref flags }, flags.len() + 2 }
807 impl_writeable_len_match!(LocalFeatures, {
808 { LocalFeatures { ref flags }, flags.len() + 2 }
813 impl_writeable_len_match!(Init, {
814 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
820 impl_writeable_len_match!(OpenChannel, {
821 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
822 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
825 temporary_channel_id,
829 max_htlc_value_in_flight_msat,
830 channel_reserve_satoshis,
836 revocation_basepoint,
838 delayed_payment_basepoint,
840 first_per_commitment_point,
842 shutdown_scriptpubkey
845 impl_writeable!(RevokeAndACK, 32+32+33, {
847 per_commitment_secret,
848 next_per_commitment_point
851 impl_writeable_len_match!(Shutdown, {
852 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
858 impl_writeable_len_match!(UpdateFailHTLC, {
859 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
866 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
873 impl_writeable!(UpdateFee, 32+4, {
878 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
884 impl_writeable_len_match!(OnionErrorPacket, {
885 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
890 impl Writeable for OnionPacket {
891 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
892 w.size_hint(1 + 33 + 20*65 + 32);
893 self.version.write(w)?;
894 match self.public_key {
895 Ok(pubkey) => pubkey.write(w)?,
896 Err(_) => [0u8;33].write(w)?,
898 w.write_all(&self.hop_data)?;
904 impl<R: Read> Readable<R> for OnionPacket {
905 fn read(r: &mut R) -> Result<Self, DecodeError> {
907 version: Readable::read(r)?,
909 let mut buf = [0u8;33];
910 r.read_exact(&mut buf)?;
911 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
913 hop_data: Readable::read(r)?,
914 hmac: Readable::read(r)?,
919 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
928 impl Writeable for OnionRealm0HopData {
929 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
931 self.short_channel_id.write(w)?;
932 self.amt_to_forward.write(w)?;
933 self.outgoing_cltv_value.write(w)?;
934 w.write_all(&[0;12])?;
939 impl<R: Read> Readable<R> for OnionRealm0HopData {
940 fn read(r: &mut R) -> Result<Self, DecodeError> {
941 Ok(OnionRealm0HopData {
942 short_channel_id: Readable::read(r)?,
943 amt_to_forward: Readable::read(r)?,
944 outgoing_cltv_value: {
945 let v: u32 = Readable::read(r)?;
946 r.read_exact(&mut [0; 12])?;
953 impl Writeable for OnionHopData {
954 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
956 self.realm.write(w)?;
963 impl<R: Read> Readable<R> for OnionHopData {
964 fn read(r: &mut R) -> Result<Self, DecodeError> {
967 let r: u8 = Readable::read(r)?;
969 return Err(DecodeError::UnknownVersion);
973 data: Readable::read(r)?,
974 hmac: Readable::read(r)?,
979 impl Writeable for Ping {
980 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
981 w.size_hint(self.byteslen as usize + 4);
982 self.ponglen.write(w)?;
983 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
988 impl<R: Read> Readable<R> for Ping {
989 fn read(r: &mut R) -> Result<Self, DecodeError> {
991 ponglen: Readable::read(r)?,
993 let byteslen = Readable::read(r)?;
994 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1001 impl Writeable for Pong {
1002 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1003 w.size_hint(self.byteslen as usize + 2);
1004 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1009 impl<R: Read> Readable<R> for Pong {
1010 fn read(r: &mut R) -> Result<Self, DecodeError> {
1013 let byteslen = Readable::read(r)?;
1014 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1021 impl Writeable for UnsignedChannelAnnouncement {
1022 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1023 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1024 self.features.write(w)?;
1025 self.chain_hash.write(w)?;
1026 self.short_channel_id.write(w)?;
1027 self.node_id_1.write(w)?;
1028 self.node_id_2.write(w)?;
1029 self.bitcoin_key_1.write(w)?;
1030 self.bitcoin_key_2.write(w)?;
1031 w.write_all(&self.excess_data[..])?;
1036 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1037 fn read(r: &mut R) -> Result<Self, DecodeError> {
1040 let f: GlobalFeatures = Readable::read(r)?;
1041 if f.requires_unknown_bits() {
1042 return Err(DecodeError::UnknownRequiredFeature);
1046 chain_hash: Readable::read(r)?,
1047 short_channel_id: Readable::read(r)?,
1048 node_id_1: Readable::read(r)?,
1049 node_id_2: Readable::read(r)?,
1050 bitcoin_key_1: Readable::read(r)?,
1051 bitcoin_key_2: Readable::read(r)?,
1053 let mut excess_data = vec![];
1054 r.read_to_end(&mut excess_data)?;
1061 impl_writeable_len_match!(ChannelAnnouncement, {
1062 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1063 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1067 bitcoin_signature_1,
1068 bitcoin_signature_2,
1072 impl Writeable for UnsignedChannelUpdate {
1073 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1074 w.size_hint(64 + self.excess_data.len());
1075 self.chain_hash.write(w)?;
1076 self.short_channel_id.write(w)?;
1077 self.timestamp.write(w)?;
1078 self.flags.write(w)?;
1079 self.cltv_expiry_delta.write(w)?;
1080 self.htlc_minimum_msat.write(w)?;
1081 self.fee_base_msat.write(w)?;
1082 self.fee_proportional_millionths.write(w)?;
1083 w.write_all(&self.excess_data[..])?;
1088 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1089 fn read(r: &mut R) -> Result<Self, DecodeError> {
1091 chain_hash: Readable::read(r)?,
1092 short_channel_id: Readable::read(r)?,
1093 timestamp: Readable::read(r)?,
1094 flags: Readable::read(r)?,
1095 cltv_expiry_delta: Readable::read(r)?,
1096 htlc_minimum_msat: Readable::read(r)?,
1097 fee_base_msat: Readable::read(r)?,
1098 fee_proportional_millionths: Readable::read(r)?,
1100 let mut excess_data = vec![];
1101 r.read_to_end(&mut excess_data)?;
1108 impl_writeable_len_match!(ChannelUpdate, {
1109 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1110 64 + excess_data.len() + 64 }
1116 impl Writeable for ErrorMessage {
1117 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1118 w.size_hint(32 + 2 + self.data.len());
1119 self.channel_id.write(w)?;
1120 (self.data.len() as u16).write(w)?;
1121 w.write_all(self.data.as_bytes())?;
1126 impl<R: Read> Readable<R> for ErrorMessage {
1127 fn read(r: &mut R) -> Result<Self, DecodeError> {
1129 channel_id: Readable::read(r)?,
1131 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1132 let mut data = vec![];
1133 let data_len = r.read_to_end(&mut data)?;
1134 sz = cmp::min(data_len, sz);
1135 match String::from_utf8(data[..sz as usize].to_vec()) {
1137 Err(_) => return Err(DecodeError::InvalidValue),
1144 impl Writeable for UnsignedNodeAnnouncement {
1145 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1146 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1147 self.features.write(w)?;
1148 self.timestamp.write(w)?;
1149 self.node_id.write(w)?;
1150 w.write_all(&self.rgb)?;
1151 self.alias.write(w)?;
1153 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1154 let mut addrs_to_encode = self.addresses.clone();
1155 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1156 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1157 for addr in addrs_to_encode.iter() {
1159 &NetAddress::IPv4{addr, port} => {
1161 addr_slice.extend_from_slice(&addr);
1162 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1164 &NetAddress::IPv6{addr, port} => {
1166 addr_slice.extend_from_slice(&addr);
1167 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1169 &NetAddress::OnionV2{addr, port} => {
1171 addr_slice.extend_from_slice(&addr);
1172 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1174 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1176 addr_slice.extend_from_slice(&ed25519_pubkey);
1177 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1178 addr_slice.push(version);
1179 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1183 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1184 w.write_all(&addr_slice[..])?;
1185 w.write_all(&self.excess_address_data[..])?;
1186 w.write_all(&self.excess_data[..])?;
1191 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1192 fn read(r: &mut R) -> Result<Self, DecodeError> {
1193 let features: GlobalFeatures = Readable::read(r)?;
1194 if features.requires_unknown_bits() {
1195 return Err(DecodeError::UnknownRequiredFeature);
1197 let timestamp: u32 = Readable::read(r)?;
1198 let node_id: PublicKey = Readable::read(r)?;
1199 let mut rgb = [0; 3];
1200 r.read_exact(&mut rgb)?;
1201 let alias: [u8; 32] = Readable::read(r)?;
1203 let addrlen: u16 = Readable::read(r)?;
1204 let mut addr_readpos = 0;
1205 let mut addresses = Vec::with_capacity(4);
1209 if addrlen <= addr_readpos { break; }
1210 f = Readable::read(r)?;
1213 if addresses.len() > 0 {
1214 return Err(DecodeError::ExtraAddressesPerType);
1216 if addrlen < addr_readpos + 1 + 6 {
1217 return Err(DecodeError::BadLengthDescriptor);
1219 addresses.push(NetAddress::IPv4 {
1221 let mut addr = [0; 4];
1222 r.read_exact(&mut addr)?;
1225 port: Readable::read(r)?,
1227 addr_readpos += 1 + 6
1230 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1231 return Err(DecodeError::ExtraAddressesPerType);
1233 if addrlen < addr_readpos + 1 + 18 {
1234 return Err(DecodeError::BadLengthDescriptor);
1236 addresses.push(NetAddress::IPv6 {
1238 let mut addr = [0; 16];
1239 r.read_exact(&mut addr)?;
1242 port: Readable::read(r)?,
1244 addr_readpos += 1 + 18
1247 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1248 return Err(DecodeError::ExtraAddressesPerType);
1250 if addrlen < addr_readpos + 1 + 12 {
1251 return Err(DecodeError::BadLengthDescriptor);
1253 addresses.push(NetAddress::OnionV2 {
1255 let mut addr = [0; 10];
1256 r.read_exact(&mut addr)?;
1259 port: Readable::read(r)?,
1261 addr_readpos += 1 + 12
1264 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1265 return Err(DecodeError::ExtraAddressesPerType);
1267 if addrlen < addr_readpos + 1 + 37 {
1268 return Err(DecodeError::BadLengthDescriptor);
1270 addresses.push(NetAddress::OnionV3 {
1271 ed25519_pubkey: Readable::read(r)?,
1272 checksum: Readable::read(r)?,
1273 version: Readable::read(r)?,
1274 port: Readable::read(r)?,
1276 addr_readpos += 1 + 37
1278 _ => { excess = 1; break; }
1282 let mut excess_data = vec![];
1283 let excess_address_data = if addr_readpos < addrlen {
1284 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1285 r.read_exact(&mut excess_address_data[excess..])?;
1287 excess_address_data[0] = f;
1292 excess_data.push(f);
1297 Ok(UnsignedNodeAnnouncement {
1299 timestamp: timestamp,
1303 addresses: addresses,
1304 excess_address_data: excess_address_data,
1306 r.read_to_end(&mut excess_data)?;
1313 impl_writeable_len_match!(NodeAnnouncement, {
1314 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1315 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1325 use util::ser::Writeable;
1326 use secp256k1::key::{PublicKey,SecretKey};
1327 use secp256k1::Secp256k1;
1330 fn encoding_channel_reestablish_no_secret() {
1331 let cr = msgs::ChannelReestablish {
1332 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],
1333 next_local_commitment_number: 3,
1334 next_remote_commitment_number: 4,
1335 data_loss_protect: None,
1338 let encoded_value = cr.encode();
1341 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]
1346 fn encoding_channel_reestablish_with_secret() {
1348 let secp_ctx = Secp256k1::new();
1349 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1352 let cr = msgs::ChannelReestablish {
1353 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],
1354 next_local_commitment_number: 3,
1355 next_remote_commitment_number: 4,
1356 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1359 let encoded_value = cr.encode();
1362 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]