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 message, 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::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 self.flags.iter().enumerate().any(|(idx, &byte)| {
95 ( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 )
99 pub(crate) fn supports_unknown_bits(&self) -> bool {
100 self.flags.iter().enumerate().any(|(idx, &byte)| {
101 ( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 )
106 /// Tracks globalfeatures which are in init messages and routing announcements
107 #[derive(Clone, PartialEq)]
108 pub struct GlobalFeatures {
112 impl GlobalFeatures {
113 pub(crate) fn new() -> GlobalFeatures {
119 pub(crate) fn requires_unknown_bits(&self) -> bool {
120 for &byte in self.flags.iter() {
121 if (byte & 0x55) != 0 {
128 pub(crate) fn supports_unknown_bits(&self) -> bool {
129 for &byte in self.flags.iter() {
138 /// An init message to be sent or received from a peer
140 pub(crate) global_features: GlobalFeatures,
141 pub(crate) local_features: LocalFeatures,
144 /// An error message to be sent or received from a peer
146 pub struct ErrorMessage {
147 pub(crate) channel_id: [u8; 32],
148 pub(crate) data: String,
151 /// A ping message to be sent or received from a peer
153 pub(crate) ponglen: u16,
154 pub(crate) byteslen: u16,
157 /// A pong message to be sent or received from a peer
159 pub(crate) byteslen: u16,
162 /// An open_channel message to be sent or received from a peer
164 pub struct OpenChannel {
165 pub(crate) chain_hash: Sha256dHash,
166 pub(crate) temporary_channel_id: [u8; 32],
167 pub(crate) funding_satoshis: u64,
168 pub(crate) push_msat: u64,
169 pub(crate) dust_limit_satoshis: u64,
170 pub(crate) max_htlc_value_in_flight_msat: u64,
171 pub(crate) channel_reserve_satoshis: u64,
172 pub(crate) htlc_minimum_msat: u64,
173 pub(crate) feerate_per_kw: u32,
174 pub(crate) to_self_delay: u16,
175 pub(crate) max_accepted_htlcs: u16,
176 pub(crate) funding_pubkey: PublicKey,
177 pub(crate) revocation_basepoint: PublicKey,
178 pub(crate) payment_basepoint: PublicKey,
179 pub(crate) delayed_payment_basepoint: PublicKey,
180 pub(crate) htlc_basepoint: PublicKey,
181 pub(crate) first_per_commitment_point: PublicKey,
182 pub(crate) channel_flags: u8,
183 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
186 /// An accept_channel message to be sent or received from a peer
188 pub struct AcceptChannel {
189 pub(crate) temporary_channel_id: [u8; 32],
190 pub(crate) dust_limit_satoshis: u64,
191 pub(crate) max_htlc_value_in_flight_msat: u64,
192 pub(crate) channel_reserve_satoshis: u64,
193 pub(crate) htlc_minimum_msat: u64,
194 pub(crate) minimum_depth: u32,
195 pub(crate) to_self_delay: u16,
196 pub(crate) max_accepted_htlcs: u16,
197 pub(crate) funding_pubkey: PublicKey,
198 pub(crate) revocation_basepoint: PublicKey,
199 pub(crate) payment_basepoint: PublicKey,
200 pub(crate) delayed_payment_basepoint: PublicKey,
201 pub(crate) htlc_basepoint: PublicKey,
202 pub(crate) first_per_commitment_point: PublicKey,
203 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
206 /// A funding_created message to be sent or received from a peer
208 pub struct FundingCreated {
209 pub(crate) temporary_channel_id: [u8; 32],
210 pub(crate) funding_txid: Sha256dHash,
211 pub(crate) funding_output_index: u16,
212 pub(crate) signature: Signature,
215 /// A funding_signed message to be sent or received from a peer
217 pub struct FundingSigned {
218 pub(crate) channel_id: [u8; 32],
219 pub(crate) signature: Signature,
222 /// A funding_locked message to be sent or received from a peer
223 #[derive(Clone, PartialEq)]
224 pub struct FundingLocked {
225 pub(crate) channel_id: [u8; 32],
226 pub(crate) next_per_commitment_point: PublicKey,
229 /// A shutdown message to be sent or received from a peer
230 #[derive(Clone, PartialEq)]
231 pub struct Shutdown {
232 pub(crate) channel_id: [u8; 32],
233 pub(crate) scriptpubkey: Script,
236 /// A closing_signed message to be sent or received from a peer
237 #[derive(Clone, PartialEq)]
238 pub struct ClosingSigned {
239 pub(crate) channel_id: [u8; 32],
240 pub(crate) fee_satoshis: u64,
241 pub(crate) signature: Signature,
244 /// An update_add_htlc message to be sent or received from a peer
245 #[derive(Clone, PartialEq)]
246 pub struct UpdateAddHTLC {
247 pub(crate) channel_id: [u8; 32],
248 pub(crate) htlc_id: u64,
249 pub(crate) amount_msat: u64,
250 pub(crate) payment_hash: PaymentHash,
251 pub(crate) cltv_expiry: u32,
252 pub(crate) onion_routing_packet: OnionPacket,
255 /// An update_fulfill_htlc message to be sent or received from a peer
256 #[derive(Clone, PartialEq)]
257 pub struct UpdateFulfillHTLC {
258 pub(crate) channel_id: [u8; 32],
259 pub(crate) htlc_id: u64,
260 pub(crate) payment_preimage: PaymentPreimage,
263 /// An update_fail_htlc message to be sent or received from a peer
264 #[derive(Clone, PartialEq)]
265 pub struct UpdateFailHTLC {
266 pub(crate) channel_id: [u8; 32],
267 pub(crate) htlc_id: u64,
268 pub(crate) reason: OnionErrorPacket,
271 /// An update_fail_malformed_htlc message to be sent or received from a peer
272 #[derive(Clone, PartialEq)]
273 pub struct UpdateFailMalformedHTLC {
274 pub(crate) channel_id: [u8; 32],
275 pub(crate) htlc_id: u64,
276 pub(crate) sha256_of_onion: [u8; 32],
277 pub(crate) failure_code: u16,
280 /// A commitment_signed message to be sent or received from a peer
281 #[derive(Clone, PartialEq)]
282 pub struct CommitmentSigned {
283 pub(crate) channel_id: [u8; 32],
284 pub(crate) signature: Signature,
285 pub(crate) htlc_signatures: Vec<Signature>,
288 /// A revoke_and_ack message to be sent or received from a peer
289 #[derive(Clone, PartialEq)]
290 pub struct RevokeAndACK {
291 pub(crate) channel_id: [u8; 32],
292 pub(crate) per_commitment_secret: [u8; 32],
293 pub(crate) next_per_commitment_point: PublicKey,
296 /// An update_fee message to be sent or received from a peer
297 #[derive(PartialEq, Clone)]
298 pub struct UpdateFee {
299 pub(crate) channel_id: [u8; 32],
300 pub(crate) feerate_per_kw: u32,
303 #[derive(PartialEq, Clone)]
304 pub(crate) struct DataLossProtect {
305 pub(crate) your_last_per_commitment_secret: [u8; 32],
306 pub(crate) my_current_per_commitment_point: PublicKey,
309 /// A channel_reestablish message to be sent or received from a peer
310 #[derive(PartialEq, Clone)]
311 pub struct ChannelReestablish {
312 pub(crate) channel_id: [u8; 32],
313 pub(crate) next_local_commitment_number: u64,
314 pub(crate) next_remote_commitment_number: u64,
315 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
318 /// An announcement_signatures message to be sent or received from a peer
320 pub struct AnnouncementSignatures {
321 pub(crate) channel_id: [u8; 32],
322 pub(crate) short_channel_id: u64,
323 pub(crate) node_signature: Signature,
324 pub(crate) bitcoin_signature: Signature,
327 /// An address which can be used to connect to a remote peer
328 #[derive(PartialEq, Clone)]
329 pub enum NetAddress {
330 /// An IPv4 address/port on which the peer is listening.
332 /// The 4-byte IPv4 address
334 /// The port on which the node is listening
337 /// An IPv6 address/port on which the peer is listening.
339 /// The 16-byte IPv6 address
341 /// The port on which the node is listening
344 /// An old-style Tor onion address/port on which the peer is listening.
346 /// The bytes (usually encoded in base32 with ".onion" appended)
348 /// The port on which the node is listening
351 /// A new-style Tor onion address/port on which the peer is listening.
352 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
353 /// wrap as base32 and append ".onion".
355 /// The ed25519 long-term public key of the peer
356 ed25519_pubkey: [u8; 32],
357 /// The checksum of the pubkey and version, as included in the onion address
359 /// The version byte, as defined by the Tor Onion v3 spec.
361 /// The port on which the node is listening
366 fn get_id(&self) -> u8 {
368 &NetAddress::IPv4 {..} => { 1 },
369 &NetAddress::IPv6 {..} => { 2 },
370 &NetAddress::OnionV2 {..} => { 3 },
371 &NetAddress::OnionV3 {..} => { 4 },
375 /// Strict byte-length of address descriptor, 1-byte type not recorded
376 fn len(&self) -> u16 {
378 &NetAddress::IPv4 { .. } => { 6 },
379 &NetAddress::IPv6 { .. } => { 18 },
380 &NetAddress::OnionV2 { .. } => { 12 },
381 &NetAddress::OnionV3 { .. } => { 37 },
386 impl Writeable for NetAddress {
387 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
389 &NetAddress::IPv4 { ref addr, ref port } => {
394 &NetAddress::IPv6 { ref addr, ref port } => {
399 &NetAddress::OnionV2 { ref addr, ref port } => {
404 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
406 ed25519_pubkey.write(writer)?;
407 checksum.write(writer)?;
408 version.write(writer)?;
416 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
417 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
418 let byte = <u8 as Readable<R>>::read(reader)?;
421 Ok(Ok(NetAddress::IPv4 {
422 addr: Readable::read(reader)?,
423 port: Readable::read(reader)?,
427 Ok(Ok(NetAddress::IPv6 {
428 addr: Readable::read(reader)?,
429 port: Readable::read(reader)?,
433 Ok(Ok(NetAddress::OnionV2 {
434 addr: Readable::read(reader)?,
435 port: Readable::read(reader)?,
439 Ok(Ok(NetAddress::OnionV3 {
440 ed25519_pubkey: Readable::read(reader)?,
441 checksum: Readable::read(reader)?,
442 version: Readable::read(reader)?,
443 port: Readable::read(reader)?,
446 _ => return Ok(Err(byte)),
451 #[derive(PartialEq, Clone)]
452 // Only exposed as broadcast of node_announcement should be filtered by node_id
453 /// The unsigned part of a node_announcement
454 pub struct UnsignedNodeAnnouncement {
455 pub(crate) features: GlobalFeatures,
456 pub(crate) timestamp: u32,
457 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
459 pub node_id: PublicKey,
460 pub(crate) rgb: [u8; 3],
461 pub(crate) alias: [u8; 32],
462 /// List of addresses on which this node is reachable. Note that you may only have up to one
463 /// address of each type, if you have more, they may be silently discarded or we may panic!
464 pub(crate) addresses: Vec<NetAddress>,
465 pub(crate) excess_address_data: Vec<u8>,
466 pub(crate) excess_data: Vec<u8>,
468 #[derive(PartialEq, Clone)]
469 /// A node_announcement message to be sent or received from a peer
470 pub struct NodeAnnouncement {
471 pub(crate) signature: Signature,
472 pub(crate) contents: UnsignedNodeAnnouncement,
475 // Only exposed as broadcast of channel_announcement should be filtered by node_id
476 /// The unsigned part of a channel_announcement
477 #[derive(PartialEq, Clone)]
478 pub struct UnsignedChannelAnnouncement {
479 pub(crate) features: GlobalFeatures,
480 pub(crate) chain_hash: Sha256dHash,
481 pub(crate) short_channel_id: u64,
482 /// One of the two node_ids which are endpoints of this channel
483 pub node_id_1: PublicKey,
484 /// The other of the two node_ids which are endpoints of this channel
485 pub node_id_2: PublicKey,
486 pub(crate) bitcoin_key_1: PublicKey,
487 pub(crate) bitcoin_key_2: PublicKey,
488 pub(crate) excess_data: Vec<u8>,
490 /// A channel_announcement message to be sent or received from a peer
491 #[derive(PartialEq, Clone)]
492 pub struct ChannelAnnouncement {
493 pub(crate) node_signature_1: Signature,
494 pub(crate) node_signature_2: Signature,
495 pub(crate) bitcoin_signature_1: Signature,
496 pub(crate) bitcoin_signature_2: Signature,
497 pub(crate) contents: UnsignedChannelAnnouncement,
500 #[derive(PartialEq, Clone)]
501 pub(crate) struct UnsignedChannelUpdate {
502 pub(crate) chain_hash: Sha256dHash,
503 pub(crate) short_channel_id: u64,
504 pub(crate) timestamp: u32,
505 pub(crate) flags: u16,
506 pub(crate) cltv_expiry_delta: u16,
507 pub(crate) htlc_minimum_msat: u64,
508 pub(crate) fee_base_msat: u32,
509 pub(crate) fee_proportional_millionths: u32,
510 pub(crate) excess_data: Vec<u8>,
512 /// A channel_update message to be sent or received from a peer
513 #[derive(PartialEq, Clone)]
514 pub struct ChannelUpdate {
515 pub(crate) signature: Signature,
516 pub(crate) contents: UnsignedChannelUpdate,
519 /// Used to put an error message in a HandleError
521 pub enum ErrorAction {
522 /// The peer took some action which made us think they were useless. Disconnect them.
524 /// An error message which we should make an effort to send before we disconnect.
525 msg: Option<ErrorMessage>
527 /// The peer did something harmless that we weren't able to process, just log and ignore
529 /// The peer did something incorrect. Tell them.
531 /// The message to send.
536 /// An Err type for failure to process messages.
537 pub struct HandleError { //TODO: rename me
538 /// A human-readable message describing the error
539 pub err: &'static str,
540 /// The action which should be taken against the offending peer.
541 pub action: Option<ErrorAction>, //TODO: Make this required
544 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
545 /// transaction updates if they were pending.
546 #[derive(PartialEq, Clone)]
547 pub struct CommitmentUpdate {
548 /// update_add_htlc messages which should be sent
549 pub update_add_htlcs: Vec<UpdateAddHTLC>,
550 /// update_fulfill_htlc messages which should be sent
551 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
552 /// update_fail_htlc messages which should be sent
553 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
554 /// update_fail_malformed_htlc messages which should be sent
555 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
556 /// An update_fee message which should be sent
557 pub update_fee: Option<UpdateFee>,
558 /// Finally, the commitment_signed message which should be sent
559 pub commitment_signed: CommitmentSigned,
562 /// The information we received from a peer along the route of a payment we originated. This is
563 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
564 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
566 pub enum HTLCFailChannelUpdate {
567 /// We received an error which included a full ChannelUpdate message.
568 ChannelUpdateMessage {
569 /// The unwrapped message we received
572 /// We received an error which indicated only that a channel has been closed
574 /// The short_channel_id which has now closed.
575 short_channel_id: u64,
576 /// when this true, this channel should be permanently removed from the
577 /// consideration. Otherwise, this channel can be restored as new channel_update is received
580 /// We received an error which indicated only that a node has failed
582 /// The node_id that has failed.
584 /// when this true, node should be permanently removed from the
585 /// consideration. Otherwise, the channels connected to this node can be
586 /// restored as new channel_update is received
591 /// Messages could have optional fields to use with extended features
592 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
593 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
594 /// separate enum type for them.
595 #[derive(Clone, PartialEq)]
596 pub enum OptionalField<T> {
597 /// Optional field is included in message
599 /// Optional field is absent in message
603 /// A trait to describe an object which can receive channel messages.
605 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
606 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
607 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
609 /// Handle an incoming open_channel message from the given peer.
610 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
611 /// Handle an incoming accept_channel message from the given peer.
612 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
613 /// Handle an incoming funding_created message from the given peer.
614 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
615 /// Handle an incoming funding_signed message from the given peer.
616 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
617 /// Handle an incoming funding_locked message from the given peer.
618 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
621 /// Handle an incoming shutdown message from the given peer.
622 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
623 /// Handle an incoming closing_signed message from the given peer.
624 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
627 /// Handle an incoming update_add_htlc message from the given peer.
628 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
629 /// Handle an incoming update_fulfill_htlc message from the given peer.
630 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
631 /// Handle an incoming update_fail_htlc message from the given peer.
632 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
633 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
634 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
635 /// Handle an incoming commitment_signed message from the given peer.
636 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
637 /// Handle an incoming revoke_and_ack message from the given peer.
638 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
640 /// Handle an incoming update_fee message from the given peer.
641 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
643 // Channel-to-announce:
644 /// Handle an incoming announcement_signatures message from the given peer.
645 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
647 // Connection loss/reestablish:
648 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
649 /// is believed to be possible in the future (eg they're sending us messages we don't
650 /// understand or indicate they require unknown feature bits), no_connection_possible is set
651 /// and any outstanding channels should be failed.
652 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
654 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
655 fn peer_connected(&self, their_node_id: &PublicKey);
656 /// Handle an incoming channel_reestablish message from the given peer.
657 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
660 /// Handle an incoming error message from the given peer.
661 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
664 /// A trait to describe an object which can receive routing messages.
665 pub trait RoutingMessageHandler : Send + Sync {
666 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
667 /// false or returning an Err otherwise.
668 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
669 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
670 /// or returning an Err otherwise.
671 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
672 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
673 /// false or returning an Err otherwise.
674 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
675 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
676 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
677 /// Gets a subset of the channel announcements and updates required to dump our routing table
678 /// to a remote node, starting at the short_channel_id indicated by starting_point and
679 /// including batch_amount entries.
680 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
681 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
682 /// starting at the node *after* the provided publickey and including batch_amount entries.
683 /// If None is provided for starting_point, we start at the first node.
684 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
687 pub(crate) struct OnionRealm0HopData {
688 pub(crate) short_channel_id: u64,
689 pub(crate) amt_to_forward: u64,
690 pub(crate) outgoing_cltv_value: u32,
691 // 12 bytes of 0-padding
694 mod fuzzy_internal_msgs {
695 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
696 // them from untrusted input):
698 use super::OnionRealm0HopData;
699 pub struct OnionHopData {
700 pub(crate) realm: u8,
701 pub(crate) data: OnionRealm0HopData,
702 pub(crate) hmac: [u8; 32],
704 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
706 pub struct DecodedOnionErrorPacket {
707 pub(crate) hmac: [u8; 32],
708 pub(crate) failuremsg: Vec<u8>,
709 pub(crate) pad: Vec<u8>,
712 #[cfg(feature = "fuzztarget")]
713 pub use self::fuzzy_internal_msgs::*;
714 #[cfg(not(feature = "fuzztarget"))]
715 pub(crate) use self::fuzzy_internal_msgs::*;
718 pub(crate) struct OnionPacket {
719 pub(crate) version: u8,
720 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
721 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
722 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
723 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
724 pub(crate) hop_data: [u8; 20*65],
725 pub(crate) hmac: [u8; 32],
728 impl PartialEq for OnionPacket {
729 fn eq(&self, other: &OnionPacket) -> bool {
730 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
731 if i != j { return false; }
733 self.version == other.version &&
734 self.public_key == other.public_key &&
735 self.hmac == other.hmac
739 #[derive(Clone, PartialEq)]
740 pub(crate) struct OnionErrorPacket {
741 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
742 // (TODO) We limit it in decode to much lower...
743 pub(crate) data: Vec<u8>,
746 impl Error for DecodeError {
747 fn description(&self) -> &str {
749 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
750 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
751 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
752 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
753 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
754 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
755 DecodeError::Io(ref e) => e.description(),
759 impl fmt::Display for DecodeError {
760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
761 f.write_str(self.description())
765 impl fmt::Debug for HandleError {
766 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
767 f.write_str(self.err)
771 impl From<::std::io::Error> for DecodeError {
772 fn from(e: ::std::io::Error) -> Self {
773 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
774 DecodeError::ShortRead
781 impl Writeable for OptionalField<Script> {
782 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
784 OptionalField::Present(ref script) => {
785 // Note that Writeable for script includes the 16-bit length tag for us
788 OptionalField::Absent => {}
794 impl<R: Read> Readable<R> for OptionalField<Script> {
795 fn read(r: &mut R) -> Result<Self, DecodeError> {
796 match <u16 as Readable<R>>::read(r) {
798 let mut buf = vec![0; len as usize];
799 r.read_exact(&mut buf)?;
800 Ok(OptionalField::Present(Script::from(buf)))
802 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
808 impl_writeable_len_match!(AcceptChannel, {
809 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
812 temporary_channel_id,
814 max_htlc_value_in_flight_msat,
815 channel_reserve_satoshis,
821 revocation_basepoint,
823 delayed_payment_basepoint,
825 first_per_commitment_point,
826 shutdown_scriptpubkey
829 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
836 impl Writeable for ChannelReestablish {
837 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
838 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
839 self.channel_id.write(w)?;
840 self.next_local_commitment_number.write(w)?;
841 self.next_remote_commitment_number.write(w)?;
842 match self.data_loss_protect {
843 OptionalField::Present(ref data_loss_protect) => {
844 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
845 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
847 OptionalField::Absent => {}
853 impl<R: Read> Readable<R> for ChannelReestablish{
854 fn read(r: &mut R) -> Result<Self, DecodeError> {
856 channel_id: Readable::read(r)?,
857 next_local_commitment_number: Readable::read(r)?,
858 next_remote_commitment_number: Readable::read(r)?,
860 match <[u8; 32] as Readable<R>>::read(r) {
861 Ok(your_last_per_commitment_secret) =>
862 OptionalField::Present(DataLossProtect {
863 your_last_per_commitment_secret,
864 my_current_per_commitment_point: Readable::read(r)?,
866 Err(DecodeError::ShortRead) => OptionalField::Absent,
867 Err(e) => return Err(e)
874 impl_writeable!(ClosingSigned, 32+8+64, {
880 impl_writeable_len_match!(CommitmentSigned, {
881 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
888 impl_writeable_len_match!(DecodedOnionErrorPacket, {
889 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
896 impl_writeable!(FundingCreated, 32+32+2+64, {
897 temporary_channel_id,
899 funding_output_index,
903 impl_writeable!(FundingSigned, 32+64, {
908 impl_writeable!(FundingLocked, 32+33, {
910 next_per_commitment_point
913 impl_writeable_len_match!(GlobalFeatures, {
914 { GlobalFeatures { ref flags }, flags.len() + 2 }
919 impl_writeable_len_match!(LocalFeatures, {
920 { LocalFeatures { ref flags }, flags.len() + 2 }
925 impl_writeable_len_match!(Init, {
926 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
932 impl_writeable_len_match!(OpenChannel, {
933 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
937 temporary_channel_id,
941 max_htlc_value_in_flight_msat,
942 channel_reserve_satoshis,
948 revocation_basepoint,
950 delayed_payment_basepoint,
952 first_per_commitment_point,
954 shutdown_scriptpubkey
957 impl_writeable!(RevokeAndACK, 32+32+33, {
959 per_commitment_secret,
960 next_per_commitment_point
963 impl_writeable_len_match!(Shutdown, {
964 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
970 impl_writeable_len_match!(UpdateFailHTLC, {
971 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
978 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
985 impl_writeable!(UpdateFee, 32+4, {
990 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
996 impl_writeable_len_match!(OnionErrorPacket, {
997 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1002 impl Writeable for OnionPacket {
1003 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1004 w.size_hint(1 + 33 + 20*65 + 32);
1005 self.version.write(w)?;
1006 match self.public_key {
1007 Ok(pubkey) => pubkey.write(w)?,
1008 Err(_) => [0u8;33].write(w)?,
1010 w.write_all(&self.hop_data)?;
1011 self.hmac.write(w)?;
1016 impl<R: Read> Readable<R> for OnionPacket {
1017 fn read(r: &mut R) -> Result<Self, DecodeError> {
1019 version: Readable::read(r)?,
1021 let mut buf = [0u8;33];
1022 r.read_exact(&mut buf)?;
1023 PublicKey::from_slice(&buf)
1025 hop_data: Readable::read(r)?,
1026 hmac: Readable::read(r)?,
1031 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1037 onion_routing_packet
1040 impl Writeable for OnionRealm0HopData {
1041 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1043 self.short_channel_id.write(w)?;
1044 self.amt_to_forward.write(w)?;
1045 self.outgoing_cltv_value.write(w)?;
1046 w.write_all(&[0;12])?;
1051 impl<R: Read> Readable<R> for OnionRealm0HopData {
1052 fn read(r: &mut R) -> Result<Self, DecodeError> {
1053 Ok(OnionRealm0HopData {
1054 short_channel_id: Readable::read(r)?,
1055 amt_to_forward: Readable::read(r)?,
1056 outgoing_cltv_value: {
1057 let v: u32 = Readable::read(r)?;
1058 r.read_exact(&mut [0; 12])?;
1065 impl Writeable for OnionHopData {
1066 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1068 self.realm.write(w)?;
1069 self.data.write(w)?;
1070 self.hmac.write(w)?;
1075 impl<R: Read> Readable<R> for OnionHopData {
1076 fn read(r: &mut R) -> Result<Self, DecodeError> {
1079 let r: u8 = Readable::read(r)?;
1081 return Err(DecodeError::UnknownVersion);
1085 data: Readable::read(r)?,
1086 hmac: Readable::read(r)?,
1091 impl Writeable for Ping {
1092 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1093 w.size_hint(self.byteslen as usize + 4);
1094 self.ponglen.write(w)?;
1095 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1100 impl<R: Read> Readable<R> for Ping {
1101 fn read(r: &mut R) -> Result<Self, DecodeError> {
1103 ponglen: Readable::read(r)?,
1105 let byteslen = Readable::read(r)?;
1106 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1113 impl Writeable for Pong {
1114 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1115 w.size_hint(self.byteslen as usize + 2);
1116 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1121 impl<R: Read> Readable<R> for Pong {
1122 fn read(r: &mut R) -> Result<Self, DecodeError> {
1125 let byteslen = Readable::read(r)?;
1126 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1133 impl Writeable for UnsignedChannelAnnouncement {
1134 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1135 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1136 self.features.write(w)?;
1137 self.chain_hash.write(w)?;
1138 self.short_channel_id.write(w)?;
1139 self.node_id_1.write(w)?;
1140 self.node_id_2.write(w)?;
1141 self.bitcoin_key_1.write(w)?;
1142 self.bitcoin_key_2.write(w)?;
1143 w.write_all(&self.excess_data[..])?;
1148 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1149 fn read(r: &mut R) -> Result<Self, DecodeError> {
1152 let f: GlobalFeatures = Readable::read(r)?;
1153 if f.requires_unknown_bits() {
1154 return Err(DecodeError::UnknownRequiredFeature);
1158 chain_hash: Readable::read(r)?,
1159 short_channel_id: Readable::read(r)?,
1160 node_id_1: Readable::read(r)?,
1161 node_id_2: Readable::read(r)?,
1162 bitcoin_key_1: Readable::read(r)?,
1163 bitcoin_key_2: Readable::read(r)?,
1165 let mut excess_data = vec![];
1166 r.read_to_end(&mut excess_data)?;
1173 impl_writeable_len_match!(ChannelAnnouncement, {
1174 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1175 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1179 bitcoin_signature_1,
1180 bitcoin_signature_2,
1184 impl Writeable for UnsignedChannelUpdate {
1185 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1186 w.size_hint(64 + self.excess_data.len());
1187 self.chain_hash.write(w)?;
1188 self.short_channel_id.write(w)?;
1189 self.timestamp.write(w)?;
1190 self.flags.write(w)?;
1191 self.cltv_expiry_delta.write(w)?;
1192 self.htlc_minimum_msat.write(w)?;
1193 self.fee_base_msat.write(w)?;
1194 self.fee_proportional_millionths.write(w)?;
1195 w.write_all(&self.excess_data[..])?;
1200 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1201 fn read(r: &mut R) -> Result<Self, DecodeError> {
1203 chain_hash: Readable::read(r)?,
1204 short_channel_id: Readable::read(r)?,
1205 timestamp: Readable::read(r)?,
1206 flags: Readable::read(r)?,
1207 cltv_expiry_delta: Readable::read(r)?,
1208 htlc_minimum_msat: Readable::read(r)?,
1209 fee_base_msat: Readable::read(r)?,
1210 fee_proportional_millionths: Readable::read(r)?,
1212 let mut excess_data = vec![];
1213 r.read_to_end(&mut excess_data)?;
1220 impl_writeable_len_match!(ChannelUpdate, {
1221 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1222 64 + excess_data.len() + 64 }
1228 impl Writeable for ErrorMessage {
1229 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1230 w.size_hint(32 + 2 + self.data.len());
1231 self.channel_id.write(w)?;
1232 (self.data.len() as u16).write(w)?;
1233 w.write_all(self.data.as_bytes())?;
1238 impl<R: Read> Readable<R> for ErrorMessage {
1239 fn read(r: &mut R) -> Result<Self, DecodeError> {
1241 channel_id: Readable::read(r)?,
1243 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1244 let mut data = vec![];
1245 let data_len = r.read_to_end(&mut data)?;
1246 sz = cmp::min(data_len, sz);
1247 match String::from_utf8(data[..sz as usize].to_vec()) {
1249 Err(_) => return Err(DecodeError::InvalidValue),
1256 impl Writeable for UnsignedNodeAnnouncement {
1257 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1258 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1259 self.features.write(w)?;
1260 self.timestamp.write(w)?;
1261 self.node_id.write(w)?;
1262 w.write_all(&self.rgb)?;
1263 self.alias.write(w)?;
1265 let mut addrs_to_encode = self.addresses.clone();
1266 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1267 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1268 let mut addr_len = 0;
1269 for addr in &addrs_to_encode {
1270 addr_len += 1 + addr.len();
1272 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1273 for addr in addrs_to_encode {
1276 w.write_all(&self.excess_address_data[..])?;
1277 w.write_all(&self.excess_data[..])?;
1282 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1283 fn read(r: &mut R) -> Result<Self, DecodeError> {
1284 let features: GlobalFeatures = Readable::read(r)?;
1285 if features.requires_unknown_bits() {
1286 return Err(DecodeError::UnknownRequiredFeature);
1288 let timestamp: u32 = Readable::read(r)?;
1289 let node_id: PublicKey = Readable::read(r)?;
1290 let mut rgb = [0; 3];
1291 r.read_exact(&mut rgb)?;
1292 let alias: [u8; 32] = Readable::read(r)?;
1294 let addr_len: u16 = Readable::read(r)?;
1295 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1296 let mut addr_readpos = 0;
1297 let mut excess = false;
1298 let mut excess_byte = 0;
1300 if addr_len <= addr_readpos { break; }
1301 match Readable::read(r) {
1304 NetAddress::IPv4 { .. } => {
1305 if addresses.len() > 0 {
1306 return Err(DecodeError::ExtraAddressesPerType);
1309 NetAddress::IPv6 { .. } => {
1310 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1311 return Err(DecodeError::ExtraAddressesPerType);
1314 NetAddress::OnionV2 { .. } => {
1315 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1316 return Err(DecodeError::ExtraAddressesPerType);
1319 NetAddress::OnionV3 { .. } => {
1320 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1321 return Err(DecodeError::ExtraAddressesPerType);
1325 if addr_len < addr_readpos + 1 + addr.len() {
1326 return Err(DecodeError::BadLengthDescriptor);
1328 addr_readpos += (1 + addr.len()) as u16;
1329 addresses.push(addr);
1331 Ok(Err(unknown_descriptor)) => {
1333 excess_byte = unknown_descriptor;
1336 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1337 Err(e) => return Err(e),
1341 let mut excess_data = vec![];
1342 let excess_address_data = if addr_readpos < addr_len {
1343 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1344 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1346 excess_address_data[0] = excess_byte;
1351 excess_data.push(excess_byte);
1355 r.read_to_end(&mut excess_data)?;
1356 Ok(UnsignedNodeAnnouncement {
1363 excess_address_data,
1369 impl_writeable_len_match!(NodeAnnouncement, {
1370 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1371 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1381 use ln::msgs::OptionalField;
1382 use util::ser::Writeable;
1383 use secp256k1::key::{PublicKey,SecretKey};
1384 use secp256k1::Secp256k1;
1387 fn encoding_channel_reestablish_no_secret() {
1388 let cr = msgs::ChannelReestablish {
1389 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],
1390 next_local_commitment_number: 3,
1391 next_remote_commitment_number: 4,
1392 data_loss_protect: OptionalField::Absent,
1395 let encoded_value = cr.encode();
1398 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]
1403 fn encoding_channel_reestablish_with_secret() {
1405 let secp_ctx = Secp256k1::new();
1406 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1409 let cr = msgs::ChannelReestablish {
1410 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],
1411 next_local_commitment_number: 3,
1412 next_remote_commitment_number: 4,
1413 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1416 let encoded_value = cr.encode();
1419 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]