1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
3 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
4 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
5 //! server entirely) which handles only channel-related messages you may wish to implement
6 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
9 //! Note that if you go with such an architecture (instead of passing raw socket events to a
10 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
11 //! source node_id of the mssage, however this does allow you to significantly reduce bandwidth
12 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
13 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
14 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
15 //! raw socket events into your non-internet-facing system and then send routing events back to
16 //! track the network on the less-secure system.
18 use secp256k1::key::PublicKey;
19 use secp256k1::{Secp256k1, Signature};
21 use bitcoin::util::hash::Sha256dHash;
22 use bitcoin::blockdata::script::Script;
24 use std::error::Error;
27 use std::result::Result;
29 use util::{byte_utils, events};
30 use util::ser::{Readable, Writeable, Writer};
32 /// An error in decoding a message or struct.
34 pub enum DecodeError {
35 /// A version byte specified something we don't know how to handle.
36 /// Includes unknown realm byte in an OnionHopData packet
38 /// Unknown feature mandating we fail to parse message
39 UnknownRequiredFeature,
40 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
41 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
45 /// node_announcement included more than one address of a given type!
46 ExtraAddressesPerType,
47 /// A length descriptor in the packet didn't describe the later data correctly
48 /// (currently only generated in node_announcement)
50 /// Error from std::io
54 /// Tracks localfeatures which are only in init messages
55 #[derive(Clone, PartialEq)]
56 pub struct LocalFeatures {
61 pub(crate) fn new() -> LocalFeatures {
67 pub(crate) fn supports_data_loss_protect(&self) -> bool {
68 self.flags.len() > 0 && (self.flags[0] & 3) != 0
70 pub(crate) fn requires_data_loss_protect(&self) -> bool {
71 self.flags.len() > 0 && (self.flags[0] & 1) != 0
74 pub(crate) fn initial_routing_sync(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
77 pub(crate) fn set_initial_routing_sync(&mut self) {
78 if self.flags.len() == 0 {
79 self.flags.resize(1, 1 << 3);
81 self.flags[0] |= 1 << 3;
85 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
86 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
88 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
89 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
92 pub(crate) fn requires_unknown_bits(&self) -> bool {
93 for (idx, &byte) in self.flags.iter().enumerate() {
94 if idx != 0 && (byte & 0x55) != 0 {
96 } else if idx == 0 && (byte & 0x14) != 0 {
103 pub(crate) fn supports_unknown_bits(&self) -> bool {
104 for (idx, &byte) in self.flags.iter().enumerate() {
105 if idx != 0 && byte != 0 {
107 } else if idx == 0 && (byte & 0xc4) != 0 {
115 /// Tracks globalfeatures which are in init messages and routing announcements
116 #[derive(Clone, PartialEq)]
117 pub struct GlobalFeatures {
121 impl GlobalFeatures {
122 pub(crate) fn new() -> GlobalFeatures {
128 pub(crate) fn requires_unknown_bits(&self) -> bool {
129 for &byte in self.flags.iter() {
130 if (byte & 0x55) != 0 {
137 pub(crate) fn supports_unknown_bits(&self) -> bool {
138 for &byte in self.flags.iter() {
147 /// An init message to be sent or received from a peer
149 pub(crate) global_features: GlobalFeatures,
150 pub(crate) local_features: LocalFeatures,
153 /// An error message to be sent or received from a peer
154 pub struct ErrorMessage {
155 pub(crate) channel_id: [u8; 32],
156 pub(crate) data: String,
159 /// A ping message to be sent or received from a peer
161 pub(crate) ponglen: u16,
162 pub(crate) byteslen: u16,
165 /// A pong message to be sent or received from a peer
167 pub(crate) byteslen: u16,
170 /// An open_channel message to be sent or received from a peer
172 pub struct OpenChannel {
173 pub(crate) chain_hash: Sha256dHash,
174 pub(crate) temporary_channel_id: [u8; 32],
175 pub(crate) funding_satoshis: u64,
176 pub(crate) push_msat: u64,
177 pub(crate) dust_limit_satoshis: u64,
178 pub(crate) max_htlc_value_in_flight_msat: u64,
179 pub(crate) channel_reserve_satoshis: u64,
180 pub(crate) htlc_minimum_msat: u64,
181 pub(crate) feerate_per_kw: u32,
182 pub(crate) to_self_delay: u16,
183 pub(crate) max_accepted_htlcs: u16,
184 pub(crate) funding_pubkey: PublicKey,
185 pub(crate) revocation_basepoint: PublicKey,
186 pub(crate) payment_basepoint: PublicKey,
187 pub(crate) delayed_payment_basepoint: PublicKey,
188 pub(crate) htlc_basepoint: PublicKey,
189 pub(crate) first_per_commitment_point: PublicKey,
190 pub(crate) channel_flags: u8,
191 pub(crate) shutdown_scriptpubkey: Option<Script>,
194 /// An accept_channel message to be sent or received from a peer
196 pub struct AcceptChannel {
197 pub(crate) temporary_channel_id: [u8; 32],
198 pub(crate) dust_limit_satoshis: u64,
199 pub(crate) max_htlc_value_in_flight_msat: u64,
200 pub(crate) channel_reserve_satoshis: u64,
201 pub(crate) htlc_minimum_msat: u64,
202 pub(crate) minimum_depth: u32,
203 pub(crate) to_self_delay: u16,
204 pub(crate) max_accepted_htlcs: u16,
205 pub(crate) funding_pubkey: PublicKey,
206 pub(crate) revocation_basepoint: PublicKey,
207 pub(crate) payment_basepoint: PublicKey,
208 pub(crate) delayed_payment_basepoint: PublicKey,
209 pub(crate) htlc_basepoint: PublicKey,
210 pub(crate) first_per_commitment_point: PublicKey,
211 pub(crate) shutdown_scriptpubkey: Option<Script>,
214 /// A funding_created message to be sent or received from a peer
216 pub struct FundingCreated {
217 pub(crate) temporary_channel_id: [u8; 32],
218 pub(crate) funding_txid: Sha256dHash,
219 pub(crate) funding_output_index: u16,
220 pub(crate) signature: Signature,
223 /// A funding_signed message to be sent or received from a peer
225 pub struct FundingSigned {
226 pub(crate) channel_id: [u8; 32],
227 pub(crate) signature: Signature,
230 /// A funding_locked message to be sent or received from a peer
231 #[derive(Clone, PartialEq)]
232 pub struct FundingLocked {
233 pub(crate) channel_id: [u8; 32],
234 pub(crate) next_per_commitment_point: PublicKey,
237 /// A shutdown message to be sent or received from a peer
238 pub struct Shutdown {
239 pub(crate) channel_id: [u8; 32],
240 pub(crate) scriptpubkey: Script,
243 /// A closing_signed message to be sent or received from a peer
244 pub struct ClosingSigned {
245 pub(crate) channel_id: [u8; 32],
246 pub(crate) fee_satoshis: u64,
247 pub(crate) signature: Signature,
250 /// An update_add_htlc message to be sent or received from a peer
251 #[derive(Clone, PartialEq)]
252 pub struct UpdateAddHTLC {
253 pub(crate) channel_id: [u8; 32],
254 pub(crate) htlc_id: u64,
255 pub(crate) amount_msat: u64,
256 pub(crate) payment_hash: [u8; 32],
257 pub(crate) cltv_expiry: u32,
258 pub(crate) onion_routing_packet: OnionPacket,
261 /// An update_fulfill_htlc message to be sent or received from a peer
262 #[derive(Clone, PartialEq)]
263 pub struct UpdateFulfillHTLC {
264 pub(crate) channel_id: [u8; 32],
265 pub(crate) htlc_id: u64,
266 pub(crate) payment_preimage: [u8; 32],
269 /// An update_fail_htlc message to be sent or received from a peer
270 #[derive(Clone, PartialEq)]
271 pub struct UpdateFailHTLC {
272 pub(crate) channel_id: [u8; 32],
273 pub(crate) htlc_id: u64,
274 pub(crate) reason: OnionErrorPacket,
277 /// An update_fail_malformed_htlc message to be sent or received from a peer
278 #[derive(Clone, PartialEq)]
279 pub struct UpdateFailMalformedHTLC {
280 pub(crate) channel_id: [u8; 32],
281 pub(crate) htlc_id: u64,
282 pub(crate) sha256_of_onion: [u8; 32],
283 pub(crate) failure_code: u16,
286 /// A commitment_signed message to be sent or received from a peer
287 #[derive(Clone, PartialEq)]
288 pub struct CommitmentSigned {
289 pub(crate) channel_id: [u8; 32],
290 pub(crate) signature: Signature,
291 pub(crate) htlc_signatures: Vec<Signature>,
294 /// A revoke_and_ack message to be sent or received from a peer
295 #[derive(Clone, PartialEq)]
296 pub struct RevokeAndACK {
297 pub(crate) channel_id: [u8; 32],
298 pub(crate) per_commitment_secret: [u8; 32],
299 pub(crate) next_per_commitment_point: PublicKey,
302 /// An update_fee message to be sent or received from a peer
304 pub struct UpdateFee {
305 pub(crate) channel_id: [u8; 32],
306 pub(crate) feerate_per_kw: u32,
310 pub(crate) struct DataLossProtect {
311 pub(crate) your_last_per_commitment_secret: [u8; 32],
312 pub(crate) my_current_per_commitment_point: PublicKey,
315 /// A channel_reestablish message to be sent or received from a peer
317 pub struct ChannelReestablish {
318 pub(crate) channel_id: [u8; 32],
319 pub(crate) next_local_commitment_number: u64,
320 pub(crate) next_remote_commitment_number: u64,
321 pub(crate) data_loss_protect: Option<DataLossProtect>,
324 /// An announcement_signatures message to be sent or received from a peer
326 pub struct AnnouncementSignatures {
327 pub(crate) channel_id: [u8; 32],
328 pub(crate) short_channel_id: u64,
329 pub(crate) node_signature: Signature,
330 pub(crate) bitcoin_signature: Signature,
333 /// An address which can be used to connect to a remote peer
335 pub enum NetAddress {
336 /// An IPv4 address/port on which the peer is listenting.
338 /// The 4-byte IPv4 address
340 /// The port on which the node is listenting
343 /// An IPv6 address/port on which the peer is listenting.
345 /// The 16-byte IPv6 address
347 /// The port on which the node is listenting
350 /// An old-style Tor onion address/port on which the peer is listening.
352 /// The bytes (usually encoded in base32 with ".onion" appended)
354 /// The port on which the node is listenting
357 /// A new-style Tor onion address/port on which the peer is listening.
358 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
359 /// wrap as base32 and append ".onion".
361 /// The ed25519 long-term public key of the peer
362 ed25519_pubkey: [u8; 32],
363 /// The checksum of the pubkey and version, as included in the onion address
365 /// The version byte, as defined by the Tor Onion v3 spec.
367 /// The port on which the node is listenting
372 fn get_id(&self) -> u8 {
374 &NetAddress::IPv4 {..} => { 1 },
375 &NetAddress::IPv6 {..} => { 2 },
376 &NetAddress::OnionV2 {..} => { 3 },
377 &NetAddress::OnionV3 {..} => { 4 },
382 // Only exposed as broadcast of node_announcement should be filtered by node_id
383 /// The unsigned part of a node_announcement
384 pub struct UnsignedNodeAnnouncement {
385 pub(crate) features: GlobalFeatures,
386 pub(crate) timestamp: u32,
387 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
389 pub node_id: PublicKey,
390 pub(crate) rgb: [u8; 3],
391 pub(crate) alias: [u8; 32],
392 /// List of addresses on which this node is reachable. Note that you may only have up to one
393 /// address of each type, if you have more, they may be silently discarded or we may panic!
394 pub(crate) addresses: Vec<NetAddress>,
395 pub(crate) excess_address_data: Vec<u8>,
396 pub(crate) excess_data: Vec<u8>,
398 /// A node_announcement message to be sent or received from a peer
399 pub struct NodeAnnouncement {
400 pub(crate) signature: Signature,
401 pub(crate) contents: UnsignedNodeAnnouncement,
404 // Only exposed as broadcast of channel_announcement should be filtered by node_id
405 /// The unsigned part of a channel_announcement
406 #[derive(PartialEq, Clone)]
407 pub struct UnsignedChannelAnnouncement {
408 pub(crate) features: GlobalFeatures,
409 pub(crate) chain_hash: Sha256dHash,
410 pub(crate) short_channel_id: u64,
411 /// One of the two node_ids which are endpoints of this channel
412 pub node_id_1: PublicKey,
413 /// The other of the two node_ids which are endpoints of this channel
414 pub node_id_2: PublicKey,
415 pub(crate) bitcoin_key_1: PublicKey,
416 pub(crate) bitcoin_key_2: PublicKey,
417 pub(crate) excess_data: Vec<u8>,
419 /// A channel_announcement message to be sent or received from a peer
420 #[derive(PartialEq, Clone)]
421 pub struct ChannelAnnouncement {
422 pub(crate) node_signature_1: Signature,
423 pub(crate) node_signature_2: Signature,
424 pub(crate) bitcoin_signature_1: Signature,
425 pub(crate) bitcoin_signature_2: Signature,
426 pub(crate) contents: UnsignedChannelAnnouncement,
429 #[derive(PartialEq, Clone)]
430 pub(crate) struct UnsignedChannelUpdate {
431 pub(crate) chain_hash: Sha256dHash,
432 pub(crate) short_channel_id: u64,
433 pub(crate) timestamp: u32,
434 pub(crate) flags: u16,
435 pub(crate) cltv_expiry_delta: u16,
436 pub(crate) htlc_minimum_msat: u64,
437 pub(crate) fee_base_msat: u32,
438 pub(crate) fee_proportional_millionths: u32,
439 pub(crate) excess_data: Vec<u8>,
441 /// A channel_update message to be sent or received from a peer
442 #[derive(PartialEq, Clone)]
443 pub struct ChannelUpdate {
444 pub(crate) signature: Signature,
445 pub(crate) contents: UnsignedChannelUpdate,
448 /// Used to put an error message in a HandleError
449 pub enum ErrorAction {
450 /// The peer took some action which made us think they were useless. Disconnect them.
452 /// An error message which we should make an effort to send before we disconnect.
453 msg: Option<ErrorMessage>
455 /// The peer did something harmless that we weren't able to process, just log and ignore
457 /// The peer did something incorrect. Tell them.
459 /// The message to send.
464 /// An Err type for failure to process messages.
465 pub struct HandleError { //TODO: rename me
466 /// A human-readable message describing the error
467 pub err: &'static str,
468 /// The action which should be taken against the offending peer.
469 pub action: Option<ErrorAction>, //TODO: Make this required
472 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
473 /// transaction updates if they were pending.
475 pub struct CommitmentUpdate {
476 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
477 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
478 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
479 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
480 pub(crate) update_fee: Option<UpdateFee>,
481 pub(crate) commitment_signed: CommitmentSigned,
484 /// The information we received from a peer along the route of a payment we originated. This is
485 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
486 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
487 pub enum HTLCFailChannelUpdate {
488 /// We received an error which included a full ChannelUpdate message.
489 ChannelUpdateMessage {
490 /// The unwrapped message we received
493 /// We received an error which indicated only that a channel has been closed
495 /// The short_channel_id which has now closed.
496 short_channel_id: u64,
497 /// when this true, this channel should be permanently removed from the
498 /// consideration. Otherwise, this channel can be restored as new channel_update is received
501 /// We received an error which indicated only that a node has failed
503 /// The node_id that has failed.
505 /// when this true, node should be permanently removed from the
506 /// consideration. Otherwise, the channels connected to this node can be
507 /// restored as new channel_update is received
512 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
513 /// be sent in the order they appear in the return value, however sometimes the order needs to be
514 /// variable at runtime (eg handle_channel_reestablish needs to re-send messages in the order they
515 /// were originally sent). In those cases, this enum is also returned.
516 #[derive(Clone, PartialEq)]
517 pub enum RAACommitmentOrder {
518 /// Send the CommitmentUpdate messages first
520 /// Send the RevokeAndACK message first
524 /// A trait to describe an object which can receive channel messages.
526 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
527 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
528 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
530 /// Handle an incoming open_channel message from the given peer.
531 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
532 /// Handle an incoming accept_channel message from the given peer.
533 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
534 /// Handle an incoming funding_created message from the given peer.
535 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
536 /// Handle an incoming funding_signed message from the given peer.
537 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
538 /// Handle an incoming funding_locked message from the given peer.
539 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
542 /// Handle an incoming shutdown message from the given peer.
543 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
544 /// Handle an incoming closing_signed message from the given peer.
545 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
548 /// Handle an incoming update_add_htlc message from the given peer.
549 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
550 /// Handle an incoming update_fulfill_htlc message from the given peer.
551 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
552 /// Handle an incoming update_fail_htlc message from the given peer.
553 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
554 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
555 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
556 /// Handle an incoming commitment_signed message from the given peer.
557 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
558 /// Handle an incoming revoke_and_ack message from the given peer.
559 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
561 /// Handle an incoming update_fee message from the given peer.
562 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
564 // Channel-to-announce:
565 /// Handle an incoming announcement_signatures message from the given peer.
566 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
568 // Connection loss/reestablish:
569 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
570 /// is believed to be possible in the future (eg they're sending us messages we don't
571 /// understand or indicate they require unknown feature bits), no_connection_possible is set
572 /// and any outstanding channels should be failed.
573 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
575 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
576 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
577 /// Handle an incoming channel_reestablish message from the given peer.
578 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>, RAACommitmentOrder), HandleError>;
581 /// Handle an incoming error message from the given peer.
582 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
585 /// A trait to describe an object which can receive routing messages.
586 pub trait RoutingMessageHandler : Send + Sync {
587 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
588 /// false or returning an Err otherwise.
589 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
590 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
591 /// or returning an Err otherwise.
592 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
593 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
594 /// false or returning an Err otherwise.
595 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
596 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
597 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
600 pub(crate) struct OnionRealm0HopData {
601 pub(crate) short_channel_id: u64,
602 pub(crate) amt_to_forward: u64,
603 pub(crate) outgoing_cltv_value: u32,
604 // 12 bytes of 0-padding
607 mod fuzzy_internal_msgs {
608 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
609 // them from untrusted input):
611 use super::OnionRealm0HopData;
612 pub struct OnionHopData {
613 pub(crate) realm: u8,
614 pub(crate) data: OnionRealm0HopData,
615 pub(crate) hmac: [u8; 32],
617 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
619 pub struct DecodedOnionErrorPacket {
620 pub(crate) hmac: [u8; 32],
621 pub(crate) failuremsg: Vec<u8>,
622 pub(crate) pad: Vec<u8>,
625 #[cfg(feature = "fuzztarget")]
626 pub use self::fuzzy_internal_msgs::*;
627 #[cfg(not(feature = "fuzztarget"))]
628 pub(crate) use self::fuzzy_internal_msgs::*;
631 pub(crate) struct OnionPacket {
632 pub(crate) version: u8,
633 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
634 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
635 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
636 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
637 pub(crate) hop_data: [u8; 20*65],
638 pub(crate) hmac: [u8; 32],
641 impl PartialEq for OnionPacket {
642 fn eq(&self, other: &OnionPacket) -> bool {
643 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
644 if i != j { return false; }
646 self.version == other.version &&
647 self.public_key == other.public_key &&
648 self.hmac == other.hmac
652 #[derive(Clone, PartialEq)]
653 pub(crate) struct OnionErrorPacket {
654 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
655 // (TODO) We limit it in decode to much lower...
656 pub(crate) data: Vec<u8>,
659 impl Error for DecodeError {
660 fn description(&self) -> &str {
662 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
663 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
664 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
665 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
666 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
667 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
668 DecodeError::Io(ref e) => e.description(),
672 impl fmt::Display for DecodeError {
673 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
674 f.write_str(self.description())
678 impl fmt::Debug for HandleError {
679 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680 f.write_str(self.err)
684 impl From<::std::io::Error> for DecodeError {
685 fn from(e: ::std::io::Error) -> Self {
686 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
687 DecodeError::ShortRead
694 impl_writeable_len_match!(AcceptChannel, {
695 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
698 temporary_channel_id,
700 max_htlc_value_in_flight_msat,
701 channel_reserve_satoshis,
707 revocation_basepoint,
709 delayed_payment_basepoint,
711 first_per_commitment_point,
712 shutdown_scriptpubkey
715 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
722 impl Writeable for ChannelReestablish {
723 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
724 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
725 self.channel_id.write(w)?;
726 self.next_local_commitment_number.write(w)?;
727 self.next_remote_commitment_number.write(w)?;
728 if let Some(ref data_loss_protect) = self.data_loss_protect {
729 data_loss_protect.your_last_per_commitment_secret.write(w)?;
730 data_loss_protect.my_current_per_commitment_point.write(w)?;
736 impl<R: Read> Readable<R> for ChannelReestablish{
737 fn read(r: &mut R) -> Result<Self, DecodeError> {
739 channel_id: Readable::read(r)?,
740 next_local_commitment_number: Readable::read(r)?,
741 next_remote_commitment_number: Readable::read(r)?,
743 match <[u8; 32] as Readable<R>>::read(r) {
744 Ok(your_last_per_commitment_secret) =>
745 Some(DataLossProtect {
746 your_last_per_commitment_secret,
747 my_current_per_commitment_point: Readable::read(r)?,
749 Err(DecodeError::ShortRead) => None,
750 Err(e) => return Err(e)
757 impl_writeable!(ClosingSigned, 32+8+64, {
763 impl_writeable_len_match!(CommitmentSigned, {
764 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
771 impl_writeable_len_match!(DecodedOnionErrorPacket, {
772 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
779 impl_writeable!(FundingCreated, 32+32+2+64, {
780 temporary_channel_id,
782 funding_output_index,
786 impl_writeable!(FundingSigned, 32+64, {
791 impl_writeable!(FundingLocked, 32+33, {
793 next_per_commitment_point
796 impl_writeable_len_match!(GlobalFeatures, {
797 { GlobalFeatures { ref flags }, flags.len() + 2 }
802 impl_writeable_len_match!(LocalFeatures, {
803 { LocalFeatures { ref flags }, flags.len() + 2 }
808 impl_writeable_len_match!(Init, {
809 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
815 impl_writeable_len_match!(OpenChannel, {
816 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
817 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
820 temporary_channel_id,
824 max_htlc_value_in_flight_msat,
825 channel_reserve_satoshis,
831 revocation_basepoint,
833 delayed_payment_basepoint,
835 first_per_commitment_point,
837 shutdown_scriptpubkey
840 impl_writeable!(RevokeAndACK, 32+32+33, {
842 per_commitment_secret,
843 next_per_commitment_point
846 impl_writeable_len_match!(Shutdown, {
847 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
853 impl_writeable_len_match!(UpdateFailHTLC, {
854 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
861 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
868 impl_writeable!(UpdateFee, 32+4, {
873 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
879 impl_writeable_len_match!(OnionErrorPacket, {
880 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
885 impl Writeable for OnionPacket {
886 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
887 w.size_hint(1 + 33 + 20*65 + 32);
888 self.version.write(w)?;
889 match self.public_key {
890 Ok(pubkey) => pubkey.write(w)?,
891 Err(_) => [0u8;33].write(w)?,
893 w.write_all(&self.hop_data)?;
899 impl<R: Read> Readable<R> for OnionPacket {
900 fn read(r: &mut R) -> Result<Self, DecodeError> {
902 version: Readable::read(r)?,
904 let mut buf = [0u8;33];
905 r.read_exact(&mut buf)?;
906 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
908 hop_data: Readable::read(r)?,
909 hmac: Readable::read(r)?,
914 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
923 impl Writeable for OnionRealm0HopData {
924 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
926 self.short_channel_id.write(w)?;
927 self.amt_to_forward.write(w)?;
928 self.outgoing_cltv_value.write(w)?;
929 w.write_all(&[0;12])?;
934 impl<R: Read> Readable<R> for OnionRealm0HopData {
935 fn read(r: &mut R) -> Result<Self, DecodeError> {
936 Ok(OnionRealm0HopData {
937 short_channel_id: Readable::read(r)?,
938 amt_to_forward: Readable::read(r)?,
939 outgoing_cltv_value: {
940 let v: u32 = Readable::read(r)?;
941 r.read_exact(&mut [0; 12])?;
948 impl Writeable for OnionHopData {
949 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
951 self.realm.write(w)?;
958 impl<R: Read> Readable<R> for OnionHopData {
959 fn read(r: &mut R) -> Result<Self, DecodeError> {
962 let r: u8 = Readable::read(r)?;
964 return Err(DecodeError::UnknownVersion);
968 data: Readable::read(r)?,
969 hmac: Readable::read(r)?,
974 impl Writeable for Ping {
975 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
976 w.size_hint(self.byteslen as usize + 4);
977 self.ponglen.write(w)?;
978 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
983 impl<R: Read> Readable<R> for Ping {
984 fn read(r: &mut R) -> Result<Self, DecodeError> {
986 ponglen: Readable::read(r)?,
988 let byteslen = Readable::read(r)?;
989 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
996 impl Writeable for Pong {
997 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
998 w.size_hint(self.byteslen as usize + 2);
999 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1004 impl<R: Read> Readable<R> for Pong {
1005 fn read(r: &mut R) -> Result<Self, DecodeError> {
1008 let byteslen = Readable::read(r)?;
1009 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1016 impl Writeable for UnsignedChannelAnnouncement {
1017 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1018 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1019 self.features.write(w)?;
1020 self.chain_hash.write(w)?;
1021 self.short_channel_id.write(w)?;
1022 self.node_id_1.write(w)?;
1023 self.node_id_2.write(w)?;
1024 self.bitcoin_key_1.write(w)?;
1025 self.bitcoin_key_2.write(w)?;
1026 w.write_all(&self.excess_data[..])?;
1031 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1032 fn read(r: &mut R) -> Result<Self, DecodeError> {
1035 let f: GlobalFeatures = Readable::read(r)?;
1036 if f.requires_unknown_bits() {
1037 return Err(DecodeError::UnknownRequiredFeature);
1041 chain_hash: Readable::read(r)?,
1042 short_channel_id: Readable::read(r)?,
1043 node_id_1: Readable::read(r)?,
1044 node_id_2: Readable::read(r)?,
1045 bitcoin_key_1: Readable::read(r)?,
1046 bitcoin_key_2: Readable::read(r)?,
1048 let mut excess_data = vec![];
1049 r.read_to_end(&mut excess_data)?;
1056 impl_writeable_len_match!(ChannelAnnouncement, {
1057 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1058 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1062 bitcoin_signature_1,
1063 bitcoin_signature_2,
1067 impl Writeable for UnsignedChannelUpdate {
1068 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1069 w.size_hint(64 + self.excess_data.len());
1070 self.chain_hash.write(w)?;
1071 self.short_channel_id.write(w)?;
1072 self.timestamp.write(w)?;
1073 self.flags.write(w)?;
1074 self.cltv_expiry_delta.write(w)?;
1075 self.htlc_minimum_msat.write(w)?;
1076 self.fee_base_msat.write(w)?;
1077 self.fee_proportional_millionths.write(w)?;
1078 w.write_all(&self.excess_data[..])?;
1083 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1084 fn read(r: &mut R) -> Result<Self, DecodeError> {
1086 chain_hash: Readable::read(r)?,
1087 short_channel_id: Readable::read(r)?,
1088 timestamp: Readable::read(r)?,
1089 flags: Readable::read(r)?,
1090 cltv_expiry_delta: Readable::read(r)?,
1091 htlc_minimum_msat: Readable::read(r)?,
1092 fee_base_msat: Readable::read(r)?,
1093 fee_proportional_millionths: Readable::read(r)?,
1095 let mut excess_data = vec![];
1096 r.read_to_end(&mut excess_data)?;
1103 impl_writeable_len_match!(ChannelUpdate, {
1104 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1105 64 + excess_data.len() + 64 }
1111 impl Writeable for ErrorMessage {
1112 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1113 w.size_hint(32 + 2 + self.data.len());
1114 self.channel_id.write(w)?;
1115 (self.data.len() as u16).write(w)?;
1116 w.write_all(self.data.as_bytes())?;
1121 impl<R: Read> Readable<R> for ErrorMessage {
1122 fn read(r: &mut R) -> Result<Self, DecodeError> {
1124 channel_id: Readable::read(r)?,
1126 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1127 let mut data = vec![];
1128 let data_len = r.read_to_end(&mut data)?;
1129 sz = cmp::min(data_len, sz);
1130 match String::from_utf8(data[..sz as usize].to_vec()) {
1132 Err(_) => return Err(DecodeError::InvalidValue),
1139 impl Writeable for UnsignedNodeAnnouncement {
1140 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1141 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1142 self.features.write(w)?;
1143 self.timestamp.write(w)?;
1144 self.node_id.write(w)?;
1145 w.write_all(&self.rgb)?;
1146 self.alias.write(w)?;
1148 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1149 let mut addrs_to_encode = self.addresses.clone();
1150 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1151 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1152 for addr in addrs_to_encode.iter() {
1154 &NetAddress::IPv4{addr, port} => {
1156 addr_slice.extend_from_slice(&addr);
1157 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1159 &NetAddress::IPv6{addr, port} => {
1161 addr_slice.extend_from_slice(&addr);
1162 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1164 &NetAddress::OnionV2{addr, port} => {
1166 addr_slice.extend_from_slice(&addr);
1167 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1169 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1171 addr_slice.extend_from_slice(&ed25519_pubkey);
1172 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1173 addr_slice.push(version);
1174 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1178 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1179 w.write_all(&addr_slice[..])?;
1180 w.write_all(&self.excess_address_data[..])?;
1181 w.write_all(&self.excess_data[..])?;
1186 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1187 fn read(r: &mut R) -> Result<Self, DecodeError> {
1188 let features: GlobalFeatures = Readable::read(r)?;
1189 if features.requires_unknown_bits() {
1190 return Err(DecodeError::UnknownRequiredFeature);
1192 let timestamp: u32 = Readable::read(r)?;
1193 let node_id: PublicKey = Readable::read(r)?;
1194 let mut rgb = [0; 3];
1195 r.read_exact(&mut rgb)?;
1196 let alias: [u8; 32] = Readable::read(r)?;
1198 let addrlen: u16 = Readable::read(r)?;
1199 let mut addr_readpos = 0;
1200 let mut addresses = Vec::with_capacity(4);
1204 if addrlen <= addr_readpos { break; }
1205 f = Readable::read(r)?;
1208 if addresses.len() > 0 {
1209 return Err(DecodeError::ExtraAddressesPerType);
1211 if addrlen < addr_readpos + 1 + 6 {
1212 return Err(DecodeError::BadLengthDescriptor);
1214 addresses.push(NetAddress::IPv4 {
1216 let mut addr = [0; 4];
1217 r.read_exact(&mut addr)?;
1220 port: Readable::read(r)?,
1222 addr_readpos += 1 + 6
1225 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1226 return Err(DecodeError::ExtraAddressesPerType);
1228 if addrlen < addr_readpos + 1 + 18 {
1229 return Err(DecodeError::BadLengthDescriptor);
1231 addresses.push(NetAddress::IPv6 {
1233 let mut addr = [0; 16];
1234 r.read_exact(&mut addr)?;
1237 port: Readable::read(r)?,
1239 addr_readpos += 1 + 18
1242 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1243 return Err(DecodeError::ExtraAddressesPerType);
1245 if addrlen < addr_readpos + 1 + 12 {
1246 return Err(DecodeError::BadLengthDescriptor);
1248 addresses.push(NetAddress::OnionV2 {
1250 let mut addr = [0; 10];
1251 r.read_exact(&mut addr)?;
1254 port: Readable::read(r)?,
1256 addr_readpos += 1 + 12
1259 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1260 return Err(DecodeError::ExtraAddressesPerType);
1262 if addrlen < addr_readpos + 1 + 37 {
1263 return Err(DecodeError::BadLengthDescriptor);
1265 addresses.push(NetAddress::OnionV3 {
1266 ed25519_pubkey: Readable::read(r)?,
1267 checksum: Readable::read(r)?,
1268 version: Readable::read(r)?,
1269 port: Readable::read(r)?,
1271 addr_readpos += 1 + 37
1273 _ => { excess = 1; break; }
1277 let mut excess_data = vec![];
1278 let excess_address_data = if addr_readpos < addrlen {
1279 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1280 r.read_exact(&mut excess_address_data[excess..])?;
1282 excess_address_data[0] = f;
1287 excess_data.push(f);
1292 Ok(UnsignedNodeAnnouncement {
1294 timestamp: timestamp,
1298 addresses: addresses,
1299 excess_address_data: excess_address_data,
1301 r.read_to_end(&mut excess_data)?;
1308 impl_writeable_len_match!(NodeAnnouncement, {
1309 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1310 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1320 use util::ser::Writeable;
1321 use secp256k1::key::{PublicKey,SecretKey};
1322 use secp256k1::Secp256k1;
1325 fn encoding_channel_reestablish_no_secret() {
1326 let cr = msgs::ChannelReestablish {
1327 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],
1328 next_local_commitment_number: 3,
1329 next_remote_commitment_number: 4,
1330 data_loss_protect: None,
1333 let encoded_value = cr.encode();
1336 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]
1341 fn encoding_channel_reestablish_with_secret() {
1343 let secp_ctx = Secp256k1::new();
1344 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1347 let cr = msgs::ChannelReestablish {
1348 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],
1349 next_local_commitment_number: 3,
1350 next_remote_commitment_number: 4,
1351 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1354 let encoded_value = cr.encode();
1357 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]