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
155 pub struct ErrorMessage {
156 pub(crate) channel_id: [u8; 32],
157 pub(crate) data: String,
160 /// A ping message to be sent or received from a peer
162 pub(crate) ponglen: u16,
163 pub(crate) byteslen: u16,
166 /// A pong message to be sent or received from a peer
168 pub(crate) byteslen: u16,
171 /// An open_channel message to be sent or received from a peer
173 pub struct OpenChannel {
174 pub(crate) chain_hash: Sha256dHash,
175 pub(crate) temporary_channel_id: [u8; 32],
176 pub(crate) funding_satoshis: u64,
177 pub(crate) push_msat: u64,
178 pub(crate) dust_limit_satoshis: u64,
179 pub(crate) max_htlc_value_in_flight_msat: u64,
180 pub(crate) channel_reserve_satoshis: u64,
181 pub(crate) htlc_minimum_msat: u64,
182 pub(crate) feerate_per_kw: u32,
183 pub(crate) to_self_delay: u16,
184 pub(crate) max_accepted_htlcs: u16,
185 pub(crate) funding_pubkey: PublicKey,
186 pub(crate) revocation_basepoint: PublicKey,
187 pub(crate) payment_basepoint: PublicKey,
188 pub(crate) delayed_payment_basepoint: PublicKey,
189 pub(crate) htlc_basepoint: PublicKey,
190 pub(crate) first_per_commitment_point: PublicKey,
191 pub(crate) channel_flags: u8,
192 pub(crate) shutdown_scriptpubkey: Option<Script>,
195 /// An accept_channel message to be sent or received from a peer
197 pub struct AcceptChannel {
198 pub(crate) temporary_channel_id: [u8; 32],
199 pub(crate) dust_limit_satoshis: u64,
200 pub(crate) max_htlc_value_in_flight_msat: u64,
201 pub(crate) channel_reserve_satoshis: u64,
202 pub(crate) htlc_minimum_msat: u64,
203 pub(crate) minimum_depth: u32,
204 pub(crate) to_self_delay: u16,
205 pub(crate) max_accepted_htlcs: u16,
206 pub(crate) funding_pubkey: PublicKey,
207 pub(crate) revocation_basepoint: PublicKey,
208 pub(crate) payment_basepoint: PublicKey,
209 pub(crate) delayed_payment_basepoint: PublicKey,
210 pub(crate) htlc_basepoint: PublicKey,
211 pub(crate) first_per_commitment_point: PublicKey,
212 pub(crate) shutdown_scriptpubkey: Option<Script>,
215 /// A funding_created message to be sent or received from a peer
217 pub struct FundingCreated {
218 pub(crate) temporary_channel_id: [u8; 32],
219 pub(crate) funding_txid: Sha256dHash,
220 pub(crate) funding_output_index: u16,
221 pub(crate) signature: Signature,
224 /// A funding_signed message to be sent or received from a peer
226 pub struct FundingSigned {
227 pub(crate) channel_id: [u8; 32],
228 pub(crate) signature: Signature,
231 /// A funding_locked message to be sent or received from a peer
232 #[derive(Clone, PartialEq)]
233 pub struct FundingLocked {
234 pub(crate) channel_id: [u8; 32],
235 pub(crate) next_per_commitment_point: PublicKey,
238 /// A shutdown message to be sent or received from a peer
239 #[derive(Clone, PartialEq)]
240 pub struct Shutdown {
241 pub(crate) channel_id: [u8; 32],
242 pub(crate) scriptpubkey: Script,
245 /// A closing_signed message to be sent or received from a peer
246 #[derive(Clone, PartialEq)]
247 pub struct ClosingSigned {
248 pub(crate) channel_id: [u8; 32],
249 pub(crate) fee_satoshis: u64,
250 pub(crate) signature: Signature,
253 /// An update_add_htlc message to be sent or received from a peer
254 #[derive(Clone, PartialEq)]
255 pub struct UpdateAddHTLC {
256 pub(crate) channel_id: [u8; 32],
257 pub(crate) htlc_id: u64,
258 pub(crate) amount_msat: u64,
259 pub(crate) payment_hash: [u8; 32],
260 pub(crate) cltv_expiry: u32,
261 pub(crate) onion_routing_packet: OnionPacket,
264 /// An update_fulfill_htlc message to be sent or received from a peer
265 #[derive(Clone, PartialEq)]
266 pub struct UpdateFulfillHTLC {
267 pub(crate) channel_id: [u8; 32],
268 pub(crate) htlc_id: u64,
269 pub(crate) payment_preimage: [u8; 32],
272 /// An update_fail_htlc message to be sent or received from a peer
273 #[derive(Clone, PartialEq)]
274 pub struct UpdateFailHTLC {
275 pub(crate) channel_id: [u8; 32],
276 pub(crate) htlc_id: u64,
277 pub(crate) reason: OnionErrorPacket,
280 /// An update_fail_malformed_htlc message to be sent or received from a peer
281 #[derive(Clone, PartialEq)]
282 pub struct UpdateFailMalformedHTLC {
283 pub(crate) channel_id: [u8; 32],
284 pub(crate) htlc_id: u64,
285 pub(crate) sha256_of_onion: [u8; 32],
286 pub(crate) failure_code: u16,
289 /// A commitment_signed message to be sent or received from a peer
290 #[derive(Clone, PartialEq)]
291 pub struct CommitmentSigned {
292 pub(crate) channel_id: [u8; 32],
293 pub(crate) signature: Signature,
294 pub(crate) htlc_signatures: Vec<Signature>,
297 /// A revoke_and_ack message to be sent or received from a peer
298 #[derive(Clone, PartialEq)]
299 pub struct RevokeAndACK {
300 pub(crate) channel_id: [u8; 32],
301 pub(crate) per_commitment_secret: [u8; 32],
302 pub(crate) next_per_commitment_point: PublicKey,
305 /// An update_fee message to be sent or received from a peer
306 #[derive(PartialEq, Clone)]
307 pub struct UpdateFee {
308 pub(crate) channel_id: [u8; 32],
309 pub(crate) feerate_per_kw: u32,
312 #[derive(PartialEq, Clone)]
313 pub(crate) struct DataLossProtect {
314 pub(crate) your_last_per_commitment_secret: [u8; 32],
315 pub(crate) my_current_per_commitment_point: PublicKey,
318 /// A channel_reestablish message to be sent or received from a peer
319 #[derive(PartialEq, Clone)]
320 pub struct ChannelReestablish {
321 pub(crate) channel_id: [u8; 32],
322 pub(crate) next_local_commitment_number: u64,
323 pub(crate) next_remote_commitment_number: u64,
324 pub(crate) data_loss_protect: Option<DataLossProtect>,
327 /// An announcement_signatures message to be sent or received from a peer
329 pub struct AnnouncementSignatures {
330 pub(crate) channel_id: [u8; 32],
331 pub(crate) short_channel_id: u64,
332 pub(crate) node_signature: Signature,
333 pub(crate) bitcoin_signature: Signature,
336 /// An address which can be used to connect to a remote peer
338 pub enum NetAddress {
339 /// An IPv4 address/port on which the peer is listenting.
341 /// The 4-byte IPv4 address
343 /// The port on which the node is listenting
346 /// An IPv6 address/port on which the peer is listenting.
348 /// The 16-byte IPv6 address
350 /// The port on which the node is listenting
353 /// An old-style Tor onion address/port on which the peer is listening.
355 /// The bytes (usually encoded in base32 with ".onion" appended)
357 /// The port on which the node is listenting
360 /// A new-style Tor onion address/port on which the peer is listening.
361 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
362 /// wrap as base32 and append ".onion".
364 /// The ed25519 long-term public key of the peer
365 ed25519_pubkey: [u8; 32],
366 /// The checksum of the pubkey and version, as included in the onion address
368 /// The version byte, as defined by the Tor Onion v3 spec.
370 /// The port on which the node is listenting
375 fn get_id(&self) -> u8 {
377 &NetAddress::IPv4 {..} => { 1 },
378 &NetAddress::IPv6 {..} => { 2 },
379 &NetAddress::OnionV2 {..} => { 3 },
380 &NetAddress::OnionV3 {..} => { 4 },
385 // Only exposed as broadcast of node_announcement should be filtered by node_id
386 /// The unsigned part of a node_announcement
387 pub struct UnsignedNodeAnnouncement {
388 pub(crate) features: GlobalFeatures,
389 pub(crate) timestamp: u32,
390 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
392 pub node_id: PublicKey,
393 pub(crate) rgb: [u8; 3],
394 pub(crate) alias: [u8; 32],
395 /// List of addresses on which this node is reachable. Note that you may only have up to one
396 /// address of each type, if you have more, they may be silently discarded or we may panic!
397 pub(crate) addresses: Vec<NetAddress>,
398 pub(crate) excess_address_data: Vec<u8>,
399 pub(crate) excess_data: Vec<u8>,
401 /// A node_announcement message to be sent or received from a peer
402 pub struct NodeAnnouncement {
403 pub(crate) signature: Signature,
404 pub(crate) contents: UnsignedNodeAnnouncement,
407 // Only exposed as broadcast of channel_announcement should be filtered by node_id
408 /// The unsigned part of a channel_announcement
409 #[derive(PartialEq, Clone)]
410 pub struct UnsignedChannelAnnouncement {
411 pub(crate) features: GlobalFeatures,
412 pub(crate) chain_hash: Sha256dHash,
413 pub(crate) short_channel_id: u64,
414 /// One of the two node_ids which are endpoints of this channel
415 pub node_id_1: PublicKey,
416 /// The other of the two node_ids which are endpoints of this channel
417 pub node_id_2: PublicKey,
418 pub(crate) bitcoin_key_1: PublicKey,
419 pub(crate) bitcoin_key_2: PublicKey,
420 pub(crate) excess_data: Vec<u8>,
422 /// A channel_announcement message to be sent or received from a peer
423 #[derive(PartialEq, Clone)]
424 pub struct ChannelAnnouncement {
425 pub(crate) node_signature_1: Signature,
426 pub(crate) node_signature_2: Signature,
427 pub(crate) bitcoin_signature_1: Signature,
428 pub(crate) bitcoin_signature_2: Signature,
429 pub(crate) contents: UnsignedChannelAnnouncement,
432 #[derive(PartialEq, Clone)]
433 pub(crate) struct UnsignedChannelUpdate {
434 pub(crate) chain_hash: Sha256dHash,
435 pub(crate) short_channel_id: u64,
436 pub(crate) timestamp: u32,
437 pub(crate) flags: u16,
438 pub(crate) cltv_expiry_delta: u16,
439 pub(crate) htlc_minimum_msat: u64,
440 pub(crate) fee_base_msat: u32,
441 pub(crate) fee_proportional_millionths: u32,
442 pub(crate) excess_data: Vec<u8>,
444 /// A channel_update message to be sent or received from a peer
445 #[derive(PartialEq, Clone)]
446 pub struct ChannelUpdate {
447 pub(crate) signature: Signature,
448 pub(crate) contents: UnsignedChannelUpdate,
451 /// Used to put an error message in a HandleError
453 pub enum ErrorAction {
454 /// The peer took some action which made us think they were useless. Disconnect them.
456 /// An error message which we should make an effort to send before we disconnect.
457 msg: Option<ErrorMessage>
459 /// The peer did something harmless that we weren't able to process, just log and ignore
461 /// The peer did something incorrect. Tell them.
463 /// The message to send.
468 /// An Err type for failure to process messages.
469 pub struct HandleError { //TODO: rename me
470 /// A human-readable message describing the error
471 pub err: &'static str,
472 /// The action which should be taken against the offending peer.
473 pub action: Option<ErrorAction>, //TODO: Make this required
476 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
477 /// transaction updates if they were pending.
478 #[derive(PartialEq, Clone)]
479 pub struct CommitmentUpdate {
480 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
481 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
482 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
483 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
484 pub(crate) update_fee: Option<UpdateFee>,
485 pub(crate) commitment_signed: CommitmentSigned,
488 /// The information we received from a peer along the route of a payment we originated. This is
489 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
490 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
492 pub enum HTLCFailChannelUpdate {
493 /// We received an error which included a full ChannelUpdate message.
494 ChannelUpdateMessage {
495 /// The unwrapped message we received
498 /// We received an error which indicated only that a channel has been closed
500 /// The short_channel_id which has now closed.
501 short_channel_id: u64,
502 /// when this true, this channel should be permanently removed from the
503 /// consideration. Otherwise, this channel can be restored as new channel_update is received
506 /// We received an error which indicated only that a node has failed
508 /// The node_id that has failed.
510 /// when this true, node should be permanently removed from the
511 /// consideration. Otherwise, the channels connected to this node can be
512 /// restored as new channel_update is received
517 /// A trait to describe an object which can receive channel messages.
519 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
520 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
521 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
523 /// Handle an incoming open_channel message from the given peer.
524 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
525 /// Handle an incoming accept_channel message from the given peer.
526 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
527 /// Handle an incoming funding_created message from the given peer.
528 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
529 /// Handle an incoming funding_signed message from the given peer.
530 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
531 /// Handle an incoming funding_locked message from the given peer.
532 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
535 /// Handle an incoming shutdown message from the given peer.
536 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
537 /// Handle an incoming closing_signed message from the given peer.
538 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
541 /// Handle an incoming update_add_htlc message from the given peer.
542 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
543 /// Handle an incoming update_fulfill_htlc message from the given peer.
544 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
545 /// Handle an incoming update_fail_htlc message from the given peer.
546 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
547 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
548 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
549 /// Handle an incoming commitment_signed message from the given peer.
550 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
551 /// Handle an incoming revoke_and_ack message from the given peer.
552 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
554 /// Handle an incoming update_fee message from the given peer.
555 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
557 // Channel-to-announce:
558 /// Handle an incoming announcement_signatures message from the given peer.
559 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
561 // Connection loss/reestablish:
562 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
563 /// is believed to be possible in the future (eg they're sending us messages we don't
564 /// understand or indicate they require unknown feature bits), no_connection_possible is set
565 /// and any outstanding channels should be failed.
566 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
568 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
569 fn peer_connected(&self, their_node_id: &PublicKey);
570 /// Handle an incoming channel_reestablish message from the given peer.
571 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
574 /// Handle an incoming error message from the given peer.
575 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
578 /// A trait to describe an object which can receive routing messages.
579 pub trait RoutingMessageHandler : Send + Sync {
580 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
581 /// false or returning an Err otherwise.
582 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
583 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
584 /// or returning an Err otherwise.
585 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
586 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
587 /// false or returning an Err otherwise.
588 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
589 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
590 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
593 pub(crate) struct OnionRealm0HopData {
594 pub(crate) short_channel_id: u64,
595 pub(crate) amt_to_forward: u64,
596 pub(crate) outgoing_cltv_value: u32,
597 // 12 bytes of 0-padding
600 mod fuzzy_internal_msgs {
601 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
602 // them from untrusted input):
604 use super::OnionRealm0HopData;
605 pub struct OnionHopData {
606 pub(crate) realm: u8,
607 pub(crate) data: OnionRealm0HopData,
608 pub(crate) hmac: [u8; 32],
610 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
612 pub struct DecodedOnionErrorPacket {
613 pub(crate) hmac: [u8; 32],
614 pub(crate) failuremsg: Vec<u8>,
615 pub(crate) pad: Vec<u8>,
618 #[cfg(feature = "fuzztarget")]
619 pub use self::fuzzy_internal_msgs::*;
620 #[cfg(not(feature = "fuzztarget"))]
621 pub(crate) use self::fuzzy_internal_msgs::*;
624 pub(crate) struct OnionPacket {
625 pub(crate) version: u8,
626 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
627 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
628 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
629 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
630 pub(crate) hop_data: [u8; 20*65],
631 pub(crate) hmac: [u8; 32],
634 impl PartialEq for OnionPacket {
635 fn eq(&self, other: &OnionPacket) -> bool {
636 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
637 if i != j { return false; }
639 self.version == other.version &&
640 self.public_key == other.public_key &&
641 self.hmac == other.hmac
645 #[derive(Clone, PartialEq)]
646 pub(crate) struct OnionErrorPacket {
647 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
648 // (TODO) We limit it in decode to much lower...
649 pub(crate) data: Vec<u8>,
652 impl Error for DecodeError {
653 fn description(&self) -> &str {
655 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
656 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
657 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
658 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
659 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
660 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
661 DecodeError::Io(ref e) => e.description(),
665 impl fmt::Display for DecodeError {
666 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
667 f.write_str(self.description())
671 impl fmt::Debug for HandleError {
672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
673 f.write_str(self.err)
677 impl From<::std::io::Error> for DecodeError {
678 fn from(e: ::std::io::Error) -> Self {
679 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
680 DecodeError::ShortRead
687 impl_writeable_len_match!(AcceptChannel, {
688 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
691 temporary_channel_id,
693 max_htlc_value_in_flight_msat,
694 channel_reserve_satoshis,
700 revocation_basepoint,
702 delayed_payment_basepoint,
704 first_per_commitment_point,
705 shutdown_scriptpubkey
708 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
715 impl Writeable for ChannelReestablish {
716 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
717 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
718 self.channel_id.write(w)?;
719 self.next_local_commitment_number.write(w)?;
720 self.next_remote_commitment_number.write(w)?;
721 if let Some(ref data_loss_protect) = self.data_loss_protect {
722 data_loss_protect.your_last_per_commitment_secret.write(w)?;
723 data_loss_protect.my_current_per_commitment_point.write(w)?;
729 impl<R: Read> Readable<R> for ChannelReestablish{
730 fn read(r: &mut R) -> Result<Self, DecodeError> {
732 channel_id: Readable::read(r)?,
733 next_local_commitment_number: Readable::read(r)?,
734 next_remote_commitment_number: Readable::read(r)?,
736 match <[u8; 32] as Readable<R>>::read(r) {
737 Ok(your_last_per_commitment_secret) =>
738 Some(DataLossProtect {
739 your_last_per_commitment_secret,
740 my_current_per_commitment_point: Readable::read(r)?,
742 Err(DecodeError::ShortRead) => None,
743 Err(e) => return Err(e)
750 impl_writeable!(ClosingSigned, 32+8+64, {
756 impl_writeable_len_match!(CommitmentSigned, {
757 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
764 impl_writeable_len_match!(DecodedOnionErrorPacket, {
765 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
772 impl_writeable!(FundingCreated, 32+32+2+64, {
773 temporary_channel_id,
775 funding_output_index,
779 impl_writeable!(FundingSigned, 32+64, {
784 impl_writeable!(FundingLocked, 32+33, {
786 next_per_commitment_point
789 impl_writeable_len_match!(GlobalFeatures, {
790 { GlobalFeatures { ref flags }, flags.len() + 2 }
795 impl_writeable_len_match!(LocalFeatures, {
796 { LocalFeatures { ref flags }, flags.len() + 2 }
801 impl_writeable_len_match!(Init, {
802 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
808 impl_writeable_len_match!(OpenChannel, {
809 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
810 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
813 temporary_channel_id,
817 max_htlc_value_in_flight_msat,
818 channel_reserve_satoshis,
824 revocation_basepoint,
826 delayed_payment_basepoint,
828 first_per_commitment_point,
830 shutdown_scriptpubkey
833 impl_writeable!(RevokeAndACK, 32+32+33, {
835 per_commitment_secret,
836 next_per_commitment_point
839 impl_writeable_len_match!(Shutdown, {
840 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
846 impl_writeable_len_match!(UpdateFailHTLC, {
847 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
854 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
861 impl_writeable!(UpdateFee, 32+4, {
866 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
872 impl_writeable_len_match!(OnionErrorPacket, {
873 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
878 impl Writeable for OnionPacket {
879 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
880 w.size_hint(1 + 33 + 20*65 + 32);
881 self.version.write(w)?;
882 match self.public_key {
883 Ok(pubkey) => pubkey.write(w)?,
884 Err(_) => [0u8;33].write(w)?,
886 w.write_all(&self.hop_data)?;
892 impl<R: Read> Readable<R> for OnionPacket {
893 fn read(r: &mut R) -> Result<Self, DecodeError> {
895 version: Readable::read(r)?,
897 let mut buf = [0u8;33];
898 r.read_exact(&mut buf)?;
899 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
901 hop_data: Readable::read(r)?,
902 hmac: Readable::read(r)?,
907 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
916 impl Writeable for OnionRealm0HopData {
917 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
919 self.short_channel_id.write(w)?;
920 self.amt_to_forward.write(w)?;
921 self.outgoing_cltv_value.write(w)?;
922 w.write_all(&[0;12])?;
927 impl<R: Read> Readable<R> for OnionRealm0HopData {
928 fn read(r: &mut R) -> Result<Self, DecodeError> {
929 Ok(OnionRealm0HopData {
930 short_channel_id: Readable::read(r)?,
931 amt_to_forward: Readable::read(r)?,
932 outgoing_cltv_value: {
933 let v: u32 = Readable::read(r)?;
934 r.read_exact(&mut [0; 12])?;
941 impl Writeable for OnionHopData {
942 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
944 self.realm.write(w)?;
951 impl<R: Read> Readable<R> for OnionHopData {
952 fn read(r: &mut R) -> Result<Self, DecodeError> {
955 let r: u8 = Readable::read(r)?;
957 return Err(DecodeError::UnknownVersion);
961 data: Readable::read(r)?,
962 hmac: Readable::read(r)?,
967 impl Writeable for Ping {
968 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
969 w.size_hint(self.byteslen as usize + 4);
970 self.ponglen.write(w)?;
971 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
976 impl<R: Read> Readable<R> for Ping {
977 fn read(r: &mut R) -> Result<Self, DecodeError> {
979 ponglen: Readable::read(r)?,
981 let byteslen = Readable::read(r)?;
982 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
989 impl Writeable for Pong {
990 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
991 w.size_hint(self.byteslen as usize + 2);
992 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
997 impl<R: Read> Readable<R> for Pong {
998 fn read(r: &mut R) -> Result<Self, DecodeError> {
1001 let byteslen = Readable::read(r)?;
1002 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1009 impl Writeable for UnsignedChannelAnnouncement {
1010 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1011 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1012 self.features.write(w)?;
1013 self.chain_hash.write(w)?;
1014 self.short_channel_id.write(w)?;
1015 self.node_id_1.write(w)?;
1016 self.node_id_2.write(w)?;
1017 self.bitcoin_key_1.write(w)?;
1018 self.bitcoin_key_2.write(w)?;
1019 w.write_all(&self.excess_data[..])?;
1024 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1025 fn read(r: &mut R) -> Result<Self, DecodeError> {
1028 let f: GlobalFeatures = Readable::read(r)?;
1029 if f.requires_unknown_bits() {
1030 return Err(DecodeError::UnknownRequiredFeature);
1034 chain_hash: Readable::read(r)?,
1035 short_channel_id: Readable::read(r)?,
1036 node_id_1: Readable::read(r)?,
1037 node_id_2: Readable::read(r)?,
1038 bitcoin_key_1: Readable::read(r)?,
1039 bitcoin_key_2: Readable::read(r)?,
1041 let mut excess_data = vec![];
1042 r.read_to_end(&mut excess_data)?;
1049 impl_writeable_len_match!(ChannelAnnouncement, {
1050 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1051 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1055 bitcoin_signature_1,
1056 bitcoin_signature_2,
1060 impl Writeable for UnsignedChannelUpdate {
1061 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1062 w.size_hint(64 + self.excess_data.len());
1063 self.chain_hash.write(w)?;
1064 self.short_channel_id.write(w)?;
1065 self.timestamp.write(w)?;
1066 self.flags.write(w)?;
1067 self.cltv_expiry_delta.write(w)?;
1068 self.htlc_minimum_msat.write(w)?;
1069 self.fee_base_msat.write(w)?;
1070 self.fee_proportional_millionths.write(w)?;
1071 w.write_all(&self.excess_data[..])?;
1076 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1077 fn read(r: &mut R) -> Result<Self, DecodeError> {
1079 chain_hash: Readable::read(r)?,
1080 short_channel_id: Readable::read(r)?,
1081 timestamp: Readable::read(r)?,
1082 flags: Readable::read(r)?,
1083 cltv_expiry_delta: Readable::read(r)?,
1084 htlc_minimum_msat: Readable::read(r)?,
1085 fee_base_msat: Readable::read(r)?,
1086 fee_proportional_millionths: Readable::read(r)?,
1088 let mut excess_data = vec![];
1089 r.read_to_end(&mut excess_data)?;
1096 impl_writeable_len_match!(ChannelUpdate, {
1097 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1098 64 + excess_data.len() + 64 }
1104 impl Writeable for ErrorMessage {
1105 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1106 w.size_hint(32 + 2 + self.data.len());
1107 self.channel_id.write(w)?;
1108 (self.data.len() as u16).write(w)?;
1109 w.write_all(self.data.as_bytes())?;
1114 impl<R: Read> Readable<R> for ErrorMessage {
1115 fn read(r: &mut R) -> Result<Self, DecodeError> {
1117 channel_id: Readable::read(r)?,
1119 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1120 let mut data = vec![];
1121 let data_len = r.read_to_end(&mut data)?;
1122 sz = cmp::min(data_len, sz);
1123 match String::from_utf8(data[..sz as usize].to_vec()) {
1125 Err(_) => return Err(DecodeError::InvalidValue),
1132 impl Writeable for UnsignedNodeAnnouncement {
1133 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1134 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1135 self.features.write(w)?;
1136 self.timestamp.write(w)?;
1137 self.node_id.write(w)?;
1138 w.write_all(&self.rgb)?;
1139 self.alias.write(w)?;
1141 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1142 let mut addrs_to_encode = self.addresses.clone();
1143 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1144 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1145 for addr in addrs_to_encode.iter() {
1147 &NetAddress::IPv4{addr, port} => {
1149 addr_slice.extend_from_slice(&addr);
1150 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1152 &NetAddress::IPv6{addr, port} => {
1154 addr_slice.extend_from_slice(&addr);
1155 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1157 &NetAddress::OnionV2{addr, port} => {
1159 addr_slice.extend_from_slice(&addr);
1160 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1162 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1164 addr_slice.extend_from_slice(&ed25519_pubkey);
1165 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1166 addr_slice.push(version);
1167 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1171 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1172 w.write_all(&addr_slice[..])?;
1173 w.write_all(&self.excess_address_data[..])?;
1174 w.write_all(&self.excess_data[..])?;
1179 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1180 fn read(r: &mut R) -> Result<Self, DecodeError> {
1181 let features: GlobalFeatures = Readable::read(r)?;
1182 if features.requires_unknown_bits() {
1183 return Err(DecodeError::UnknownRequiredFeature);
1185 let timestamp: u32 = Readable::read(r)?;
1186 let node_id: PublicKey = Readable::read(r)?;
1187 let mut rgb = [0; 3];
1188 r.read_exact(&mut rgb)?;
1189 let alias: [u8; 32] = Readable::read(r)?;
1191 let addrlen: u16 = Readable::read(r)?;
1192 let mut addr_readpos = 0;
1193 let mut addresses = Vec::with_capacity(4);
1197 if addrlen <= addr_readpos { break; }
1198 f = Readable::read(r)?;
1201 if addresses.len() > 0 {
1202 return Err(DecodeError::ExtraAddressesPerType);
1204 if addrlen < addr_readpos + 1 + 6 {
1205 return Err(DecodeError::BadLengthDescriptor);
1207 addresses.push(NetAddress::IPv4 {
1209 let mut addr = [0; 4];
1210 r.read_exact(&mut addr)?;
1213 port: Readable::read(r)?,
1215 addr_readpos += 1 + 6
1218 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1219 return Err(DecodeError::ExtraAddressesPerType);
1221 if addrlen < addr_readpos + 1 + 18 {
1222 return Err(DecodeError::BadLengthDescriptor);
1224 addresses.push(NetAddress::IPv6 {
1226 let mut addr = [0; 16];
1227 r.read_exact(&mut addr)?;
1230 port: Readable::read(r)?,
1232 addr_readpos += 1 + 18
1235 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1236 return Err(DecodeError::ExtraAddressesPerType);
1238 if addrlen < addr_readpos + 1 + 12 {
1239 return Err(DecodeError::BadLengthDescriptor);
1241 addresses.push(NetAddress::OnionV2 {
1243 let mut addr = [0; 10];
1244 r.read_exact(&mut addr)?;
1247 port: Readable::read(r)?,
1249 addr_readpos += 1 + 12
1252 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1253 return Err(DecodeError::ExtraAddressesPerType);
1255 if addrlen < addr_readpos + 1 + 37 {
1256 return Err(DecodeError::BadLengthDescriptor);
1258 addresses.push(NetAddress::OnionV3 {
1259 ed25519_pubkey: Readable::read(r)?,
1260 checksum: Readable::read(r)?,
1261 version: Readable::read(r)?,
1262 port: Readable::read(r)?,
1264 addr_readpos += 1 + 37
1266 _ => { excess = 1; break; }
1270 let mut excess_data = vec![];
1271 let excess_address_data = if addr_readpos < addrlen {
1272 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1273 r.read_exact(&mut excess_address_data[excess..])?;
1275 excess_address_data[0] = f;
1280 excess_data.push(f);
1285 Ok(UnsignedNodeAnnouncement {
1287 timestamp: timestamp,
1291 addresses: addresses,
1292 excess_address_data: excess_address_data,
1294 r.read_to_end(&mut excess_data)?;
1301 impl_writeable_len_match!(NodeAnnouncement, {
1302 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1303 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1313 use util::ser::Writeable;
1314 use secp256k1::key::{PublicKey,SecretKey};
1315 use secp256k1::Secp256k1;
1318 fn encoding_channel_reestablish_no_secret() {
1319 let cr = msgs::ChannelReestablish {
1320 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],
1321 next_local_commitment_number: 3,
1322 next_remote_commitment_number: 4,
1323 data_loss_protect: None,
1326 let encoded_value = cr.encode();
1329 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]
1334 fn encoding_channel_reestablish_with_secret() {
1336 let secp_ctx = Secp256k1::new();
1337 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1340 let cr = msgs::ChannelReestablish {
1341 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],
1342 next_local_commitment_number: 3,
1343 next_remote_commitment_number: 4,
1344 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1347 let encoded_value = cr.encode();
1350 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]