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 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 listening.
342 /// The 4-byte IPv4 address
344 /// The port on which the node is listening
347 /// An IPv6 address/port on which the peer is listening.
349 /// The 16-byte IPv6 address
351 /// The port on which the node is listening
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 listening
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 listening
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 /// update_add_htlc messages which should be sent
559 pub update_add_htlcs: Vec<UpdateAddHTLC>,
560 /// update_fulfill_htlc messages which should be sent
561 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
562 /// update_fail_htlc messages which should be sent
563 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
564 /// update_fail_malformed_htlc messages which should be sent
565 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
566 /// An update_fee message which should be sent
567 pub update_fee: Option<UpdateFee>,
568 /// Finally, the commitment_signed message which should be sent
569 pub commitment_signed: CommitmentSigned,
572 /// The information we received from a peer along the route of a payment we originated. This is
573 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
574 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
576 pub enum HTLCFailChannelUpdate {
577 /// We received an error which included a full ChannelUpdate message.
578 ChannelUpdateMessage {
579 /// The unwrapped message we received
582 /// We received an error which indicated only that a channel has been closed
584 /// The short_channel_id which has now closed.
585 short_channel_id: u64,
586 /// when this true, this channel should be permanently removed from the
587 /// consideration. Otherwise, this channel can be restored as new channel_update is received
590 /// We received an error which indicated only that a node has failed
592 /// The node_id that has failed.
594 /// when this true, node should be permanently removed from the
595 /// consideration. Otherwise, the channels connected to this node can be
596 /// restored as new channel_update is received
601 /// Messages could have optional fields to use with extended features
602 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
603 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
604 /// separate enum type for them.
605 #[derive(Clone, PartialEq)]
606 pub enum OptionalField<T> {
607 /// Optional field is included in message
609 /// Optional field is absent in message
613 /// A trait to describe an object which can receive channel messages.
615 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
616 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
617 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
619 /// Handle an incoming open_channel message from the given peer.
620 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
621 /// Handle an incoming accept_channel message from the given peer.
622 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
623 /// Handle an incoming funding_created message from the given peer.
624 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
625 /// Handle an incoming funding_signed message from the given peer.
626 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
627 /// Handle an incoming funding_locked message from the given peer.
628 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
631 /// Handle an incoming shutdown message from the given peer.
632 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
633 /// Handle an incoming closing_signed message from the given peer.
634 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
637 /// Handle an incoming update_add_htlc message from the given peer.
638 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
639 /// Handle an incoming update_fulfill_htlc message from the given peer.
640 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
641 /// Handle an incoming update_fail_htlc message from the given peer.
642 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
643 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
644 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
645 /// Handle an incoming commitment_signed message from the given peer.
646 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
647 /// Handle an incoming revoke_and_ack message from the given peer.
648 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
650 /// Handle an incoming update_fee message from the given peer.
651 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
653 // Channel-to-announce:
654 /// Handle an incoming announcement_signatures message from the given peer.
655 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
657 // Connection loss/reestablish:
658 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
659 /// is believed to be possible in the future (eg they're sending us messages we don't
660 /// understand or indicate they require unknown feature bits), no_connection_possible is set
661 /// and any outstanding channels should be failed.
662 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
664 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
665 fn peer_connected(&self, their_node_id: &PublicKey);
666 /// Handle an incoming channel_reestablish message from the given peer.
667 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
670 /// Handle an incoming error message from the given peer.
671 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
674 /// A trait to describe an object which can receive routing messages.
675 pub trait RoutingMessageHandler : Send + Sync {
676 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
677 /// false or returning an Err otherwise.
678 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
679 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
680 /// or returning an Err otherwise.
681 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
682 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
683 /// false or returning an Err otherwise.
684 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
685 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
686 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
687 /// Gets a subset of the channel announcements and updates required to dump our routing table
688 /// to a remote node, starting at the short_channel_id indicated by starting_point and
689 /// including batch_amount entries.
690 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
691 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
692 /// starting at the node *after* the provided publickey and including batch_amount entries.
693 /// If None is provided for starting_point, we start at the first node.
694 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
697 pub(crate) struct OnionRealm0HopData {
698 pub(crate) short_channel_id: u64,
699 pub(crate) amt_to_forward: u64,
700 pub(crate) outgoing_cltv_value: u32,
701 // 12 bytes of 0-padding
704 mod fuzzy_internal_msgs {
705 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
706 // them from untrusted input):
708 use super::OnionRealm0HopData;
709 pub struct OnionHopData {
710 pub(crate) realm: u8,
711 pub(crate) data: OnionRealm0HopData,
712 pub(crate) hmac: [u8; 32],
714 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
716 pub struct DecodedOnionErrorPacket {
717 pub(crate) hmac: [u8; 32],
718 pub(crate) failuremsg: Vec<u8>,
719 pub(crate) pad: Vec<u8>,
722 #[cfg(feature = "fuzztarget")]
723 pub use self::fuzzy_internal_msgs::*;
724 #[cfg(not(feature = "fuzztarget"))]
725 pub(crate) use self::fuzzy_internal_msgs::*;
728 pub(crate) struct OnionPacket {
729 pub(crate) version: u8,
730 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
731 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
732 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
733 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
734 pub(crate) hop_data: [u8; 20*65],
735 pub(crate) hmac: [u8; 32],
738 impl PartialEq for OnionPacket {
739 fn eq(&self, other: &OnionPacket) -> bool {
740 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
741 if i != j { return false; }
743 self.version == other.version &&
744 self.public_key == other.public_key &&
745 self.hmac == other.hmac
749 #[derive(Clone, PartialEq)]
750 pub(crate) struct OnionErrorPacket {
751 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
752 // (TODO) We limit it in decode to much lower...
753 pub(crate) data: Vec<u8>,
756 impl Error for DecodeError {
757 fn description(&self) -> &str {
759 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
760 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
761 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
762 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
763 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
764 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
765 DecodeError::Io(ref e) => e.description(),
769 impl fmt::Display for DecodeError {
770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 f.write_str(self.description())
775 impl fmt::Debug for HandleError {
776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777 f.write_str(self.err)
781 impl From<::std::io::Error> for DecodeError {
782 fn from(e: ::std::io::Error) -> Self {
783 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
784 DecodeError::ShortRead
791 impl Writeable for OptionalField<Script> {
792 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
794 OptionalField::Present(ref script) => {
795 // Note that Writeable for script includes the 16-bit length tag for us
798 OptionalField::Absent => {}
804 impl<R: Read> Readable<R> for OptionalField<Script> {
805 fn read(r: &mut R) -> Result<Self, DecodeError> {
806 match <u16 as Readable<R>>::read(r) {
808 let mut buf = vec![0; len as usize];
809 r.read_exact(&mut buf)?;
810 Ok(OptionalField::Present(Script::from(buf)))
812 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
818 impl_writeable_len_match!(AcceptChannel, {
819 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
822 temporary_channel_id,
824 max_htlc_value_in_flight_msat,
825 channel_reserve_satoshis,
831 revocation_basepoint,
833 delayed_payment_basepoint,
835 first_per_commitment_point,
836 shutdown_scriptpubkey
839 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
846 impl Writeable for ChannelReestablish {
847 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
848 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
849 self.channel_id.write(w)?;
850 self.next_local_commitment_number.write(w)?;
851 self.next_remote_commitment_number.write(w)?;
852 match self.data_loss_protect {
853 OptionalField::Present(ref data_loss_protect) => {
854 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
855 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
857 OptionalField::Absent => {}
863 impl<R: Read> Readable<R> for ChannelReestablish{
864 fn read(r: &mut R) -> Result<Self, DecodeError> {
866 channel_id: Readable::read(r)?,
867 next_local_commitment_number: Readable::read(r)?,
868 next_remote_commitment_number: Readable::read(r)?,
870 match <[u8; 32] as Readable<R>>::read(r) {
871 Ok(your_last_per_commitment_secret) =>
872 OptionalField::Present(DataLossProtect {
873 your_last_per_commitment_secret,
874 my_current_per_commitment_point: Readable::read(r)?,
876 Err(DecodeError::ShortRead) => OptionalField::Absent,
877 Err(e) => return Err(e)
884 impl_writeable!(ClosingSigned, 32+8+64, {
890 impl_writeable_len_match!(CommitmentSigned, {
891 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
898 impl_writeable_len_match!(DecodedOnionErrorPacket, {
899 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
906 impl_writeable!(FundingCreated, 32+32+2+64, {
907 temporary_channel_id,
909 funding_output_index,
913 impl_writeable!(FundingSigned, 32+64, {
918 impl_writeable!(FundingLocked, 32+33, {
920 next_per_commitment_point
923 impl_writeable_len_match!(GlobalFeatures, {
924 { GlobalFeatures { ref flags }, flags.len() + 2 }
929 impl_writeable_len_match!(LocalFeatures, {
930 { LocalFeatures { ref flags }, flags.len() + 2 }
935 impl_writeable_len_match!(Init, {
936 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
942 impl_writeable_len_match!(OpenChannel, {
943 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
947 temporary_channel_id,
951 max_htlc_value_in_flight_msat,
952 channel_reserve_satoshis,
958 revocation_basepoint,
960 delayed_payment_basepoint,
962 first_per_commitment_point,
964 shutdown_scriptpubkey
967 impl_writeable!(RevokeAndACK, 32+32+33, {
969 per_commitment_secret,
970 next_per_commitment_point
973 impl_writeable_len_match!(Shutdown, {
974 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
980 impl_writeable_len_match!(UpdateFailHTLC, {
981 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
988 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
995 impl_writeable!(UpdateFee, 32+4, {
1000 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1006 impl_writeable_len_match!(OnionErrorPacket, {
1007 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1012 impl Writeable for OnionPacket {
1013 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1014 w.size_hint(1 + 33 + 20*65 + 32);
1015 self.version.write(w)?;
1016 match self.public_key {
1017 Ok(pubkey) => pubkey.write(w)?,
1018 Err(_) => [0u8;33].write(w)?,
1020 w.write_all(&self.hop_data)?;
1021 self.hmac.write(w)?;
1026 impl<R: Read> Readable<R> for OnionPacket {
1027 fn read(r: &mut R) -> Result<Self, DecodeError> {
1029 version: Readable::read(r)?,
1031 let mut buf = [0u8;33];
1032 r.read_exact(&mut buf)?;
1033 PublicKey::from_slice(&buf)
1035 hop_data: Readable::read(r)?,
1036 hmac: Readable::read(r)?,
1041 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1047 onion_routing_packet
1050 impl Writeable for OnionRealm0HopData {
1051 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1053 self.short_channel_id.write(w)?;
1054 self.amt_to_forward.write(w)?;
1055 self.outgoing_cltv_value.write(w)?;
1056 w.write_all(&[0;12])?;
1061 impl<R: Read> Readable<R> for OnionRealm0HopData {
1062 fn read(r: &mut R) -> Result<Self, DecodeError> {
1063 Ok(OnionRealm0HopData {
1064 short_channel_id: Readable::read(r)?,
1065 amt_to_forward: Readable::read(r)?,
1066 outgoing_cltv_value: {
1067 let v: u32 = Readable::read(r)?;
1068 r.read_exact(&mut [0; 12])?;
1075 impl Writeable for OnionHopData {
1076 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1078 self.realm.write(w)?;
1079 self.data.write(w)?;
1080 self.hmac.write(w)?;
1085 impl<R: Read> Readable<R> for OnionHopData {
1086 fn read(r: &mut R) -> Result<Self, DecodeError> {
1089 let r: u8 = Readable::read(r)?;
1091 return Err(DecodeError::UnknownVersion);
1095 data: Readable::read(r)?,
1096 hmac: Readable::read(r)?,
1101 impl Writeable for Ping {
1102 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1103 w.size_hint(self.byteslen as usize + 4);
1104 self.ponglen.write(w)?;
1105 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1110 impl<R: Read> Readable<R> for Ping {
1111 fn read(r: &mut R) -> Result<Self, DecodeError> {
1113 ponglen: Readable::read(r)?,
1115 let byteslen = Readable::read(r)?;
1116 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1123 impl Writeable for Pong {
1124 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1125 w.size_hint(self.byteslen as usize + 2);
1126 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1131 impl<R: Read> Readable<R> for Pong {
1132 fn read(r: &mut R) -> Result<Self, DecodeError> {
1135 let byteslen = Readable::read(r)?;
1136 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1143 impl Writeable for UnsignedChannelAnnouncement {
1144 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1145 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1146 self.features.write(w)?;
1147 self.chain_hash.write(w)?;
1148 self.short_channel_id.write(w)?;
1149 self.node_id_1.write(w)?;
1150 self.node_id_2.write(w)?;
1151 self.bitcoin_key_1.write(w)?;
1152 self.bitcoin_key_2.write(w)?;
1153 w.write_all(&self.excess_data[..])?;
1158 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1159 fn read(r: &mut R) -> Result<Self, DecodeError> {
1162 let f: GlobalFeatures = Readable::read(r)?;
1163 if f.requires_unknown_bits() {
1164 return Err(DecodeError::UnknownRequiredFeature);
1168 chain_hash: Readable::read(r)?,
1169 short_channel_id: Readable::read(r)?,
1170 node_id_1: Readable::read(r)?,
1171 node_id_2: Readable::read(r)?,
1172 bitcoin_key_1: Readable::read(r)?,
1173 bitcoin_key_2: Readable::read(r)?,
1175 let mut excess_data = vec![];
1176 r.read_to_end(&mut excess_data)?;
1183 impl_writeable_len_match!(ChannelAnnouncement, {
1184 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1185 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1189 bitcoin_signature_1,
1190 bitcoin_signature_2,
1194 impl Writeable for UnsignedChannelUpdate {
1195 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1196 w.size_hint(64 + self.excess_data.len());
1197 self.chain_hash.write(w)?;
1198 self.short_channel_id.write(w)?;
1199 self.timestamp.write(w)?;
1200 self.flags.write(w)?;
1201 self.cltv_expiry_delta.write(w)?;
1202 self.htlc_minimum_msat.write(w)?;
1203 self.fee_base_msat.write(w)?;
1204 self.fee_proportional_millionths.write(w)?;
1205 w.write_all(&self.excess_data[..])?;
1210 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1211 fn read(r: &mut R) -> Result<Self, DecodeError> {
1213 chain_hash: Readable::read(r)?,
1214 short_channel_id: Readable::read(r)?,
1215 timestamp: Readable::read(r)?,
1216 flags: Readable::read(r)?,
1217 cltv_expiry_delta: Readable::read(r)?,
1218 htlc_minimum_msat: Readable::read(r)?,
1219 fee_base_msat: Readable::read(r)?,
1220 fee_proportional_millionths: Readable::read(r)?,
1222 let mut excess_data = vec![];
1223 r.read_to_end(&mut excess_data)?;
1230 impl_writeable_len_match!(ChannelUpdate, {
1231 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1232 64 + excess_data.len() + 64 }
1238 impl Writeable for ErrorMessage {
1239 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1240 w.size_hint(32 + 2 + self.data.len());
1241 self.channel_id.write(w)?;
1242 (self.data.len() as u16).write(w)?;
1243 w.write_all(self.data.as_bytes())?;
1248 impl<R: Read> Readable<R> for ErrorMessage {
1249 fn read(r: &mut R) -> Result<Self, DecodeError> {
1251 channel_id: Readable::read(r)?,
1253 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1254 let mut data = vec![];
1255 let data_len = r.read_to_end(&mut data)?;
1256 sz = cmp::min(data_len, sz);
1257 match String::from_utf8(data[..sz as usize].to_vec()) {
1259 Err(_) => return Err(DecodeError::InvalidValue),
1266 impl Writeable for UnsignedNodeAnnouncement {
1267 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1268 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1269 self.features.write(w)?;
1270 self.timestamp.write(w)?;
1271 self.node_id.write(w)?;
1272 w.write_all(&self.rgb)?;
1273 self.alias.write(w)?;
1275 let mut addrs_to_encode = self.addresses.clone();
1276 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1277 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1278 let mut addr_len = 0;
1279 for addr in &addrs_to_encode {
1280 addr_len += 1 + addr.len();
1282 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1283 for addr in addrs_to_encode {
1286 w.write_all(&self.excess_address_data[..])?;
1287 w.write_all(&self.excess_data[..])?;
1292 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1293 fn read(r: &mut R) -> Result<Self, DecodeError> {
1294 let features: GlobalFeatures = Readable::read(r)?;
1295 if features.requires_unknown_bits() {
1296 return Err(DecodeError::UnknownRequiredFeature);
1298 let timestamp: u32 = Readable::read(r)?;
1299 let node_id: PublicKey = Readable::read(r)?;
1300 let mut rgb = [0; 3];
1301 r.read_exact(&mut rgb)?;
1302 let alias: [u8; 32] = Readable::read(r)?;
1304 let addr_len: u16 = Readable::read(r)?;
1305 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1306 let mut addr_readpos = 0;
1307 let mut excess = false;
1308 let mut excess_byte = 0;
1310 if addr_len <= addr_readpos { break; }
1311 match Readable::read(r) {
1314 NetAddress::IPv4 { .. } => {
1315 if addresses.len() > 0 {
1316 return Err(DecodeError::ExtraAddressesPerType);
1319 NetAddress::IPv6 { .. } => {
1320 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1321 return Err(DecodeError::ExtraAddressesPerType);
1324 NetAddress::OnionV2 { .. } => {
1325 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1326 return Err(DecodeError::ExtraAddressesPerType);
1329 NetAddress::OnionV3 { .. } => {
1330 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1331 return Err(DecodeError::ExtraAddressesPerType);
1335 if addr_len < addr_readpos + 1 + addr.len() {
1336 return Err(DecodeError::BadLengthDescriptor);
1338 addr_readpos += (1 + addr.len()) as u16;
1339 addresses.push(addr);
1341 Ok(Err(unknown_descriptor)) => {
1343 excess_byte = unknown_descriptor;
1346 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1347 Err(e) => return Err(e),
1351 let mut excess_data = vec![];
1352 let excess_address_data = if addr_readpos < addr_len {
1353 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1354 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1356 excess_address_data[0] = excess_byte;
1361 excess_data.push(excess_byte);
1365 r.read_to_end(&mut excess_data)?;
1366 Ok(UnsignedNodeAnnouncement {
1373 excess_address_data,
1379 impl_writeable_len_match!(NodeAnnouncement, {
1380 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1381 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1391 use ln::msgs::OptionalField;
1392 use util::ser::Writeable;
1393 use secp256k1::key::{PublicKey,SecretKey};
1394 use secp256k1::Secp256k1;
1397 fn encoding_channel_reestablish_no_secret() {
1398 let cr = msgs::ChannelReestablish {
1399 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],
1400 next_local_commitment_number: 3,
1401 next_remote_commitment_number: 4,
1402 data_loss_protect: OptionalField::Absent,
1405 let encoded_value = cr.encode();
1408 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]
1413 fn encoding_channel_reestablish_with_secret() {
1415 let secp_ctx = Secp256k1::new();
1416 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1419 let cr = msgs::ChannelReestablish {
1420 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],
1421 next_local_commitment_number: 3,
1422 next_remote_commitment_number: 4,
1423 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1426 let encoded_value = cr.encode();
1429 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]