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;
30 use util::ser::{Readable, Writeable, Writer};
32 use ln::channelmanager::{PaymentPreimage, PaymentHash};
34 /// An error in decoding a message or struct.
36 pub enum DecodeError {
37 /// A version byte specified something we don't know how to handle.
38 /// Includes unknown realm byte in an OnionHopData packet
40 /// Unknown feature mandating we fail to parse message
41 UnknownRequiredFeature,
42 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
43 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
47 /// node_announcement included more than one address of a given type!
48 ExtraAddressesPerType,
49 /// A length descriptor in the packet didn't describe the later data correctly
51 /// Error from std::io
55 /// Tracks localfeatures which are only in init messages
56 #[derive(Clone, PartialEq)]
57 pub struct LocalFeatures {
62 pub(crate) fn new() -> LocalFeatures {
68 pub(crate) fn supports_data_loss_protect(&self) -> bool {
69 self.flags.len() > 0 && (self.flags[0] & 3) != 0
71 pub(crate) fn requires_data_loss_protect(&self) -> bool {
72 self.flags.len() > 0 && (self.flags[0] & 1) != 0
75 pub(crate) fn initial_routing_sync(&self) -> bool {
76 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
78 pub(crate) fn set_initial_routing_sync(&mut self) {
79 if self.flags.len() == 0 {
80 self.flags.resize(1, 1 << 3);
82 self.flags[0] |= 1 << 3;
86 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
87 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
89 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
90 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
93 pub(crate) fn requires_unknown_bits(&self) -> bool {
94 for (idx, &byte) in self.flags.iter().enumerate() {
95 if idx != 0 && (byte & 0x55) != 0 {
97 } else if idx == 0 && (byte & 0x14) != 0 {
104 pub(crate) fn supports_unknown_bits(&self) -> bool {
105 for (idx, &byte) in self.flags.iter().enumerate() {
106 if idx != 0 && byte != 0 {
108 } else if idx == 0 && (byte & 0xc4) != 0 {
116 /// Tracks globalfeatures which are in init messages and routing announcements
117 #[derive(Clone, PartialEq)]
118 pub struct GlobalFeatures {
122 impl GlobalFeatures {
123 pub(crate) fn new() -> GlobalFeatures {
129 pub(crate) fn requires_unknown_bits(&self) -> bool {
130 for &byte in self.flags.iter() {
131 if (byte & 0x55) != 0 {
138 pub(crate) fn supports_unknown_bits(&self) -> bool {
139 for &byte in self.flags.iter() {
148 /// An init message to be sent or received from a peer
150 pub(crate) global_features: GlobalFeatures,
151 pub(crate) local_features: LocalFeatures,
154 /// An error message to be sent or received from a peer
156 pub struct ErrorMessage {
157 pub(crate) channel_id: [u8; 32],
158 pub(crate) data: String,
161 /// A ping message to be sent or received from a peer
163 pub(crate) ponglen: u16,
164 pub(crate) byteslen: u16,
167 /// A pong message to be sent or received from a peer
169 pub(crate) byteslen: u16,
172 /// An open_channel message to be sent or received from a peer
174 pub struct OpenChannel {
175 pub(crate) chain_hash: Sha256dHash,
176 pub(crate) temporary_channel_id: [u8; 32],
177 pub(crate) funding_satoshis: u64,
178 pub(crate) push_msat: u64,
179 pub(crate) dust_limit_satoshis: u64,
180 pub(crate) max_htlc_value_in_flight_msat: u64,
181 pub(crate) channel_reserve_satoshis: u64,
182 pub(crate) htlc_minimum_msat: u64,
183 pub(crate) feerate_per_kw: u32,
184 pub(crate) to_self_delay: u16,
185 pub(crate) max_accepted_htlcs: u16,
186 pub(crate) funding_pubkey: PublicKey,
187 pub(crate) revocation_basepoint: PublicKey,
188 pub(crate) payment_basepoint: PublicKey,
189 pub(crate) delayed_payment_basepoint: PublicKey,
190 pub(crate) htlc_basepoint: PublicKey,
191 pub(crate) first_per_commitment_point: PublicKey,
192 pub(crate) channel_flags: u8,
193 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
196 /// An accept_channel message to be sent or received from a peer
198 pub struct AcceptChannel {
199 pub(crate) temporary_channel_id: [u8; 32],
200 pub(crate) dust_limit_satoshis: u64,
201 pub(crate) max_htlc_value_in_flight_msat: u64,
202 pub(crate) channel_reserve_satoshis: u64,
203 pub(crate) htlc_minimum_msat: u64,
204 pub(crate) minimum_depth: u32,
205 pub(crate) to_self_delay: u16,
206 pub(crate) max_accepted_htlcs: u16,
207 pub(crate) funding_pubkey: PublicKey,
208 pub(crate) revocation_basepoint: PublicKey,
209 pub(crate) payment_basepoint: PublicKey,
210 pub(crate) delayed_payment_basepoint: PublicKey,
211 pub(crate) htlc_basepoint: PublicKey,
212 pub(crate) first_per_commitment_point: PublicKey,
213 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
216 /// A funding_created message to be sent or received from a peer
218 pub struct FundingCreated {
219 pub(crate) temporary_channel_id: [u8; 32],
220 pub(crate) funding_txid: Sha256dHash,
221 pub(crate) funding_output_index: u16,
222 pub(crate) signature: Signature,
225 /// A funding_signed message to be sent or received from a peer
227 pub struct FundingSigned {
228 pub(crate) channel_id: [u8; 32],
229 pub(crate) signature: Signature,
232 /// A funding_locked message to be sent or received from a peer
233 #[derive(Clone, PartialEq)]
234 pub struct FundingLocked {
235 pub(crate) channel_id: [u8; 32],
236 pub(crate) next_per_commitment_point: PublicKey,
239 /// A shutdown message to be sent or received from a peer
240 #[derive(Clone, PartialEq)]
241 pub struct Shutdown {
242 pub(crate) channel_id: [u8; 32],
243 pub(crate) scriptpubkey: Script,
246 /// A closing_signed message to be sent or received from a peer
247 #[derive(Clone, PartialEq)]
248 pub struct ClosingSigned {
249 pub(crate) channel_id: [u8; 32],
250 pub(crate) fee_satoshis: u64,
251 pub(crate) signature: Signature,
254 /// An update_add_htlc message to be sent or received from a peer
255 #[derive(Clone, PartialEq)]
256 pub struct UpdateAddHTLC {
257 pub(crate) channel_id: [u8; 32],
258 pub(crate) htlc_id: u64,
259 pub(crate) amount_msat: u64,
260 pub(crate) payment_hash: PaymentHash,
261 pub(crate) cltv_expiry: u32,
262 pub(crate) onion_routing_packet: OnionPacket,
265 /// An update_fulfill_htlc message to be sent or received from a peer
266 #[derive(Clone, PartialEq)]
267 pub struct UpdateFulfillHTLC {
268 pub(crate) channel_id: [u8; 32],
269 pub(crate) htlc_id: u64,
270 pub(crate) payment_preimage: PaymentPreimage,
273 /// An update_fail_htlc message to be sent or received from a peer
274 #[derive(Clone, PartialEq)]
275 pub struct UpdateFailHTLC {
276 pub(crate) channel_id: [u8; 32],
277 pub(crate) htlc_id: u64,
278 pub(crate) reason: OnionErrorPacket,
281 /// An update_fail_malformed_htlc message to be sent or received from a peer
282 #[derive(Clone, PartialEq)]
283 pub struct UpdateFailMalformedHTLC {
284 pub(crate) channel_id: [u8; 32],
285 pub(crate) htlc_id: u64,
286 pub(crate) sha256_of_onion: [u8; 32],
287 pub(crate) failure_code: u16,
290 /// A commitment_signed message to be sent or received from a peer
291 #[derive(Clone, PartialEq)]
292 pub struct CommitmentSigned {
293 pub(crate) channel_id: [u8; 32],
294 pub(crate) signature: Signature,
295 pub(crate) htlc_signatures: Vec<Signature>,
298 /// A revoke_and_ack message to be sent or received from a peer
299 #[derive(Clone, PartialEq)]
300 pub struct RevokeAndACK {
301 pub(crate) channel_id: [u8; 32],
302 pub(crate) per_commitment_secret: [u8; 32],
303 pub(crate) next_per_commitment_point: PublicKey,
306 /// An update_fee message to be sent or received from a peer
307 #[derive(PartialEq, Clone)]
308 pub struct UpdateFee {
309 pub(crate) channel_id: [u8; 32],
310 pub(crate) feerate_per_kw: u32,
313 #[derive(PartialEq, Clone)]
314 pub(crate) struct DataLossProtect {
315 pub(crate) your_last_per_commitment_secret: [u8; 32],
316 pub(crate) my_current_per_commitment_point: PublicKey,
319 /// A channel_reestablish message to be sent or received from a peer
320 #[derive(PartialEq, Clone)]
321 pub struct ChannelReestablish {
322 pub(crate) channel_id: [u8; 32],
323 pub(crate) next_local_commitment_number: u64,
324 pub(crate) next_remote_commitment_number: u64,
325 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
328 /// An announcement_signatures message to be sent or received from a peer
330 pub struct AnnouncementSignatures {
331 pub(crate) channel_id: [u8; 32],
332 pub(crate) short_channel_id: u64,
333 pub(crate) node_signature: Signature,
334 pub(crate) bitcoin_signature: Signature,
337 /// An address which can be used to connect to a remote peer
338 #[derive(PartialEq, Clone)]
339 pub enum NetAddress {
340 /// An IPv4 address/port on which the peer is listenting.
342 /// The 4-byte IPv4 address
344 /// The port on which the node is listenting
347 /// An IPv6 address/port on which the peer is listenting.
349 /// The 16-byte IPv6 address
351 /// The port on which the node is listenting
354 /// An old-style Tor onion address/port on which the peer is listening.
356 /// The bytes (usually encoded in base32 with ".onion" appended)
358 /// The port on which the node is listenting
361 /// A new-style Tor onion address/port on which the peer is listening.
362 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
363 /// wrap as base32 and append ".onion".
365 /// The ed25519 long-term public key of the peer
366 ed25519_pubkey: [u8; 32],
367 /// The checksum of the pubkey and version, as included in the onion address
369 /// The version byte, as defined by the Tor Onion v3 spec.
371 /// The port on which the node is listenting
376 fn get_id(&self) -> u8 {
378 &NetAddress::IPv4 {..} => { 1 },
379 &NetAddress::IPv6 {..} => { 2 },
380 &NetAddress::OnionV2 {..} => { 3 },
381 &NetAddress::OnionV3 {..} => { 4 },
385 /// Strict byte-length of address descriptor, 1-byte type not recorded
386 fn len(&self) -> u16 {
388 &NetAddress::IPv4 { .. } => { 6 },
389 &NetAddress::IPv6 { .. } => { 18 },
390 &NetAddress::OnionV2 { .. } => { 12 },
391 &NetAddress::OnionV3 { .. } => { 37 },
396 impl Writeable for NetAddress {
397 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
399 &NetAddress::IPv4 { ref addr, ref port } => {
404 &NetAddress::IPv6 { ref addr, ref port } => {
409 &NetAddress::OnionV2 { ref addr, ref port } => {
414 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
416 ed25519_pubkey.write(writer)?;
417 checksum.write(writer)?;
418 version.write(writer)?;
426 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
427 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
428 let byte = <u8 as Readable<R>>::read(reader)?;
431 Ok(Ok(NetAddress::IPv4 {
432 addr: Readable::read(reader)?,
433 port: Readable::read(reader)?,
437 Ok(Ok(NetAddress::IPv6 {
438 addr: Readable::read(reader)?,
439 port: Readable::read(reader)?,
443 Ok(Ok(NetAddress::OnionV2 {
444 addr: Readable::read(reader)?,
445 port: Readable::read(reader)?,
449 Ok(Ok(NetAddress::OnionV3 {
450 ed25519_pubkey: Readable::read(reader)?,
451 checksum: Readable::read(reader)?,
452 version: Readable::read(reader)?,
453 port: Readable::read(reader)?,
456 _ => return Ok(Err(byte)),
461 #[derive(PartialEq, Clone)]
462 // Only exposed as broadcast of node_announcement should be filtered by node_id
463 /// The unsigned part of a node_announcement
464 pub struct UnsignedNodeAnnouncement {
465 pub(crate) features: GlobalFeatures,
466 pub(crate) timestamp: u32,
467 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
469 pub node_id: PublicKey,
470 pub(crate) rgb: [u8; 3],
471 pub(crate) alias: [u8; 32],
472 /// List of addresses on which this node is reachable. Note that you may only have up to one
473 /// address of each type, if you have more, they may be silently discarded or we may panic!
474 pub(crate) addresses: Vec<NetAddress>,
475 pub(crate) excess_address_data: Vec<u8>,
476 pub(crate) excess_data: Vec<u8>,
478 #[derive(PartialEq, Clone)]
479 /// A node_announcement message to be sent or received from a peer
480 pub struct NodeAnnouncement {
481 pub(crate) signature: Signature,
482 pub(crate) contents: UnsignedNodeAnnouncement,
485 // Only exposed as broadcast of channel_announcement should be filtered by node_id
486 /// The unsigned part of a channel_announcement
487 #[derive(PartialEq, Clone)]
488 pub struct UnsignedChannelAnnouncement {
489 pub(crate) features: GlobalFeatures,
490 pub(crate) chain_hash: Sha256dHash,
491 pub(crate) short_channel_id: u64,
492 /// One of the two node_ids which are endpoints of this channel
493 pub node_id_1: PublicKey,
494 /// The other of the two node_ids which are endpoints of this channel
495 pub node_id_2: PublicKey,
496 pub(crate) bitcoin_key_1: PublicKey,
497 pub(crate) bitcoin_key_2: PublicKey,
498 pub(crate) excess_data: Vec<u8>,
500 /// A channel_announcement message to be sent or received from a peer
501 #[derive(PartialEq, Clone)]
502 pub struct ChannelAnnouncement {
503 pub(crate) node_signature_1: Signature,
504 pub(crate) node_signature_2: Signature,
505 pub(crate) bitcoin_signature_1: Signature,
506 pub(crate) bitcoin_signature_2: Signature,
507 pub(crate) contents: UnsignedChannelAnnouncement,
510 #[derive(PartialEq, Clone)]
511 pub(crate) struct UnsignedChannelUpdate {
512 pub(crate) chain_hash: Sha256dHash,
513 pub(crate) short_channel_id: u64,
514 pub(crate) timestamp: u32,
515 pub(crate) flags: u16,
516 pub(crate) cltv_expiry_delta: u16,
517 pub(crate) htlc_minimum_msat: u64,
518 pub(crate) fee_base_msat: u32,
519 pub(crate) fee_proportional_millionths: u32,
520 pub(crate) excess_data: Vec<u8>,
522 /// A channel_update message to be sent or received from a peer
523 #[derive(PartialEq, Clone)]
524 pub struct ChannelUpdate {
525 pub(crate) signature: Signature,
526 pub(crate) contents: UnsignedChannelUpdate,
529 /// Used to put an error message in a HandleError
531 pub enum ErrorAction {
532 /// The peer took some action which made us think they were useless. Disconnect them.
534 /// An error message which we should make an effort to send before we disconnect.
535 msg: Option<ErrorMessage>
537 /// The peer did something harmless that we weren't able to process, just log and ignore
539 /// The peer did something incorrect. Tell them.
541 /// The message to send.
546 /// An Err type for failure to process messages.
547 pub struct HandleError { //TODO: rename me
548 /// A human-readable message describing the error
549 pub err: &'static str,
550 /// The action which should be taken against the offending peer.
551 pub action: Option<ErrorAction>, //TODO: Make this required
554 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
555 /// transaction updates if they were pending.
556 #[derive(PartialEq, Clone)]
557 pub struct CommitmentUpdate {
558 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
559 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
560 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
561 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
562 pub(crate) update_fee: Option<UpdateFee>,
563 pub(crate) commitment_signed: CommitmentSigned,
566 /// The information we received from a peer along the route of a payment we originated. This is
567 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
568 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
570 pub enum HTLCFailChannelUpdate {
571 /// We received an error which included a full ChannelUpdate message.
572 ChannelUpdateMessage {
573 /// The unwrapped message we received
576 /// We received an error which indicated only that a channel has been closed
578 /// The short_channel_id which has now closed.
579 short_channel_id: u64,
580 /// when this true, this channel should be permanently removed from the
581 /// consideration. Otherwise, this channel can be restored as new channel_update is received
584 /// We received an error which indicated only that a node has failed
586 /// The node_id that has failed.
588 /// when this true, node should be permanently removed from the
589 /// consideration. Otherwise, the channels connected to this node can be
590 /// restored as new channel_update is received
595 /// Messages could have optional fields to use with extended features
596 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
597 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
598 /// separate enum type for them.
599 #[derive(Clone, PartialEq)]
600 pub enum OptionalField<T> {
601 /// Optional field is included in message
603 /// Optional field is absent in message
607 /// A trait to describe an object which can receive channel messages.
609 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
610 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
611 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
613 /// Handle an incoming open_channel message from the given peer.
614 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
615 /// Handle an incoming accept_channel message from the given peer.
616 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
617 /// Handle an incoming funding_created message from the given peer.
618 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
619 /// Handle an incoming funding_signed message from the given peer.
620 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
621 /// Handle an incoming funding_locked message from the given peer.
622 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
625 /// Handle an incoming shutdown message from the given peer.
626 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
627 /// Handle an incoming closing_signed message from the given peer.
628 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
631 /// Handle an incoming update_add_htlc message from the given peer.
632 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
633 /// Handle an incoming update_fulfill_htlc message from the given peer.
634 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
635 /// Handle an incoming update_fail_htlc message from the given peer.
636 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
637 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
638 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
639 /// Handle an incoming commitment_signed message from the given peer.
640 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
641 /// Handle an incoming revoke_and_ack message from the given peer.
642 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
644 /// Handle an incoming update_fee message from the given peer.
645 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
647 // Channel-to-announce:
648 /// Handle an incoming announcement_signatures message from the given peer.
649 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
651 // Connection loss/reestablish:
652 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
653 /// is believed to be possible in the future (eg they're sending us messages we don't
654 /// understand or indicate they require unknown feature bits), no_connection_possible is set
655 /// and any outstanding channels should be failed.
656 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
658 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
659 fn peer_connected(&self, their_node_id: &PublicKey);
660 /// Handle an incoming channel_reestablish message from the given peer.
661 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
664 /// Handle an incoming error message from the given peer.
665 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
668 /// A trait to describe an object which can receive routing messages.
669 pub trait RoutingMessageHandler : Send + Sync {
670 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
671 /// false or returning an Err otherwise.
672 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
673 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
674 /// or returning an Err otherwise.
675 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
676 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
677 /// false or returning an Err otherwise.
678 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
679 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
680 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
681 /// Gets a subset of the channel announcements and updates required to dump our routing table
682 /// to a remote node, starting at the short_channel_id indicated by starting_point and
683 /// including batch_amount entries.
684 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
685 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
686 /// starting at the node *after* the provided publickey and including batch_amount entries.
687 /// If None is provided for starting_point, we start at the first node.
688 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
691 pub(crate) struct OnionRealm0HopData {
692 pub(crate) short_channel_id: u64,
693 pub(crate) amt_to_forward: u64,
694 pub(crate) outgoing_cltv_value: u32,
695 // 12 bytes of 0-padding
698 mod fuzzy_internal_msgs {
699 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
700 // them from untrusted input):
702 use super::OnionRealm0HopData;
703 pub struct OnionHopData {
704 pub(crate) realm: u8,
705 pub(crate) data: OnionRealm0HopData,
706 pub(crate) hmac: [u8; 32],
708 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
710 pub struct DecodedOnionErrorPacket {
711 pub(crate) hmac: [u8; 32],
712 pub(crate) failuremsg: Vec<u8>,
713 pub(crate) pad: Vec<u8>,
716 #[cfg(feature = "fuzztarget")]
717 pub use self::fuzzy_internal_msgs::*;
718 #[cfg(not(feature = "fuzztarget"))]
719 pub(crate) use self::fuzzy_internal_msgs::*;
722 pub(crate) struct OnionPacket {
723 pub(crate) version: u8,
724 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
725 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
726 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
727 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
728 pub(crate) hop_data: [u8; 20*65],
729 pub(crate) hmac: [u8; 32],
732 impl PartialEq for OnionPacket {
733 fn eq(&self, other: &OnionPacket) -> bool {
734 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
735 if i != j { return false; }
737 self.version == other.version &&
738 self.public_key == other.public_key &&
739 self.hmac == other.hmac
743 #[derive(Clone, PartialEq)]
744 pub(crate) struct OnionErrorPacket {
745 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
746 // (TODO) We limit it in decode to much lower...
747 pub(crate) data: Vec<u8>,
750 impl Error for DecodeError {
751 fn description(&self) -> &str {
753 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
754 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
755 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
756 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
757 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
758 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
759 DecodeError::Io(ref e) => e.description(),
763 impl fmt::Display for DecodeError {
764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
765 f.write_str(self.description())
769 impl fmt::Debug for HandleError {
770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 f.write_str(self.err)
775 impl From<::std::io::Error> for DecodeError {
776 fn from(e: ::std::io::Error) -> Self {
777 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
778 DecodeError::ShortRead
785 impl Writeable for OptionalField<Script> {
786 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
788 OptionalField::Present(ref script) => {
789 // Note that Writeable for script includes the 16-bit length tag for us
792 OptionalField::Absent => {}
798 impl<R: Read> Readable<R> for OptionalField<Script> {
799 fn read(r: &mut R) -> Result<Self, DecodeError> {
800 match <u16 as Readable<R>>::read(r) {
802 let mut buf = vec![0; len as usize];
803 r.read_exact(&mut buf)?;
804 Ok(OptionalField::Present(Script::from(buf)))
806 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
812 impl_writeable_len_match!(AcceptChannel, {
813 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
816 temporary_channel_id,
818 max_htlc_value_in_flight_msat,
819 channel_reserve_satoshis,
825 revocation_basepoint,
827 delayed_payment_basepoint,
829 first_per_commitment_point,
830 shutdown_scriptpubkey
833 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
840 impl Writeable for ChannelReestablish {
841 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
842 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
843 self.channel_id.write(w)?;
844 self.next_local_commitment_number.write(w)?;
845 self.next_remote_commitment_number.write(w)?;
846 match self.data_loss_protect {
847 OptionalField::Present(ref data_loss_protect) => {
848 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
849 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
851 OptionalField::Absent => {}
857 impl<R: Read> Readable<R> for ChannelReestablish{
858 fn read(r: &mut R) -> Result<Self, DecodeError> {
860 channel_id: Readable::read(r)?,
861 next_local_commitment_number: Readable::read(r)?,
862 next_remote_commitment_number: Readable::read(r)?,
864 match <[u8; 32] as Readable<R>>::read(r) {
865 Ok(your_last_per_commitment_secret) =>
866 OptionalField::Present(DataLossProtect {
867 your_last_per_commitment_secret,
868 my_current_per_commitment_point: Readable::read(r)?,
870 Err(DecodeError::ShortRead) => OptionalField::Absent,
871 Err(e) => return Err(e)
878 impl_writeable!(ClosingSigned, 32+8+64, {
884 impl_writeable_len_match!(CommitmentSigned, {
885 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
892 impl_writeable_len_match!(DecodedOnionErrorPacket, {
893 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
900 impl_writeable!(FundingCreated, 32+32+2+64, {
901 temporary_channel_id,
903 funding_output_index,
907 impl_writeable!(FundingSigned, 32+64, {
912 impl_writeable!(FundingLocked, 32+33, {
914 next_per_commitment_point
917 impl_writeable_len_match!(GlobalFeatures, {
918 { GlobalFeatures { ref flags }, flags.len() + 2 }
923 impl_writeable_len_match!(LocalFeatures, {
924 { LocalFeatures { ref flags }, flags.len() + 2 }
929 impl_writeable_len_match!(Init, {
930 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
936 impl_writeable_len_match!(OpenChannel, {
937 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
941 temporary_channel_id,
945 max_htlc_value_in_flight_msat,
946 channel_reserve_satoshis,
952 revocation_basepoint,
954 delayed_payment_basepoint,
956 first_per_commitment_point,
958 shutdown_scriptpubkey
961 impl_writeable!(RevokeAndACK, 32+32+33, {
963 per_commitment_secret,
964 next_per_commitment_point
967 impl_writeable_len_match!(Shutdown, {
968 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
974 impl_writeable_len_match!(UpdateFailHTLC, {
975 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
982 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
989 impl_writeable!(UpdateFee, 32+4, {
994 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1000 impl_writeable_len_match!(OnionErrorPacket, {
1001 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1006 impl Writeable for OnionPacket {
1007 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1008 w.size_hint(1 + 33 + 20*65 + 32);
1009 self.version.write(w)?;
1010 match self.public_key {
1011 Ok(pubkey) => pubkey.write(w)?,
1012 Err(_) => [0u8;33].write(w)?,
1014 w.write_all(&self.hop_data)?;
1015 self.hmac.write(w)?;
1020 impl<R: Read> Readable<R> for OnionPacket {
1021 fn read(r: &mut R) -> Result<Self, DecodeError> {
1023 version: Readable::read(r)?,
1025 let mut buf = [0u8;33];
1026 r.read_exact(&mut buf)?;
1027 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
1029 hop_data: Readable::read(r)?,
1030 hmac: Readable::read(r)?,
1035 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1041 onion_routing_packet
1044 impl Writeable for OnionRealm0HopData {
1045 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1047 self.short_channel_id.write(w)?;
1048 self.amt_to_forward.write(w)?;
1049 self.outgoing_cltv_value.write(w)?;
1050 w.write_all(&[0;12])?;
1055 impl<R: Read> Readable<R> for OnionRealm0HopData {
1056 fn read(r: &mut R) -> Result<Self, DecodeError> {
1057 Ok(OnionRealm0HopData {
1058 short_channel_id: Readable::read(r)?,
1059 amt_to_forward: Readable::read(r)?,
1060 outgoing_cltv_value: {
1061 let v: u32 = Readable::read(r)?;
1062 r.read_exact(&mut [0; 12])?;
1069 impl Writeable for OnionHopData {
1070 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1072 self.realm.write(w)?;
1073 self.data.write(w)?;
1074 self.hmac.write(w)?;
1079 impl<R: Read> Readable<R> for OnionHopData {
1080 fn read(r: &mut R) -> Result<Self, DecodeError> {
1083 let r: u8 = Readable::read(r)?;
1085 return Err(DecodeError::UnknownVersion);
1089 data: Readable::read(r)?,
1090 hmac: Readable::read(r)?,
1095 impl Writeable for Ping {
1096 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1097 w.size_hint(self.byteslen as usize + 4);
1098 self.ponglen.write(w)?;
1099 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1104 impl<R: Read> Readable<R> for Ping {
1105 fn read(r: &mut R) -> Result<Self, DecodeError> {
1107 ponglen: Readable::read(r)?,
1109 let byteslen = Readable::read(r)?;
1110 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1117 impl Writeable for Pong {
1118 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1119 w.size_hint(self.byteslen as usize + 2);
1120 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1125 impl<R: Read> Readable<R> for Pong {
1126 fn read(r: &mut R) -> Result<Self, DecodeError> {
1129 let byteslen = Readable::read(r)?;
1130 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1137 impl Writeable for UnsignedChannelAnnouncement {
1138 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1139 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1140 self.features.write(w)?;
1141 self.chain_hash.write(w)?;
1142 self.short_channel_id.write(w)?;
1143 self.node_id_1.write(w)?;
1144 self.node_id_2.write(w)?;
1145 self.bitcoin_key_1.write(w)?;
1146 self.bitcoin_key_2.write(w)?;
1147 w.write_all(&self.excess_data[..])?;
1152 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1153 fn read(r: &mut R) -> Result<Self, DecodeError> {
1156 let f: GlobalFeatures = Readable::read(r)?;
1157 if f.requires_unknown_bits() {
1158 return Err(DecodeError::UnknownRequiredFeature);
1162 chain_hash: Readable::read(r)?,
1163 short_channel_id: Readable::read(r)?,
1164 node_id_1: Readable::read(r)?,
1165 node_id_2: Readable::read(r)?,
1166 bitcoin_key_1: Readable::read(r)?,
1167 bitcoin_key_2: Readable::read(r)?,
1169 let mut excess_data = vec![];
1170 r.read_to_end(&mut excess_data)?;
1177 impl_writeable_len_match!(ChannelAnnouncement, {
1178 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1179 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1183 bitcoin_signature_1,
1184 bitcoin_signature_2,
1188 impl Writeable for UnsignedChannelUpdate {
1189 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1190 w.size_hint(64 + self.excess_data.len());
1191 self.chain_hash.write(w)?;
1192 self.short_channel_id.write(w)?;
1193 self.timestamp.write(w)?;
1194 self.flags.write(w)?;
1195 self.cltv_expiry_delta.write(w)?;
1196 self.htlc_minimum_msat.write(w)?;
1197 self.fee_base_msat.write(w)?;
1198 self.fee_proportional_millionths.write(w)?;
1199 w.write_all(&self.excess_data[..])?;
1204 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1205 fn read(r: &mut R) -> Result<Self, DecodeError> {
1207 chain_hash: Readable::read(r)?,
1208 short_channel_id: Readable::read(r)?,
1209 timestamp: Readable::read(r)?,
1210 flags: Readable::read(r)?,
1211 cltv_expiry_delta: Readable::read(r)?,
1212 htlc_minimum_msat: Readable::read(r)?,
1213 fee_base_msat: Readable::read(r)?,
1214 fee_proportional_millionths: Readable::read(r)?,
1216 let mut excess_data = vec![];
1217 r.read_to_end(&mut excess_data)?;
1224 impl_writeable_len_match!(ChannelUpdate, {
1225 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1226 64 + excess_data.len() + 64 }
1232 impl Writeable for ErrorMessage {
1233 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1234 w.size_hint(32 + 2 + self.data.len());
1235 self.channel_id.write(w)?;
1236 (self.data.len() as u16).write(w)?;
1237 w.write_all(self.data.as_bytes())?;
1242 impl<R: Read> Readable<R> for ErrorMessage {
1243 fn read(r: &mut R) -> Result<Self, DecodeError> {
1245 channel_id: Readable::read(r)?,
1247 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1248 let mut data = vec![];
1249 let data_len = r.read_to_end(&mut data)?;
1250 sz = cmp::min(data_len, sz);
1251 match String::from_utf8(data[..sz as usize].to_vec()) {
1253 Err(_) => return Err(DecodeError::InvalidValue),
1260 impl Writeable for UnsignedNodeAnnouncement {
1261 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1262 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1263 self.features.write(w)?;
1264 self.timestamp.write(w)?;
1265 self.node_id.write(w)?;
1266 w.write_all(&self.rgb)?;
1267 self.alias.write(w)?;
1269 let mut addrs_to_encode = self.addresses.clone();
1270 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1271 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1272 let mut addr_len = 0;
1273 for addr in &addrs_to_encode {
1274 addr_len += 1 + addr.len();
1276 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1277 for addr in addrs_to_encode {
1280 w.write_all(&self.excess_address_data[..])?;
1281 w.write_all(&self.excess_data[..])?;
1286 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1287 fn read(r: &mut R) -> Result<Self, DecodeError> {
1288 let features: GlobalFeatures = Readable::read(r)?;
1289 if features.requires_unknown_bits() {
1290 return Err(DecodeError::UnknownRequiredFeature);
1292 let timestamp: u32 = Readable::read(r)?;
1293 let node_id: PublicKey = Readable::read(r)?;
1294 let mut rgb = [0; 3];
1295 r.read_exact(&mut rgb)?;
1296 let alias: [u8; 32] = Readable::read(r)?;
1298 let addr_len: u16 = Readable::read(r)?;
1299 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1300 let mut addr_readpos = 0;
1301 let mut excess = false;
1302 let mut excess_byte = 0;
1304 if addr_len <= addr_readpos { break; }
1305 match Readable::read(r) {
1308 NetAddress::IPv4 { .. } => {
1309 if addresses.len() > 0 {
1310 return Err(DecodeError::ExtraAddressesPerType);
1313 NetAddress::IPv6 { .. } => {
1314 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1315 return Err(DecodeError::ExtraAddressesPerType);
1318 NetAddress::OnionV2 { .. } => {
1319 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1320 return Err(DecodeError::ExtraAddressesPerType);
1323 NetAddress::OnionV3 { .. } => {
1324 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1325 return Err(DecodeError::ExtraAddressesPerType);
1329 if addr_len < addr_readpos + 1 + addr.len() {
1330 return Err(DecodeError::BadLengthDescriptor);
1332 addr_readpos += (1 + addr.len()) as u16;
1333 addresses.push(addr);
1335 Ok(Err(unknown_descriptor)) => {
1337 excess_byte = unknown_descriptor;
1340 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1341 Err(e) => return Err(e),
1345 let mut excess_data = vec![];
1346 let excess_address_data = if addr_readpos < addr_len {
1347 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1348 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1350 excess_address_data[0] = excess_byte;
1355 excess_data.push(excess_byte);
1359 r.read_to_end(&mut excess_data)?;
1360 Ok(UnsignedNodeAnnouncement {
1367 excess_address_data,
1373 impl_writeable_len_match!(NodeAnnouncement, {
1374 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1375 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1385 use ln::msgs::OptionalField;
1386 use util::ser::Writeable;
1387 use secp256k1::key::{PublicKey,SecretKey};
1388 use secp256k1::Secp256k1;
1391 fn encoding_channel_reestablish_no_secret() {
1392 let cr = msgs::ChannelReestablish {
1393 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],
1394 next_local_commitment_number: 3,
1395 next_remote_commitment_number: 4,
1396 data_loss_protect: OptionalField::Absent,
1399 let encoded_value = cr.encode();
1402 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]
1407 fn encoding_channel_reestablish_with_secret() {
1409 let secp_ctx = Secp256k1::new();
1410 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1413 let cr = msgs::ChannelReestablish {
1414 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],
1415 next_local_commitment_number: 3,
1416 next_remote_commitment_number: 4,
1417 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1420 let encoded_value = cr.encode();
1423 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]