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
171 pub struct OpenChannel {
172 pub(crate) chain_hash: Sha256dHash,
173 pub(crate) temporary_channel_id: [u8; 32],
174 pub(crate) funding_satoshis: u64,
175 pub(crate) push_msat: u64,
176 pub(crate) dust_limit_satoshis: u64,
177 pub(crate) max_htlc_value_in_flight_msat: u64,
178 pub(crate) channel_reserve_satoshis: u64,
179 pub(crate) htlc_minimum_msat: u64,
180 pub(crate) feerate_per_kw: u32,
181 pub(crate) to_self_delay: u16,
182 pub(crate) max_accepted_htlcs: u16,
183 pub(crate) funding_pubkey: PublicKey,
184 pub(crate) revocation_basepoint: PublicKey,
185 pub(crate) payment_basepoint: PublicKey,
186 pub(crate) delayed_payment_basepoint: PublicKey,
187 pub(crate) htlc_basepoint: PublicKey,
188 pub(crate) first_per_commitment_point: PublicKey,
189 pub(crate) channel_flags: u8,
190 pub(crate) shutdown_scriptpubkey: Option<Script>,
193 /// An accept_channel message to be sent or received from a peer
194 pub struct AcceptChannel {
195 pub(crate) temporary_channel_id: [u8; 32],
196 pub(crate) dust_limit_satoshis: u64,
197 pub(crate) max_htlc_value_in_flight_msat: u64,
198 pub(crate) channel_reserve_satoshis: u64,
199 pub(crate) htlc_minimum_msat: u64,
200 pub(crate) minimum_depth: u32,
201 pub(crate) to_self_delay: u16,
202 pub(crate) max_accepted_htlcs: u16,
203 pub(crate) funding_pubkey: PublicKey,
204 pub(crate) revocation_basepoint: PublicKey,
205 pub(crate) payment_basepoint: PublicKey,
206 pub(crate) delayed_payment_basepoint: PublicKey,
207 pub(crate) htlc_basepoint: PublicKey,
208 pub(crate) first_per_commitment_point: PublicKey,
209 pub(crate) shutdown_scriptpubkey: Option<Script>,
212 /// A funding_created message to be sent or received from a peer
213 pub struct FundingCreated {
214 pub(crate) temporary_channel_id: [u8; 32],
215 pub(crate) funding_txid: Sha256dHash,
216 pub(crate) funding_output_index: u16,
217 pub(crate) signature: Signature,
220 /// A funding_signed message to be sent or received from a peer
221 pub struct FundingSigned {
222 pub(crate) channel_id: [u8; 32],
223 pub(crate) signature: Signature,
226 /// A funding_locked message to be sent or received from a peer
227 #[derive(Clone, PartialEq)]
228 pub struct FundingLocked {
229 pub(crate) channel_id: [u8; 32],
230 pub(crate) next_per_commitment_point: PublicKey,
233 /// A shutdown message to be sent or received from a peer
234 pub struct Shutdown {
235 pub(crate) channel_id: [u8; 32],
236 pub(crate) scriptpubkey: Script,
239 /// A closing_signed message to be sent or received from a peer
240 pub struct ClosingSigned {
241 pub(crate) channel_id: [u8; 32],
242 pub(crate) fee_satoshis: u64,
243 pub(crate) signature: Signature,
246 /// An update_add_htlc message to be sent or received from a peer
247 #[derive(Clone, PartialEq)]
248 pub struct UpdateAddHTLC {
249 pub(crate) channel_id: [u8; 32],
250 pub(crate) htlc_id: u64,
251 pub(crate) amount_msat: u64,
252 pub(crate) payment_hash: [u8; 32],
253 pub(crate) cltv_expiry: u32,
254 pub(crate) onion_routing_packet: OnionPacket,
257 /// An update_fulfill_htlc message to be sent or received from a peer
258 #[derive(Clone, PartialEq)]
259 pub struct UpdateFulfillHTLC {
260 pub(crate) channel_id: [u8; 32],
261 pub(crate) htlc_id: u64,
262 pub(crate) payment_preimage: [u8; 32],
265 /// An update_fail_htlc message to be sent or received from a peer
266 #[derive(Clone, PartialEq)]
267 pub struct UpdateFailHTLC {
268 pub(crate) channel_id: [u8; 32],
269 pub(crate) htlc_id: u64,
270 pub(crate) reason: OnionErrorPacket,
273 /// An update_fail_malformed_htlc message to be sent or received from a peer
274 #[derive(Clone, PartialEq)]
275 pub struct UpdateFailMalformedHTLC {
276 pub(crate) channel_id: [u8; 32],
277 pub(crate) htlc_id: u64,
278 pub(crate) sha256_of_onion: [u8; 32],
279 pub(crate) failure_code: u16,
282 /// A commitment_signed message to be sent or received from a peer
283 #[derive(Clone, PartialEq)]
284 pub struct CommitmentSigned {
285 pub(crate) channel_id: [u8; 32],
286 pub(crate) signature: Signature,
287 pub(crate) htlc_signatures: Vec<Signature>,
290 /// A revoke_and_ack message to be sent or received from a peer
291 #[derive(Clone, PartialEq)]
292 pub struct RevokeAndACK {
293 pub(crate) channel_id: [u8; 32],
294 pub(crate) per_commitment_secret: [u8; 32],
295 pub(crate) next_per_commitment_point: PublicKey,
298 /// An update_fee message to be sent or received from a peer
300 pub struct UpdateFee {
301 pub(crate) channel_id: [u8; 32],
302 pub(crate) feerate_per_kw: u32,
306 pub(crate) struct DataLossProtect {
307 pub(crate) your_last_per_commitment_secret: [u8; 32],
308 pub(crate) my_current_per_commitment_point: PublicKey,
311 /// A channel_reestablish message to be sent or received from a peer
313 pub struct ChannelReestablish {
314 pub(crate) channel_id: [u8; 32],
315 pub(crate) next_local_commitment_number: u64,
316 pub(crate) next_remote_commitment_number: u64,
317 pub(crate) data_loss_protect: Option<DataLossProtect>,
320 /// An announcement_signatures message to be sent or received from a peer
322 pub struct AnnouncementSignatures {
323 pub(crate) channel_id: [u8; 32],
324 pub(crate) short_channel_id: u64,
325 pub(crate) node_signature: Signature,
326 pub(crate) bitcoin_signature: Signature,
329 /// An address which can be used to connect to a remote peer
331 pub enum NetAddress {
332 /// An IPv4 address/port on which the peer is listenting.
334 /// The 4-byte IPv4 address
336 /// The port on which the node is listenting
339 /// An IPv6 address/port on which the peer is listenting.
341 /// The 16-byte IPv6 address
343 /// The port on which the node is listenting
346 /// An old-style Tor onion address/port on which the peer is listening.
348 /// The bytes (usually encoded in base32 with ".onion" appended)
350 /// The port on which the node is listenting
353 /// A new-style Tor onion address/port on which the peer is listening.
354 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
355 /// wrap as base32 and append ".onion".
357 /// The ed25519 long-term public key of the peer
358 ed25519_pubkey: [u8; 32],
359 /// The checksum of the pubkey and version, as included in the onion address
361 /// The version byte, as defined by the Tor Onion v3 spec.
363 /// The port on which the node is listenting
368 fn get_id(&self) -> u8 {
370 &NetAddress::IPv4 {..} => { 1 },
371 &NetAddress::IPv6 {..} => { 2 },
372 &NetAddress::OnionV2 {..} => { 3 },
373 &NetAddress::OnionV3 {..} => { 4 },
378 // Only exposed as broadcast of node_announcement should be filtered by node_id
379 /// The unsigned part of a node_announcement
380 pub struct UnsignedNodeAnnouncement {
381 pub(crate) features: GlobalFeatures,
382 pub(crate) timestamp: u32,
383 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
385 pub node_id: PublicKey,
386 pub(crate) rgb: [u8; 3],
387 pub(crate) alias: [u8; 32],
388 /// List of addresses on which this node is reachable. Note that you may only have up to one
389 /// address of each type, if you have more, they may be silently discarded or we may panic!
390 pub(crate) addresses: Vec<NetAddress>,
391 pub(crate) excess_address_data: Vec<u8>,
392 pub(crate) excess_data: Vec<u8>,
394 /// A node_announcement message to be sent or received from a peer
395 pub struct NodeAnnouncement {
396 pub(crate) signature: Signature,
397 pub(crate) contents: UnsignedNodeAnnouncement,
400 // Only exposed as broadcast of channel_announcement should be filtered by node_id
401 /// The unsigned part of a channel_announcement
402 #[derive(PartialEq, Clone)]
403 pub struct UnsignedChannelAnnouncement {
404 pub(crate) features: GlobalFeatures,
405 pub(crate) chain_hash: Sha256dHash,
406 pub(crate) short_channel_id: u64,
407 /// One of the two node_ids which are endpoints of this channel
408 pub node_id_1: PublicKey,
409 /// The other of the two node_ids which are endpoints of this channel
410 pub node_id_2: PublicKey,
411 pub(crate) bitcoin_key_1: PublicKey,
412 pub(crate) bitcoin_key_2: PublicKey,
413 pub(crate) excess_data: Vec<u8>,
415 /// A channel_announcement message to be sent or received from a peer
416 #[derive(PartialEq, Clone)]
417 pub struct ChannelAnnouncement {
418 pub(crate) node_signature_1: Signature,
419 pub(crate) node_signature_2: Signature,
420 pub(crate) bitcoin_signature_1: Signature,
421 pub(crate) bitcoin_signature_2: Signature,
422 pub(crate) contents: UnsignedChannelAnnouncement,
425 #[derive(PartialEq, Clone)]
426 pub(crate) struct UnsignedChannelUpdate {
427 pub(crate) chain_hash: Sha256dHash,
428 pub(crate) short_channel_id: u64,
429 pub(crate) timestamp: u32,
430 pub(crate) flags: u16,
431 pub(crate) cltv_expiry_delta: u16,
432 pub(crate) htlc_minimum_msat: u64,
433 pub(crate) fee_base_msat: u32,
434 pub(crate) fee_proportional_millionths: u32,
435 pub(crate) excess_data: Vec<u8>,
437 /// A channel_update message to be sent or received from a peer
438 #[derive(PartialEq, Clone)]
439 pub struct ChannelUpdate {
440 pub(crate) signature: Signature,
441 pub(crate) contents: UnsignedChannelUpdate,
444 /// Used to put an error message in a HandleError
445 pub enum ErrorAction {
446 /// The peer took some action which made us think they were useless. Disconnect them.
448 /// An error message which we should make an effort to send before we disconnect.
449 msg: Option<ErrorMessage>
451 /// The peer did something harmless that we weren't able to process, just log and ignore
453 /// The peer did something incorrect. Tell them.
455 /// The message to send.
460 /// An Err type for failure to process messages.
461 pub struct HandleError { //TODO: rename me
462 /// A human-readable message describing the error
463 pub err: &'static str,
464 /// The action which should be taken against the offending peer.
465 pub action: Option<ErrorAction>, //TODO: Make this required
468 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
469 /// transaction updates if they were pending.
471 pub struct CommitmentUpdate {
472 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
473 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
474 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
475 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
476 pub(crate) update_fee: Option<UpdateFee>,
477 pub(crate) commitment_signed: CommitmentSigned,
480 /// The information we received from a peer along the route of a payment we originated. This is
481 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
482 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
483 pub enum HTLCFailChannelUpdate {
484 /// We received an error which included a full ChannelUpdate message.
485 ChannelUpdateMessage {
486 /// The unwrapped message we received
489 /// We received an error which indicated only that a channel has been closed
491 /// The short_channel_id which has now closed.
492 short_channel_id: u64,
493 /// when this true, this channel should be permanently removed from the
494 /// consideration. Otherwise, this channel can be restored as new channel_update is received
497 /// We received an error which indicated only that a node has failed
499 /// The node_id that has failed.
501 /// when this true, node should be permanently removed from the
502 /// consideration. Otherwise, the channels connected to this node can be
503 /// restored as new channel_update is received
508 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
509 /// be sent in the order they appear in the return value, however sometimes the order needs to be
510 /// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
511 /// were originally sent). In those cases, this enum is also returned.
512 #[derive(Clone, PartialEq)]
513 pub enum RAACommitmentOrder {
514 /// Send the CommitmentUpdate messages first
516 /// Send the RevokeAndACK message first
520 /// A trait to describe an object which can receive channel messages.
522 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
523 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
524 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
526 /// Handle an incoming open_channel message from the given peer.
527 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
528 /// Handle an incoming accept_channel message from the given peer.
529 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
530 /// Handle an incoming funding_created message from the given peer.
531 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
532 /// Handle an incoming funding_signed message from the given peer.
533 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
534 /// Handle an incoming funding_locked message from the given peer.
535 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
538 /// Handle an incoming shutdown message from the given peer.
539 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
540 /// Handle an incoming closing_signed message from the given peer.
541 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
544 /// Handle an incoming update_add_htlc message from the given peer.
545 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
546 /// Handle an incoming update_fulfill_htlc message from the given peer.
547 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
548 /// Handle an incoming update_fail_htlc message from the given peer.
549 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
550 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
551 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
552 /// Handle an incoming commitment_signed message from the given peer.
553 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
554 /// Handle an incoming revoke_and_ack message from the given peer.
555 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
557 /// Handle an incoming update_fee message from the given peer.
558 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
560 // Channel-to-announce:
561 /// Handle an incoming announcement_signatures message from the given peer.
562 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
564 // Connection loss/reestablish:
565 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
566 /// is believed to be possible in the future (eg they're sending us messages we don't
567 /// understand or indicate they require unknown feature bits), no_connection_possible is set
568 /// and any outstanding channels should be failed.
569 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
571 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
572 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
573 /// Handle an incoming channel_reestablish message from the given peer.
574 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;
577 /// Handle an incoming error message from the given peer.
578 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
581 /// A trait to describe an object which can receive routing messages.
582 pub trait RoutingMessageHandler : Send + Sync {
583 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
584 /// false or returning an Err otherwise.
585 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
586 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
587 /// or returning an Err otherwise.
588 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
589 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
590 /// false or returning an Err otherwise.
591 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
592 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
593 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
596 pub(crate) struct OnionRealm0HopData {
597 pub(crate) short_channel_id: u64,
598 pub(crate) amt_to_forward: u64,
599 pub(crate) outgoing_cltv_value: u32,
600 // 12 bytes of 0-padding
603 mod fuzzy_internal_msgs {
604 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
605 // them from untrusted input):
607 use super::OnionRealm0HopData;
608 pub struct OnionHopData {
609 pub(crate) realm: u8,
610 pub(crate) data: OnionRealm0HopData,
611 pub(crate) hmac: [u8; 32],
613 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
615 pub struct DecodedOnionErrorPacket {
616 pub(crate) hmac: [u8; 32],
617 pub(crate) failuremsg: Vec<u8>,
618 pub(crate) pad: Vec<u8>,
621 #[cfg(feature = "fuzztarget")]
622 pub use self::fuzzy_internal_msgs::*;
623 #[cfg(not(feature = "fuzztarget"))]
624 pub(crate) use self::fuzzy_internal_msgs::*;
627 pub(crate) struct OnionPacket {
628 pub(crate) version: u8,
629 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
630 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
631 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
632 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
633 pub(crate) hop_data: [u8; 20*65],
634 pub(crate) hmac: [u8; 32],
637 impl PartialEq for OnionPacket {
638 fn eq(&self, other: &OnionPacket) -> bool {
639 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
640 if i != j { return false; }
642 self.version == other.version &&
643 self.public_key == other.public_key &&
644 self.hmac == other.hmac
648 #[derive(Clone, PartialEq)]
649 pub(crate) struct OnionErrorPacket {
650 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
651 // (TODO) We limit it in decode to much lower...
652 pub(crate) data: Vec<u8>,
655 impl Error for DecodeError {
656 fn description(&self) -> &str {
658 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
659 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
660 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
661 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
662 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
663 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
664 DecodeError::Io(ref e) => e.description(),
668 impl fmt::Display for DecodeError {
669 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
670 f.write_str(self.description())
674 impl fmt::Debug for HandleError {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
676 f.write_str(self.err)
680 impl From<::std::io::Error> for DecodeError {
681 fn from(e: ::std::io::Error) -> Self {
682 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
683 DecodeError::ShortRead
690 impl_writeable_len_match!(AcceptChannel, {
691 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
694 temporary_channel_id,
696 max_htlc_value_in_flight_msat,
697 channel_reserve_satoshis,
703 revocation_basepoint,
705 delayed_payment_basepoint,
707 first_per_commitment_point,
708 shutdown_scriptpubkey
711 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
718 impl Writeable for ChannelReestablish {
719 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
720 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
721 self.channel_id.write(w)?;
722 self.next_local_commitment_number.write(w)?;
723 self.next_remote_commitment_number.write(w)?;
724 if let Some(ref data_loss_protect) = self.data_loss_protect {
725 data_loss_protect.your_last_per_commitment_secret.write(w)?;
726 data_loss_protect.my_current_per_commitment_point.write(w)?;
732 impl<R: Read> Readable<R> for ChannelReestablish{
733 fn read(r: &mut R) -> Result<Self, DecodeError> {
735 channel_id: Readable::read(r)?,
736 next_local_commitment_number: Readable::read(r)?,
737 next_remote_commitment_number: Readable::read(r)?,
739 match <[u8; 32] as Readable<R>>::read(r) {
740 Ok(your_last_per_commitment_secret) =>
741 Some(DataLossProtect {
742 your_last_per_commitment_secret,
743 my_current_per_commitment_point: Readable::read(r)?,
745 Err(DecodeError::ShortRead) => None,
746 Err(e) => return Err(e)
753 impl_writeable!(ClosingSigned, 32+8+64, {
759 impl_writeable_len_match!(CommitmentSigned, {
760 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
767 impl_writeable_len_match!(DecodedOnionErrorPacket, {
768 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
775 impl_writeable!(FundingCreated, 32+32+2+64, {
776 temporary_channel_id,
778 funding_output_index,
782 impl_writeable!(FundingSigned, 32+64, {
787 impl_writeable!(FundingLocked, 32+33, {
789 next_per_commitment_point
792 impl_writeable_len_match!(GlobalFeatures, {
793 { GlobalFeatures { ref flags }, flags.len() + 2 }
798 impl_writeable_len_match!(LocalFeatures, {
799 { LocalFeatures { ref flags }, flags.len() + 2 }
804 impl_writeable_len_match!(Init, {
805 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
811 impl_writeable_len_match!(OpenChannel, {
812 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
813 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
816 temporary_channel_id,
820 max_htlc_value_in_flight_msat,
821 channel_reserve_satoshis,
827 revocation_basepoint,
829 delayed_payment_basepoint,
831 first_per_commitment_point,
833 shutdown_scriptpubkey
836 impl_writeable!(RevokeAndACK, 32+32+33, {
838 per_commitment_secret,
839 next_per_commitment_point
842 impl_writeable_len_match!(Shutdown, {
843 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
849 impl_writeable_len_match!(UpdateFailHTLC, {
850 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
857 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
864 impl_writeable!(UpdateFee, 32+4, {
869 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
875 impl_writeable_len_match!(OnionErrorPacket, {
876 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
881 impl Writeable for OnionPacket {
882 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
883 w.size_hint(1 + 33 + 20*65 + 32);
884 self.version.write(w)?;
885 match self.public_key {
886 Ok(pubkey) => pubkey.write(w)?,
887 Err(_) => [0u8;33].write(w)?,
889 w.write_all(&self.hop_data)?;
895 impl<R: Read> Readable<R> for OnionPacket {
896 fn read(r: &mut R) -> Result<Self, DecodeError> {
898 version: Readable::read(r)?,
900 let mut buf = [0u8;33];
901 r.read_exact(&mut buf)?;
902 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
904 hop_data: Readable::read(r)?,
905 hmac: Readable::read(r)?,
910 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
919 impl Writeable for OnionRealm0HopData {
920 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
922 self.short_channel_id.write(w)?;
923 self.amt_to_forward.write(w)?;
924 self.outgoing_cltv_value.write(w)?;
925 w.write_all(&[0;12])?;
930 impl<R: Read> Readable<R> for OnionRealm0HopData {
931 fn read(r: &mut R) -> Result<Self, DecodeError> {
932 Ok(OnionRealm0HopData {
933 short_channel_id: Readable::read(r)?,
934 amt_to_forward: Readable::read(r)?,
935 outgoing_cltv_value: {
936 let v: u32 = Readable::read(r)?;
937 r.read_exact(&mut [0; 12])?;
944 impl Writeable for OnionHopData {
945 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
947 self.realm.write(w)?;
954 impl<R: Read> Readable<R> for OnionHopData {
955 fn read(r: &mut R) -> Result<Self, DecodeError> {
958 let r: u8 = Readable::read(r)?;
960 return Err(DecodeError::UnknownVersion);
964 data: Readable::read(r)?,
965 hmac: Readable::read(r)?,
970 impl Writeable for Ping {
971 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
972 w.size_hint(self.byteslen as usize + 4);
973 self.ponglen.write(w)?;
974 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
979 impl<R: Read> Readable<R> for Ping {
980 fn read(r: &mut R) -> Result<Self, DecodeError> {
982 ponglen: Readable::read(r)?,
984 let byteslen = Readable::read(r)?;
985 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
992 impl Writeable for Pong {
993 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
994 w.size_hint(self.byteslen as usize + 2);
995 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1000 impl<R: Read> Readable<R> for Pong {
1001 fn read(r: &mut R) -> Result<Self, DecodeError> {
1004 let byteslen = Readable::read(r)?;
1005 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1012 impl Writeable for UnsignedChannelAnnouncement {
1013 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1014 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1015 self.features.write(w)?;
1016 self.chain_hash.write(w)?;
1017 self.short_channel_id.write(w)?;
1018 self.node_id_1.write(w)?;
1019 self.node_id_2.write(w)?;
1020 self.bitcoin_key_1.write(w)?;
1021 self.bitcoin_key_2.write(w)?;
1022 w.write_all(&self.excess_data[..])?;
1027 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1028 fn read(r: &mut R) -> Result<Self, DecodeError> {
1031 let f: GlobalFeatures = Readable::read(r)?;
1032 if f.requires_unknown_bits() {
1033 return Err(DecodeError::UnknownRequiredFeature);
1037 chain_hash: Readable::read(r)?,
1038 short_channel_id: Readable::read(r)?,
1039 node_id_1: Readable::read(r)?,
1040 node_id_2: Readable::read(r)?,
1041 bitcoin_key_1: Readable::read(r)?,
1042 bitcoin_key_2: Readable::read(r)?,
1044 let mut excess_data = vec![];
1045 r.read_to_end(&mut excess_data)?;
1052 impl_writeable_len_match!(ChannelAnnouncement, {
1053 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1054 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1058 bitcoin_signature_1,
1059 bitcoin_signature_2,
1063 impl Writeable for UnsignedChannelUpdate {
1064 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1065 w.size_hint(64 + self.excess_data.len());
1066 self.chain_hash.write(w)?;
1067 self.short_channel_id.write(w)?;
1068 self.timestamp.write(w)?;
1069 self.flags.write(w)?;
1070 self.cltv_expiry_delta.write(w)?;
1071 self.htlc_minimum_msat.write(w)?;
1072 self.fee_base_msat.write(w)?;
1073 self.fee_proportional_millionths.write(w)?;
1074 w.write_all(&self.excess_data[..])?;
1079 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1080 fn read(r: &mut R) -> Result<Self, DecodeError> {
1082 chain_hash: Readable::read(r)?,
1083 short_channel_id: Readable::read(r)?,
1084 timestamp: Readable::read(r)?,
1085 flags: Readable::read(r)?,
1086 cltv_expiry_delta: Readable::read(r)?,
1087 htlc_minimum_msat: Readable::read(r)?,
1088 fee_base_msat: Readable::read(r)?,
1089 fee_proportional_millionths: Readable::read(r)?,
1091 let mut excess_data = vec![];
1092 r.read_to_end(&mut excess_data)?;
1099 impl_writeable_len_match!(ChannelUpdate, {
1100 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1101 64 + excess_data.len() + 64 }
1107 impl Writeable for ErrorMessage {
1108 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1109 w.size_hint(32 + 2 + self.data.len());
1110 self.channel_id.write(w)?;
1111 (self.data.len() as u16).write(w)?;
1112 w.write_all(self.data.as_bytes())?;
1117 impl<R: Read> Readable<R> for ErrorMessage {
1118 fn read(r: &mut R) -> Result<Self, DecodeError> {
1120 channel_id: Readable::read(r)?,
1122 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1123 let mut data = vec![];
1124 let data_len = r.read_to_end(&mut data)?;
1125 sz = cmp::min(data_len, sz);
1126 match String::from_utf8(data[..sz as usize].to_vec()) {
1128 Err(_) => return Err(DecodeError::InvalidValue),
1135 impl Writeable for UnsignedNodeAnnouncement {
1136 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1137 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1138 self.features.write(w)?;
1139 self.timestamp.write(w)?;
1140 self.node_id.write(w)?;
1141 w.write_all(&self.rgb)?;
1142 self.alias.write(w)?;
1144 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1145 let mut addrs_to_encode = self.addresses.clone();
1146 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1147 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1148 for addr in addrs_to_encode.iter() {
1150 &NetAddress::IPv4{addr, port} => {
1152 addr_slice.extend_from_slice(&addr);
1153 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1155 &NetAddress::IPv6{addr, port} => {
1157 addr_slice.extend_from_slice(&addr);
1158 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1160 &NetAddress::OnionV2{addr, port} => {
1162 addr_slice.extend_from_slice(&addr);
1163 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1165 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1167 addr_slice.extend_from_slice(&ed25519_pubkey);
1168 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1169 addr_slice.push(version);
1170 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1174 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1175 w.write_all(&addr_slice[..])?;
1176 w.write_all(&self.excess_address_data[..])?;
1177 w.write_all(&self.excess_data[..])?;
1182 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1183 fn read(r: &mut R) -> Result<Self, DecodeError> {
1184 let features: GlobalFeatures = Readable::read(r)?;
1185 if features.requires_unknown_bits() {
1186 return Err(DecodeError::UnknownRequiredFeature);
1188 let timestamp: u32 = Readable::read(r)?;
1189 let node_id: PublicKey = Readable::read(r)?;
1190 let mut rgb = [0; 3];
1191 r.read_exact(&mut rgb)?;
1192 let alias: [u8; 32] = Readable::read(r)?;
1194 let addrlen: u16 = Readable::read(r)?;
1195 let mut addr_readpos = 0;
1196 let mut addresses = Vec::with_capacity(4);
1200 if addrlen <= addr_readpos { break; }
1201 f = Readable::read(r)?;
1204 if addresses.len() > 0 {
1205 return Err(DecodeError::ExtraAddressesPerType);
1207 if addrlen < addr_readpos + 1 + 6 {
1208 return Err(DecodeError::BadLengthDescriptor);
1210 addresses.push(NetAddress::IPv4 {
1212 let mut addr = [0; 4];
1213 r.read_exact(&mut addr)?;
1216 port: Readable::read(r)?,
1218 addr_readpos += 1 + 6
1221 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1222 return Err(DecodeError::ExtraAddressesPerType);
1224 if addrlen < addr_readpos + 1 + 18 {
1225 return Err(DecodeError::BadLengthDescriptor);
1227 addresses.push(NetAddress::IPv6 {
1229 let mut addr = [0; 16];
1230 r.read_exact(&mut addr)?;
1233 port: Readable::read(r)?,
1235 addr_readpos += 1 + 18
1238 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1239 return Err(DecodeError::ExtraAddressesPerType);
1241 if addrlen < addr_readpos + 1 + 12 {
1242 return Err(DecodeError::BadLengthDescriptor);
1244 addresses.push(NetAddress::OnionV2 {
1246 let mut addr = [0; 10];
1247 r.read_exact(&mut addr)?;
1250 port: Readable::read(r)?,
1252 addr_readpos += 1 + 12
1255 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1256 return Err(DecodeError::ExtraAddressesPerType);
1258 if addrlen < addr_readpos + 1 + 37 {
1259 return Err(DecodeError::BadLengthDescriptor);
1261 addresses.push(NetAddress::OnionV3 {
1262 ed25519_pubkey: Readable::read(r)?,
1263 checksum: Readable::read(r)?,
1264 version: Readable::read(r)?,
1265 port: Readable::read(r)?,
1267 addr_readpos += 1 + 37
1269 _ => { excess = 1; break; }
1273 let mut excess_data = vec![];
1274 let excess_address_data = if addr_readpos < addrlen {
1275 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1276 r.read_exact(&mut excess_address_data[excess..])?;
1278 excess_address_data[0] = f;
1283 excess_data.push(f);
1288 Ok(UnsignedNodeAnnouncement {
1290 timestamp: timestamp,
1294 addresses: addresses,
1295 excess_address_data: excess_address_data,
1297 r.read_to_end(&mut excess_data)?;
1304 impl_writeable_len_match!(NodeAnnouncement, {
1305 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1306 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1316 use util::ser::Writeable;
1317 use secp256k1::key::{PublicKey,SecretKey};
1318 use secp256k1::Secp256k1;
1321 fn encoding_channel_reestablish_no_secret() {
1322 let cr = msgs::ChannelReestablish {
1323 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],
1324 next_local_commitment_number: 3,
1325 next_remote_commitment_number: 4,
1326 data_loss_protect: None,
1329 let encoded_value = cr.encode();
1332 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]
1337 fn encoding_channel_reestablish_with_secret() {
1339 let secp_ctx = Secp256k1::new();
1340 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1343 let cr = msgs::ChannelReestablish {
1344 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],
1345 next_local_commitment_number: 3,
1346 next_remote_commitment_number: 4,
1347 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1350 let encoded_value = cr.encode();
1353 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]