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
215 pub struct FundingCreated {
216 pub(crate) temporary_channel_id: [u8; 32],
217 pub(crate) funding_txid: Sha256dHash,
218 pub(crate) funding_output_index: u16,
219 pub(crate) signature: Signature,
222 /// A funding_signed message to be sent or received from a peer
223 pub struct FundingSigned {
224 pub(crate) channel_id: [u8; 32],
225 pub(crate) signature: Signature,
228 /// A funding_locked message to be sent or received from a peer
229 #[derive(Clone, PartialEq)]
230 pub struct FundingLocked {
231 pub(crate) channel_id: [u8; 32],
232 pub(crate) next_per_commitment_point: PublicKey,
235 /// A shutdown message to be sent or received from a peer
236 pub struct Shutdown {
237 pub(crate) channel_id: [u8; 32],
238 pub(crate) scriptpubkey: Script,
241 /// A closing_signed message to be sent or received from a peer
242 pub struct ClosingSigned {
243 pub(crate) channel_id: [u8; 32],
244 pub(crate) fee_satoshis: u64,
245 pub(crate) signature: Signature,
248 /// An update_add_htlc message to be sent or received from a peer
249 #[derive(Clone, PartialEq)]
250 pub struct UpdateAddHTLC {
251 pub(crate) channel_id: [u8; 32],
252 pub(crate) htlc_id: u64,
253 pub(crate) amount_msat: u64,
254 pub(crate) payment_hash: [u8; 32],
255 pub(crate) cltv_expiry: u32,
256 pub(crate) onion_routing_packet: OnionPacket,
259 /// An update_fulfill_htlc message to be sent or received from a peer
260 #[derive(Clone, PartialEq)]
261 pub struct UpdateFulfillHTLC {
262 pub(crate) channel_id: [u8; 32],
263 pub(crate) htlc_id: u64,
264 pub(crate) payment_preimage: [u8; 32],
267 /// An update_fail_htlc message to be sent or received from a peer
268 #[derive(Clone, PartialEq)]
269 pub struct UpdateFailHTLC {
270 pub(crate) channel_id: [u8; 32],
271 pub(crate) htlc_id: u64,
272 pub(crate) reason: OnionErrorPacket,
275 /// An update_fail_malformed_htlc message to be sent or received from a peer
276 #[derive(Clone, PartialEq)]
277 pub struct UpdateFailMalformedHTLC {
278 pub(crate) channel_id: [u8; 32],
279 pub(crate) htlc_id: u64,
280 pub(crate) sha256_of_onion: [u8; 32],
281 pub(crate) failure_code: u16,
284 /// A commitment_signed message to be sent or received from a peer
285 #[derive(Clone, PartialEq)]
286 pub struct CommitmentSigned {
287 pub(crate) channel_id: [u8; 32],
288 pub(crate) signature: Signature,
289 pub(crate) htlc_signatures: Vec<Signature>,
292 /// A revoke_and_ack message to be sent or received from a peer
293 #[derive(Clone, PartialEq)]
294 pub struct RevokeAndACK {
295 pub(crate) channel_id: [u8; 32],
296 pub(crate) per_commitment_secret: [u8; 32],
297 pub(crate) next_per_commitment_point: PublicKey,
300 /// An update_fee message to be sent or received from a peer
302 pub struct UpdateFee {
303 pub(crate) channel_id: [u8; 32],
304 pub(crate) feerate_per_kw: u32,
308 pub(crate) struct DataLossProtect {
309 pub(crate) your_last_per_commitment_secret: [u8; 32],
310 pub(crate) my_current_per_commitment_point: PublicKey,
313 /// A channel_reestablish message to be sent or received from a peer
315 pub struct ChannelReestablish {
316 pub(crate) channel_id: [u8; 32],
317 pub(crate) next_local_commitment_number: u64,
318 pub(crate) next_remote_commitment_number: u64,
319 pub(crate) data_loss_protect: Option<DataLossProtect>,
322 /// An announcement_signatures message to be sent or received from a peer
324 pub struct AnnouncementSignatures {
325 pub(crate) channel_id: [u8; 32],
326 pub(crate) short_channel_id: u64,
327 pub(crate) node_signature: Signature,
328 pub(crate) bitcoin_signature: Signature,
331 /// An address which can be used to connect to a remote peer
333 pub enum NetAddress {
334 /// An IPv4 address/port on which the peer is listenting.
336 /// The 4-byte IPv4 address
338 /// The port on which the node is listenting
341 /// An IPv6 address/port on which the peer is listenting.
343 /// The 16-byte IPv6 address
345 /// The port on which the node is listenting
348 /// An old-style Tor onion address/port on which the peer is listening.
350 /// The bytes (usually encoded in base32 with ".onion" appended)
352 /// The port on which the node is listenting
355 /// A new-style Tor onion address/port on which the peer is listening.
356 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
357 /// wrap as base32 and append ".onion".
359 /// The ed25519 long-term public key of the peer
360 ed25519_pubkey: [u8; 32],
361 /// The checksum of the pubkey and version, as included in the onion address
363 /// The version byte, as defined by the Tor Onion v3 spec.
365 /// The port on which the node is listenting
370 fn get_id(&self) -> u8 {
372 &NetAddress::IPv4 {..} => { 1 },
373 &NetAddress::IPv6 {..} => { 2 },
374 &NetAddress::OnionV2 {..} => { 3 },
375 &NetAddress::OnionV3 {..} => { 4 },
380 // Only exposed as broadcast of node_announcement should be filtered by node_id
381 /// The unsigned part of a node_announcement
382 pub struct UnsignedNodeAnnouncement {
383 pub(crate) features: GlobalFeatures,
384 pub(crate) timestamp: u32,
385 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
387 pub node_id: PublicKey,
388 pub(crate) rgb: [u8; 3],
389 pub(crate) alias: [u8; 32],
390 /// List of addresses on which this node is reachable. Note that you may only have up to one
391 /// address of each type, if you have more, they may be silently discarded or we may panic!
392 pub(crate) addresses: Vec<NetAddress>,
393 pub(crate) excess_address_data: Vec<u8>,
394 pub(crate) excess_data: Vec<u8>,
396 /// A node_announcement message to be sent or received from a peer
397 pub struct NodeAnnouncement {
398 pub(crate) signature: Signature,
399 pub(crate) contents: UnsignedNodeAnnouncement,
402 // Only exposed as broadcast of channel_announcement should be filtered by node_id
403 /// The unsigned part of a channel_announcement
404 #[derive(PartialEq, Clone)]
405 pub struct UnsignedChannelAnnouncement {
406 pub(crate) features: GlobalFeatures,
407 pub(crate) chain_hash: Sha256dHash,
408 pub(crate) short_channel_id: u64,
409 /// One of the two node_ids which are endpoints of this channel
410 pub node_id_1: PublicKey,
411 /// The other of the two node_ids which are endpoints of this channel
412 pub node_id_2: PublicKey,
413 pub(crate) bitcoin_key_1: PublicKey,
414 pub(crate) bitcoin_key_2: PublicKey,
415 pub(crate) excess_data: Vec<u8>,
417 /// A channel_announcement message to be sent or received from a peer
418 #[derive(PartialEq, Clone)]
419 pub struct ChannelAnnouncement {
420 pub(crate) node_signature_1: Signature,
421 pub(crate) node_signature_2: Signature,
422 pub(crate) bitcoin_signature_1: Signature,
423 pub(crate) bitcoin_signature_2: Signature,
424 pub(crate) contents: UnsignedChannelAnnouncement,
427 #[derive(PartialEq, Clone)]
428 pub(crate) struct UnsignedChannelUpdate {
429 pub(crate) chain_hash: Sha256dHash,
430 pub(crate) short_channel_id: u64,
431 pub(crate) timestamp: u32,
432 pub(crate) flags: u16,
433 pub(crate) cltv_expiry_delta: u16,
434 pub(crate) htlc_minimum_msat: u64,
435 pub(crate) fee_base_msat: u32,
436 pub(crate) fee_proportional_millionths: u32,
437 pub(crate) excess_data: Vec<u8>,
439 /// A channel_update message to be sent or received from a peer
440 #[derive(PartialEq, Clone)]
441 pub struct ChannelUpdate {
442 pub(crate) signature: Signature,
443 pub(crate) contents: UnsignedChannelUpdate,
446 /// Used to put an error message in a HandleError
447 pub enum ErrorAction {
448 /// The peer took some action which made us think they were useless. Disconnect them.
450 /// An error message which we should make an effort to send before we disconnect.
451 msg: Option<ErrorMessage>
453 /// The peer did something harmless that we weren't able to process, just log and ignore
455 /// The peer did something incorrect. Tell them.
457 /// The message to send.
462 /// An Err type for failure to process messages.
463 pub struct HandleError { //TODO: rename me
464 /// A human-readable message describing the error
465 pub err: &'static str,
466 /// The action which should be taken against the offending peer.
467 pub action: Option<ErrorAction>, //TODO: Make this required
470 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
471 /// transaction updates if they were pending.
473 pub struct CommitmentUpdate {
474 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
475 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
476 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
477 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
478 pub(crate) update_fee: Option<UpdateFee>,
479 pub(crate) commitment_signed: CommitmentSigned,
482 /// The information we received from a peer along the route of a payment we originated. This is
483 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
484 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
485 pub enum HTLCFailChannelUpdate {
486 /// We received an error which included a full ChannelUpdate message.
487 ChannelUpdateMessage {
488 /// The unwrapped message we received
491 /// We received an error which indicated only that a channel has been closed
493 /// The short_channel_id which has now closed.
494 short_channel_id: u64,
495 /// when this true, this channel should be permanently removed from the
496 /// consideration. Otherwise, this channel can be restored as new channel_update is received
499 /// We received an error which indicated only that a node has failed
501 /// The node_id that has failed.
503 /// when this true, node should be permanently removed from the
504 /// consideration. Otherwise, the channels connected to this node can be
505 /// restored as new channel_update is received
510 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
511 /// be sent in the order they appear in the return value, however sometimes the order needs to be
512 /// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
513 /// were originally sent). In those cases, this enum is also returned.
514 #[derive(Clone, PartialEq)]
515 pub enum RAACommitmentOrder {
516 /// Send the CommitmentUpdate messages first
518 /// Send the RevokeAndACK message first
522 /// A trait to describe an object which can receive channel messages.
524 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
525 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
526 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
528 /// Handle an incoming open_channel message from the given peer.
529 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
530 /// Handle an incoming accept_channel message from the given peer.
531 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
532 /// Handle an incoming funding_created message from the given peer.
533 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
534 /// Handle an incoming funding_signed message from the given peer.
535 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
536 /// Handle an incoming funding_locked message from the given peer.
537 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
540 /// Handle an incoming shutdown message from the given peer.
541 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
542 /// Handle an incoming closing_signed message from the given peer.
543 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
546 /// Handle an incoming update_add_htlc message from the given peer.
547 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
548 /// Handle an incoming update_fulfill_htlc message from the given peer.
549 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
550 /// Handle an incoming update_fail_htlc message from the given peer.
551 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
552 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
553 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
554 /// Handle an incoming commitment_signed message from the given peer.
555 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
556 /// Handle an incoming revoke_and_ack message from the given peer.
557 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
559 /// Handle an incoming update_fee message from the given peer.
560 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
562 // Channel-to-announce:
563 /// Handle an incoming announcement_signatures message from the given peer.
564 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
566 // Connection loss/reestablish:
567 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
568 /// is believed to be possible in the future (eg they're sending us messages we don't
569 /// understand or indicate they require unknown feature bits), no_connection_possible is set
570 /// and any outstanding channels should be failed.
571 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
573 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
574 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
575 /// Handle an incoming channel_reestablish message from the given peer.
576 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;
579 /// Handle an incoming error message from the given peer.
580 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
583 /// A trait to describe an object which can receive routing messages.
584 pub trait RoutingMessageHandler : Send + Sync {
585 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
586 /// false or returning an Err otherwise.
587 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
588 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
589 /// or returning an Err otherwise.
590 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
591 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
592 /// false or returning an Err otherwise.
593 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
594 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
595 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
598 pub(crate) struct OnionRealm0HopData {
599 pub(crate) short_channel_id: u64,
600 pub(crate) amt_to_forward: u64,
601 pub(crate) outgoing_cltv_value: u32,
602 // 12 bytes of 0-padding
605 mod fuzzy_internal_msgs {
606 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
607 // them from untrusted input):
609 use super::OnionRealm0HopData;
610 pub struct OnionHopData {
611 pub(crate) realm: u8,
612 pub(crate) data: OnionRealm0HopData,
613 pub(crate) hmac: [u8; 32],
615 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
617 pub struct DecodedOnionErrorPacket {
618 pub(crate) hmac: [u8; 32],
619 pub(crate) failuremsg: Vec<u8>,
620 pub(crate) pad: Vec<u8>,
623 #[cfg(feature = "fuzztarget")]
624 pub use self::fuzzy_internal_msgs::*;
625 #[cfg(not(feature = "fuzztarget"))]
626 pub(crate) use self::fuzzy_internal_msgs::*;
629 pub(crate) struct OnionPacket {
630 pub(crate) version: u8,
631 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
632 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
633 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
634 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
635 pub(crate) hop_data: [u8; 20*65],
636 pub(crate) hmac: [u8; 32],
639 impl PartialEq for OnionPacket {
640 fn eq(&self, other: &OnionPacket) -> bool {
641 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
642 if i != j { return false; }
644 self.version == other.version &&
645 self.public_key == other.public_key &&
646 self.hmac == other.hmac
650 #[derive(Clone, PartialEq)]
651 pub(crate) struct OnionErrorPacket {
652 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
653 // (TODO) We limit it in decode to much lower...
654 pub(crate) data: Vec<u8>,
657 impl Error for DecodeError {
658 fn description(&self) -> &str {
660 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
661 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
662 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
663 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
664 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
665 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
666 DecodeError::Io(ref e) => e.description(),
670 impl fmt::Display for DecodeError {
671 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
672 f.write_str(self.description())
676 impl fmt::Debug for HandleError {
677 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
678 f.write_str(self.err)
682 impl From<::std::io::Error> for DecodeError {
683 fn from(e: ::std::io::Error) -> Self {
684 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
685 DecodeError::ShortRead
692 impl_writeable_len_match!(AcceptChannel, {
693 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
696 temporary_channel_id,
698 max_htlc_value_in_flight_msat,
699 channel_reserve_satoshis,
705 revocation_basepoint,
707 delayed_payment_basepoint,
709 first_per_commitment_point,
710 shutdown_scriptpubkey
713 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
720 impl Writeable for ChannelReestablish {
721 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
722 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
723 self.channel_id.write(w)?;
724 self.next_local_commitment_number.write(w)?;
725 self.next_remote_commitment_number.write(w)?;
726 if let Some(ref data_loss_protect) = self.data_loss_protect {
727 data_loss_protect.your_last_per_commitment_secret.write(w)?;
728 data_loss_protect.my_current_per_commitment_point.write(w)?;
734 impl<R: Read> Readable<R> for ChannelReestablish{
735 fn read(r: &mut R) -> Result<Self, DecodeError> {
737 channel_id: Readable::read(r)?,
738 next_local_commitment_number: Readable::read(r)?,
739 next_remote_commitment_number: Readable::read(r)?,
741 match <[u8; 32] as Readable<R>>::read(r) {
742 Ok(your_last_per_commitment_secret) =>
743 Some(DataLossProtect {
744 your_last_per_commitment_secret,
745 my_current_per_commitment_point: Readable::read(r)?,
747 Err(DecodeError::ShortRead) => None,
748 Err(e) => return Err(e)
755 impl_writeable!(ClosingSigned, 32+8+64, {
761 impl_writeable_len_match!(CommitmentSigned, {
762 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
769 impl_writeable_len_match!(DecodedOnionErrorPacket, {
770 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
777 impl_writeable!(FundingCreated, 32+32+2+64, {
778 temporary_channel_id,
780 funding_output_index,
784 impl_writeable!(FundingSigned, 32+64, {
789 impl_writeable!(FundingLocked, 32+33, {
791 next_per_commitment_point
794 impl_writeable_len_match!(GlobalFeatures, {
795 { GlobalFeatures { ref flags }, flags.len() + 2 }
800 impl_writeable_len_match!(LocalFeatures, {
801 { LocalFeatures { ref flags }, flags.len() + 2 }
806 impl_writeable_len_match!(Init, {
807 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
813 impl_writeable_len_match!(OpenChannel, {
814 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
815 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
818 temporary_channel_id,
822 max_htlc_value_in_flight_msat,
823 channel_reserve_satoshis,
829 revocation_basepoint,
831 delayed_payment_basepoint,
833 first_per_commitment_point,
835 shutdown_scriptpubkey
838 impl_writeable!(RevokeAndACK, 32+32+33, {
840 per_commitment_secret,
841 next_per_commitment_point
844 impl_writeable_len_match!(Shutdown, {
845 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
851 impl_writeable_len_match!(UpdateFailHTLC, {
852 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
859 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
866 impl_writeable!(UpdateFee, 32+4, {
871 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
877 impl_writeable_len_match!(OnionErrorPacket, {
878 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
883 impl Writeable for OnionPacket {
884 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
885 w.size_hint(1 + 33 + 20*65 + 32);
886 self.version.write(w)?;
887 match self.public_key {
888 Ok(pubkey) => pubkey.write(w)?,
889 Err(_) => [0u8;33].write(w)?,
891 w.write_all(&self.hop_data)?;
897 impl<R: Read> Readable<R> for OnionPacket {
898 fn read(r: &mut R) -> Result<Self, DecodeError> {
900 version: Readable::read(r)?,
902 let mut buf = [0u8;33];
903 r.read_exact(&mut buf)?;
904 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
906 hop_data: Readable::read(r)?,
907 hmac: Readable::read(r)?,
912 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
921 impl Writeable for OnionRealm0HopData {
922 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
924 self.short_channel_id.write(w)?;
925 self.amt_to_forward.write(w)?;
926 self.outgoing_cltv_value.write(w)?;
927 w.write_all(&[0;12])?;
932 impl<R: Read> Readable<R> for OnionRealm0HopData {
933 fn read(r: &mut R) -> Result<Self, DecodeError> {
934 Ok(OnionRealm0HopData {
935 short_channel_id: Readable::read(r)?,
936 amt_to_forward: Readable::read(r)?,
937 outgoing_cltv_value: {
938 let v: u32 = Readable::read(r)?;
939 r.read_exact(&mut [0; 12])?;
946 impl Writeable for OnionHopData {
947 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
949 self.realm.write(w)?;
956 impl<R: Read> Readable<R> for OnionHopData {
957 fn read(r: &mut R) -> Result<Self, DecodeError> {
960 let r: u8 = Readable::read(r)?;
962 return Err(DecodeError::UnknownVersion);
966 data: Readable::read(r)?,
967 hmac: Readable::read(r)?,
972 impl Writeable for Ping {
973 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
974 w.size_hint(self.byteslen as usize + 4);
975 self.ponglen.write(w)?;
976 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
981 impl<R: Read> Readable<R> for Ping {
982 fn read(r: &mut R) -> Result<Self, DecodeError> {
984 ponglen: Readable::read(r)?,
986 let byteslen = Readable::read(r)?;
987 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
994 impl Writeable for Pong {
995 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
996 w.size_hint(self.byteslen as usize + 2);
997 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1002 impl<R: Read> Readable<R> for Pong {
1003 fn read(r: &mut R) -> Result<Self, DecodeError> {
1006 let byteslen = Readable::read(r)?;
1007 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1014 impl Writeable for UnsignedChannelAnnouncement {
1015 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1016 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1017 self.features.write(w)?;
1018 self.chain_hash.write(w)?;
1019 self.short_channel_id.write(w)?;
1020 self.node_id_1.write(w)?;
1021 self.node_id_2.write(w)?;
1022 self.bitcoin_key_1.write(w)?;
1023 self.bitcoin_key_2.write(w)?;
1024 w.write_all(&self.excess_data[..])?;
1029 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1030 fn read(r: &mut R) -> Result<Self, DecodeError> {
1033 let f: GlobalFeatures = Readable::read(r)?;
1034 if f.requires_unknown_bits() {
1035 return Err(DecodeError::UnknownRequiredFeature);
1039 chain_hash: Readable::read(r)?,
1040 short_channel_id: Readable::read(r)?,
1041 node_id_1: Readable::read(r)?,
1042 node_id_2: Readable::read(r)?,
1043 bitcoin_key_1: Readable::read(r)?,
1044 bitcoin_key_2: Readable::read(r)?,
1046 let mut excess_data = vec![];
1047 r.read_to_end(&mut excess_data)?;
1054 impl_writeable_len_match!(ChannelAnnouncement, {
1055 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1056 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1060 bitcoin_signature_1,
1061 bitcoin_signature_2,
1065 impl Writeable for UnsignedChannelUpdate {
1066 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1067 w.size_hint(64 + self.excess_data.len());
1068 self.chain_hash.write(w)?;
1069 self.short_channel_id.write(w)?;
1070 self.timestamp.write(w)?;
1071 self.flags.write(w)?;
1072 self.cltv_expiry_delta.write(w)?;
1073 self.htlc_minimum_msat.write(w)?;
1074 self.fee_base_msat.write(w)?;
1075 self.fee_proportional_millionths.write(w)?;
1076 w.write_all(&self.excess_data[..])?;
1081 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1082 fn read(r: &mut R) -> Result<Self, DecodeError> {
1084 chain_hash: Readable::read(r)?,
1085 short_channel_id: Readable::read(r)?,
1086 timestamp: Readable::read(r)?,
1087 flags: Readable::read(r)?,
1088 cltv_expiry_delta: Readable::read(r)?,
1089 htlc_minimum_msat: Readable::read(r)?,
1090 fee_base_msat: Readable::read(r)?,
1091 fee_proportional_millionths: Readable::read(r)?,
1093 let mut excess_data = vec![];
1094 r.read_to_end(&mut excess_data)?;
1101 impl_writeable_len_match!(ChannelUpdate, {
1102 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1103 64 + excess_data.len() + 64 }
1109 impl Writeable for ErrorMessage {
1110 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1111 w.size_hint(32 + 2 + self.data.len());
1112 self.channel_id.write(w)?;
1113 (self.data.len() as u16).write(w)?;
1114 w.write_all(self.data.as_bytes())?;
1119 impl<R: Read> Readable<R> for ErrorMessage {
1120 fn read(r: &mut R) -> Result<Self, DecodeError> {
1122 channel_id: Readable::read(r)?,
1124 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1125 let mut data = vec![];
1126 let data_len = r.read_to_end(&mut data)?;
1127 sz = cmp::min(data_len, sz);
1128 match String::from_utf8(data[..sz as usize].to_vec()) {
1130 Err(_) => return Err(DecodeError::InvalidValue),
1137 impl Writeable for UnsignedNodeAnnouncement {
1138 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1139 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1140 self.features.write(w)?;
1141 self.timestamp.write(w)?;
1142 self.node_id.write(w)?;
1143 w.write_all(&self.rgb)?;
1144 self.alias.write(w)?;
1146 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1147 let mut addrs_to_encode = self.addresses.clone();
1148 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1149 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1150 for addr in addrs_to_encode.iter() {
1152 &NetAddress::IPv4{addr, port} => {
1154 addr_slice.extend_from_slice(&addr);
1155 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1157 &NetAddress::IPv6{addr, port} => {
1159 addr_slice.extend_from_slice(&addr);
1160 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1162 &NetAddress::OnionV2{addr, port} => {
1164 addr_slice.extend_from_slice(&addr);
1165 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1167 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1169 addr_slice.extend_from_slice(&ed25519_pubkey);
1170 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1171 addr_slice.push(version);
1172 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1176 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1177 w.write_all(&addr_slice[..])?;
1178 w.write_all(&self.excess_address_data[..])?;
1179 w.write_all(&self.excess_data[..])?;
1184 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1185 fn read(r: &mut R) -> Result<Self, DecodeError> {
1186 let features: GlobalFeatures = Readable::read(r)?;
1187 if features.requires_unknown_bits() {
1188 return Err(DecodeError::UnknownRequiredFeature);
1190 let timestamp: u32 = Readable::read(r)?;
1191 let node_id: PublicKey = Readable::read(r)?;
1192 let mut rgb = [0; 3];
1193 r.read_exact(&mut rgb)?;
1194 let alias: [u8; 32] = Readable::read(r)?;
1196 let addrlen: u16 = Readable::read(r)?;
1197 let mut addr_readpos = 0;
1198 let mut addresses = Vec::with_capacity(4);
1202 if addrlen <= addr_readpos { break; }
1203 f = Readable::read(r)?;
1206 if addresses.len() > 0 {
1207 return Err(DecodeError::ExtraAddressesPerType);
1209 if addrlen < addr_readpos + 1 + 6 {
1210 return Err(DecodeError::BadLengthDescriptor);
1212 addresses.push(NetAddress::IPv4 {
1214 let mut addr = [0; 4];
1215 r.read_exact(&mut addr)?;
1218 port: Readable::read(r)?,
1220 addr_readpos += 1 + 6
1223 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1224 return Err(DecodeError::ExtraAddressesPerType);
1226 if addrlen < addr_readpos + 1 + 18 {
1227 return Err(DecodeError::BadLengthDescriptor);
1229 addresses.push(NetAddress::IPv6 {
1231 let mut addr = [0; 16];
1232 r.read_exact(&mut addr)?;
1235 port: Readable::read(r)?,
1237 addr_readpos += 1 + 18
1240 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1241 return Err(DecodeError::ExtraAddressesPerType);
1243 if addrlen < addr_readpos + 1 + 12 {
1244 return Err(DecodeError::BadLengthDescriptor);
1246 addresses.push(NetAddress::OnionV2 {
1248 let mut addr = [0; 10];
1249 r.read_exact(&mut addr)?;
1252 port: Readable::read(r)?,
1254 addr_readpos += 1 + 12
1257 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1258 return Err(DecodeError::ExtraAddressesPerType);
1260 if addrlen < addr_readpos + 1 + 37 {
1261 return Err(DecodeError::BadLengthDescriptor);
1263 addresses.push(NetAddress::OnionV3 {
1264 ed25519_pubkey: Readable::read(r)?,
1265 checksum: Readable::read(r)?,
1266 version: Readable::read(r)?,
1267 port: Readable::read(r)?,
1269 addr_readpos += 1 + 37
1271 _ => { excess = 1; break; }
1275 let mut excess_data = vec![];
1276 let excess_address_data = if addr_readpos < addrlen {
1277 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1278 r.read_exact(&mut excess_address_data[excess..])?;
1280 excess_address_data[0] = f;
1285 excess_data.push(f);
1290 Ok(UnsignedNodeAnnouncement {
1292 timestamp: timestamp,
1296 addresses: addresses,
1297 excess_address_data: excess_address_data,
1299 r.read_to_end(&mut excess_data)?;
1306 impl_writeable_len_match!(NodeAnnouncement, {
1307 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1308 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1318 use util::ser::Writeable;
1319 use secp256k1::key::{PublicKey,SecretKey};
1320 use secp256k1::Secp256k1;
1323 fn encoding_channel_reestablish_no_secret() {
1324 let cr = msgs::ChannelReestablish {
1325 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],
1326 next_local_commitment_number: 3,
1327 next_remote_commitment_number: 4,
1328 data_loss_protect: None,
1331 let encoded_value = cr.encode();
1334 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]
1339 fn encoding_channel_reestablish_with_secret() {
1341 let secp_ctx = Secp256k1::new();
1342 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1345 let cr = msgs::ChannelReestablish {
1346 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],
1347 next_local_commitment_number: 3,
1348 next_remote_commitment_number: 4,
1349 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1352 let encoded_value = cr.encode();
1355 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]