1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
3 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
4 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
5 //! server entirely) which handles only channel-related messages you may wish to implement
6 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
9 //! Note that if you go with such an architecture (instead of passing raw socket events to a
10 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
11 //! source node_id of the mssage, however this does allow you to significantly reduce bandwidth
12 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
13 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
14 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
15 //! raw socket events into your non-internet-facing system and then send routing events back to
16 //! track the network on the less-secure system.
18 use secp256k1::key::PublicKey;
19 use secp256k1::{Secp256k1, Signature};
21 use bitcoin::util::hash::Sha256dHash;
22 use bitcoin::blockdata::script::Script;
24 use std::error::Error;
27 use std::result::Result;
29 use util::{byte_utils, events};
30 use util::ser::{Readable, Writeable, Writer};
32 /// An error in decoding a message or struct.
34 pub enum DecodeError {
35 /// A version byte specified something we don't know how to handle.
36 /// Includes unknown realm byte in an OnionHopData packet
38 /// Unknown feature mandating we fail to parse message
39 UnknownRequiredFeature,
40 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
41 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
45 /// node_announcement included more than one address of a given type!
46 ExtraAddressesPerType,
47 /// A length descriptor in the packet didn't describe the later data correctly
48 /// (currently only generated in node_announcement)
50 /// Error from std::io
54 /// Tracks localfeatures which are only in init messages
55 #[derive(Clone, PartialEq)]
56 pub struct LocalFeatures {
61 pub(crate) fn new() -> LocalFeatures {
67 pub(crate) fn supports_data_loss_protect(&self) -> bool {
68 self.flags.len() > 0 && (self.flags[0] & 3) != 0
70 pub(crate) fn requires_data_loss_protect(&self) -> bool {
71 self.flags.len() > 0 && (self.flags[0] & 1) != 0
74 pub(crate) fn initial_routing_sync(&self) -> bool {
75 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
77 pub(crate) fn set_initial_routing_sync(&mut self) {
78 if self.flags.len() == 0 {
79 self.flags.resize(1, 1 << 3);
81 self.flags[0] |= 1 << 3;
85 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
86 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
88 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
89 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
92 pub(crate) fn requires_unknown_bits(&self) -> bool {
93 for (idx, &byte) in self.flags.iter().enumerate() {
94 if idx != 0 && (byte & 0x55) != 0 {
96 } else if idx == 0 && (byte & 0x14) != 0 {
103 pub(crate) fn supports_unknown_bits(&self) -> bool {
104 for (idx, &byte) in self.flags.iter().enumerate() {
105 if idx != 0 && byte != 0 {
107 } else if idx == 0 && (byte & 0xc4) != 0 {
115 /// Tracks globalfeatures which are in init messages and routing announcements
116 #[derive(Clone, PartialEq)]
117 pub struct GlobalFeatures {
121 impl GlobalFeatures {
122 pub(crate) fn new() -> GlobalFeatures {
128 pub(crate) fn requires_unknown_bits(&self) -> bool {
129 for &byte in self.flags.iter() {
130 if (byte & 0x55) != 0 {
137 pub(crate) fn supports_unknown_bits(&self) -> bool {
138 for &byte in self.flags.iter() {
147 /// An init message to be sent or received from a peer
149 pub(crate) global_features: GlobalFeatures,
150 pub(crate) local_features: LocalFeatures,
153 /// An error message to be sent or received from a peer
154 pub struct ErrorMessage {
155 pub(crate) channel_id: [u8; 32],
156 pub(crate) data: String,
159 /// A ping message to be sent or received from a peer
161 pub(crate) ponglen: u16,
162 pub(crate) byteslen: u16,
165 /// A pong message to be sent or received from a peer
167 pub(crate) byteslen: u16,
170 /// An open_channel message to be sent or received from a peer
171 pub struct OpenChannel {
172 pub(crate) chain_hash: Sha256dHash,
173 pub(crate) temporary_channel_id: [u8; 32],
174 pub(crate) funding_satoshis: u64,
175 pub(crate) push_msat: u64,
176 pub(crate) dust_limit_satoshis: u64,
177 pub(crate) max_htlc_value_in_flight_msat: u64,
178 pub(crate) channel_reserve_satoshis: u64,
179 pub(crate) htlc_minimum_msat: u64,
180 pub(crate) feerate_per_kw: u32,
181 pub(crate) to_self_delay: u16,
182 pub(crate) max_accepted_htlcs: u16,
183 pub(crate) funding_pubkey: PublicKey,
184 pub(crate) revocation_basepoint: PublicKey,
185 pub(crate) payment_basepoint: PublicKey,
186 pub(crate) delayed_payment_basepoint: PublicKey,
187 pub(crate) htlc_basepoint: PublicKey,
188 pub(crate) first_per_commitment_point: PublicKey,
189 pub(crate) channel_flags: u8,
190 pub(crate) shutdown_scriptpubkey: Option<Script>,
193 /// An accept_channel message to be sent or received from a peer
194 pub struct AcceptChannel {
195 pub(crate) temporary_channel_id: [u8; 32],
196 pub(crate) dust_limit_satoshis: u64,
197 pub(crate) max_htlc_value_in_flight_msat: u64,
198 pub(crate) channel_reserve_satoshis: u64,
199 pub(crate) htlc_minimum_msat: u64,
200 pub(crate) minimum_depth: u32,
201 pub(crate) to_self_delay: u16,
202 pub(crate) max_accepted_htlcs: u16,
203 pub(crate) funding_pubkey: PublicKey,
204 pub(crate) revocation_basepoint: PublicKey,
205 pub(crate) payment_basepoint: PublicKey,
206 pub(crate) delayed_payment_basepoint: PublicKey,
207 pub(crate) htlc_basepoint: PublicKey,
208 pub(crate) first_per_commitment_point: PublicKey,
209 pub(crate) shutdown_scriptpubkey: Option<Script>,
212 /// A funding_created message to be sent or received from a peer
213 pub struct FundingCreated {
214 pub(crate) temporary_channel_id: [u8; 32],
215 pub(crate) funding_txid: Sha256dHash,
216 pub(crate) funding_output_index: u16,
217 pub(crate) signature: Signature,
220 /// A funding_signed message to be sent or received from a peer
221 pub struct FundingSigned {
222 pub(crate) channel_id: [u8; 32],
223 pub(crate) signature: Signature,
226 /// A funding_locked message to be sent or received from a peer
228 pub struct FundingLocked {
229 pub(crate) channel_id: [u8; 32],
230 pub(crate) next_per_commitment_point: PublicKey,
233 /// A shutdown message to be sent or received from a peer
234 pub struct Shutdown {
235 pub(crate) channel_id: [u8; 32],
236 pub(crate) scriptpubkey: Script,
239 /// A closing_signed message to be sent or received from a peer
240 pub struct ClosingSigned {
241 pub(crate) channel_id: [u8; 32],
242 pub(crate) fee_satoshis: u64,
243 pub(crate) signature: Signature,
246 /// An update_add_htlc message to be sent or received from a peer
248 pub struct UpdateAddHTLC {
249 pub(crate) channel_id: [u8; 32],
250 pub(crate) htlc_id: u64,
251 pub(crate) amount_msat: u64,
252 pub(crate) payment_hash: [u8; 32],
253 pub(crate) cltv_expiry: u32,
254 pub(crate) onion_routing_packet: OnionPacket,
257 /// An update_fulfill_htlc message to be sent or received from a peer
259 pub struct UpdateFulfillHTLC {
260 pub(crate) channel_id: [u8; 32],
261 pub(crate) htlc_id: u64,
262 pub(crate) payment_preimage: [u8; 32],
265 /// An update_fail_htlc message to be sent or received from a peer
267 pub struct UpdateFailHTLC {
268 pub(crate) channel_id: [u8; 32],
269 pub(crate) htlc_id: u64,
270 pub(crate) reason: OnionErrorPacket,
273 /// An update_fail_malformed_htlc message to be sent or received from a peer
275 pub struct UpdateFailMalformedHTLC {
276 pub(crate) channel_id: [u8; 32],
277 pub(crate) htlc_id: u64,
278 pub(crate) sha256_of_onion: [u8; 32],
279 pub(crate) failure_code: u16,
282 /// A commitment_signed message to be sent or received from a peer
284 pub struct CommitmentSigned {
285 pub(crate) channel_id: [u8; 32],
286 pub(crate) signature: Signature,
287 pub(crate) htlc_signatures: Vec<Signature>,
290 /// A revoke_and_ack message to be sent or received from a peer
291 pub struct RevokeAndACK {
292 pub(crate) channel_id: [u8; 32],
293 pub(crate) per_commitment_secret: [u8; 32],
294 pub(crate) next_per_commitment_point: PublicKey,
297 /// An update_fee message to be sent or received from a peer
298 pub struct UpdateFee {
299 pub(crate) channel_id: [u8; 32],
300 pub(crate) feerate_per_kw: u32,
303 pub(crate) struct DataLossProtect {
304 pub(crate) your_last_per_commitment_secret: [u8; 32],
305 pub(crate) my_current_per_commitment_point: PublicKey,
308 /// A channel_reestablish message to be sent or received from a peer
309 pub struct ChannelReestablish {
310 pub(crate) channel_id: [u8; 32],
311 pub(crate) next_local_commitment_number: u64,
312 pub(crate) next_remote_commitment_number: u64,
313 pub(crate) data_loss_protect: Option<DataLossProtect>,
316 /// An announcement_signatures message to be sent or received from a peer
318 pub struct AnnouncementSignatures {
319 pub(crate) channel_id: [u8; 32],
320 pub(crate) short_channel_id: u64,
321 pub(crate) node_signature: Signature,
322 pub(crate) bitcoin_signature: Signature,
325 /// An address which can be used to connect to a remote peer
327 pub enum NetAddress {
328 /// An IPv4 address/port on which the peer is listenting.
330 /// The 4-byte IPv4 address
332 /// The port on which the node is listenting
335 /// An IPv6 address/port on which the peer is listenting.
337 /// The 16-byte IPv6 address
339 /// The port on which the node is listenting
342 /// An old-style Tor onion address/port on which the peer is listening.
344 /// The bytes (usually encoded in base32 with ".onion" appended)
346 /// The port on which the node is listenting
349 /// A new-style Tor onion address/port on which the peer is listening.
350 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
351 /// wrap as base32 and append ".onion".
353 /// The ed25519 long-term public key of the peer
354 ed25519_pubkey: [u8; 32],
355 /// The checksum of the pubkey and version, as included in the onion address
357 /// The version byte, as defined by the Tor Onion v3 spec.
359 /// The port on which the node is listenting
364 fn get_id(&self) -> u8 {
366 &NetAddress::IPv4 {..} => { 1 },
367 &NetAddress::IPv6 {..} => { 2 },
368 &NetAddress::OnionV2 {..} => { 3 },
369 &NetAddress::OnionV3 {..} => { 4 },
374 // Only exposed as broadcast of node_announcement should be filtered by node_id
375 /// The unsigned part of a node_announcement
376 pub struct UnsignedNodeAnnouncement {
377 pub(crate) features: GlobalFeatures,
378 pub(crate) timestamp: u32,
379 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
381 pub node_id: PublicKey,
382 pub(crate) rgb: [u8; 3],
383 pub(crate) alias: [u8; 32],
384 /// List of addresses on which this node is reachable. Note that you may only have up to one
385 /// address of each type, if you have more, they may be silently discarded or we may panic!
386 pub(crate) addresses: Vec<NetAddress>,
387 pub(crate) excess_address_data: Vec<u8>,
388 pub(crate) excess_data: Vec<u8>,
390 /// A node_announcement message to be sent or received from a peer
391 pub struct NodeAnnouncement {
392 pub(crate) signature: Signature,
393 pub(crate) contents: UnsignedNodeAnnouncement,
396 // Only exposed as broadcast of channel_announcement should be filtered by node_id
397 /// The unsigned part of a channel_announcement
398 #[derive(PartialEq, Clone)]
399 pub struct UnsignedChannelAnnouncement {
400 pub(crate) features: GlobalFeatures,
401 pub(crate) chain_hash: Sha256dHash,
402 pub(crate) short_channel_id: u64,
403 /// One of the two node_ids which are endpoints of this channel
404 pub node_id_1: PublicKey,
405 /// The other of the two node_ids which are endpoints of this channel
406 pub node_id_2: PublicKey,
407 pub(crate) bitcoin_key_1: PublicKey,
408 pub(crate) bitcoin_key_2: PublicKey,
409 pub(crate) excess_data: Vec<u8>,
411 /// A channel_announcement message to be sent or received from a peer
412 #[derive(PartialEq, Clone)]
413 pub struct ChannelAnnouncement {
414 pub(crate) node_signature_1: Signature,
415 pub(crate) node_signature_2: Signature,
416 pub(crate) bitcoin_signature_1: Signature,
417 pub(crate) bitcoin_signature_2: Signature,
418 pub(crate) contents: UnsignedChannelAnnouncement,
421 #[derive(PartialEq, Clone)]
422 pub(crate) struct UnsignedChannelUpdate {
423 pub(crate) chain_hash: Sha256dHash,
424 pub(crate) short_channel_id: u64,
425 pub(crate) timestamp: u32,
426 pub(crate) flags: u16,
427 pub(crate) cltv_expiry_delta: u16,
428 pub(crate) htlc_minimum_msat: u64,
429 pub(crate) fee_base_msat: u32,
430 pub(crate) fee_proportional_millionths: u32,
431 pub(crate) excess_data: Vec<u8>,
433 /// A channel_update message to be sent or received from a peer
434 #[derive(PartialEq, Clone)]
435 pub struct ChannelUpdate {
436 pub(crate) signature: Signature,
437 pub(crate) contents: UnsignedChannelUpdate,
440 /// Used to put an error message in a HandleError
441 pub enum ErrorAction {
442 /// The peer took some action which made us think they were useless. Disconnect them.
444 /// An error message which we should make an effort to send before we disconnect.
445 msg: Option<ErrorMessage>
447 /// The peer did something harmless that we weren't able to process, just log and ignore
449 /// The peer did something incorrect. Tell them.
451 /// The message to send.
456 /// An Err type for failure to process messages.
457 pub struct HandleError { //TODO: rename me
458 /// A human-readable message describing the error
459 pub err: &'static str,
460 /// The action which should be taken against the offending peer.
461 pub action: Option<ErrorAction>, //TODO: Make this required
464 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
465 /// transaction updates if they were pending.
466 pub struct CommitmentUpdate {
467 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
468 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
469 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
470 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
471 pub(crate) update_fee: Option<UpdateFee>,
472 pub(crate) commitment_signed: CommitmentSigned,
475 /// The information we received from a peer along the route of a payment we originated. This is
476 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
477 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
478 pub enum HTLCFailChannelUpdate {
479 /// We received an error which included a full ChannelUpdate message.
480 ChannelUpdateMessage {
481 /// The unwrapped message we received
484 /// We received an error which indicated only that a channel has been closed
486 /// The short_channel_id which has now closed.
487 short_channel_id: u64,
491 /// A trait to describe an object which can receive channel messages.
493 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
494 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
495 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
497 /// Handle an incoming open_channel message from the given peer.
498 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
499 /// Handle an incoming accept_channel message from the given peer.
500 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
501 /// Handle an incoming funding_created message from the given peer.
502 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
503 /// Handle an incoming funding_signed message from the given peer.
504 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
505 /// Handle an incoming funding_locked message from the given peer.
506 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
509 /// Handle an incoming shutdown message from the given peer.
510 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
511 /// Handle an incoming closing_signed message from the given peer.
512 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
515 /// Handle an incoming update_add_htlc message from the given peer.
516 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
517 /// Handle an incoming update_fulfill_htlc message from the given peer.
518 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
519 /// Handle an incoming update_fail_htlc message from the given peer.
520 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
521 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
522 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
523 /// Handle an incoming commitment_signed message from the given peer.
524 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
525 /// Handle an incoming revoke_and_ack message from the given peer.
526 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
528 /// Handle an incoming update_fee message from the given peer.
529 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
531 // Channel-to-announce:
532 /// Handle an incoming announcement_signatures message from the given peer.
533 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
535 // Connection loss/reestablish:
536 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
537 /// is believed to be possible in the future (eg they're sending us messages we don't
538 /// understand or indicate they require unknown feature bits), no_connection_possible is set
539 /// and any outstanding channels should be failed.
540 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
542 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
543 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
544 /// Handle an incoming channel_reestablish message from the given peer.
545 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
548 /// Handle an incoming error message from the given peer.
549 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
552 /// A trait to describe an object which can receive routing messages.
553 pub trait RoutingMessageHandler : Send + Sync {
554 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
555 /// false or returning an Err otherwise.
556 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
557 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
558 /// or returning an Err otherwise.
559 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
560 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
561 /// false or returning an Err otherwise.
562 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
563 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
564 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
567 pub(crate) struct OnionRealm0HopData {
568 pub(crate) short_channel_id: u64,
569 pub(crate) amt_to_forward: u64,
570 pub(crate) outgoing_cltv_value: u32,
571 // 12 bytes of 0-padding
574 mod fuzzy_internal_msgs {
575 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
576 // them from untrusted input):
578 use super::OnionRealm0HopData;
579 pub struct OnionHopData {
580 pub(crate) realm: u8,
581 pub(crate) data: OnionRealm0HopData,
582 pub(crate) hmac: [u8; 32],
584 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
586 pub struct DecodedOnionErrorPacket {
587 pub(crate) hmac: [u8; 32],
588 pub(crate) failuremsg: Vec<u8>,
589 pub(crate) pad: Vec<u8>,
592 #[cfg(feature = "fuzztarget")]
593 pub use self::fuzzy_internal_msgs::*;
594 #[cfg(not(feature = "fuzztarget"))]
595 pub(crate) use self::fuzzy_internal_msgs::*;
598 pub(crate) struct OnionPacket {
599 pub(crate) version: u8,
600 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
601 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
602 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
603 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
604 pub(crate) hop_data: [u8; 20*65],
605 pub(crate) hmac: [u8; 32],
609 pub(crate) struct OnionErrorPacket {
610 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
611 // (TODO) We limit it in decode to much lower...
612 pub(crate) data: Vec<u8>,
615 impl Error for DecodeError {
616 fn description(&self) -> &str {
618 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
619 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
620 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
621 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
622 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
623 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
624 DecodeError::Io(ref e) => e.description(),
628 impl fmt::Display for DecodeError {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630 f.write_str(self.description())
634 impl fmt::Debug for HandleError {
635 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
636 f.write_str(self.err)
640 impl From<::std::io::Error> for DecodeError {
641 fn from(e: ::std::io::Error) -> Self {
642 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
643 DecodeError::ShortRead
650 impl_writeable_len_match!(AcceptChannel, {
651 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
654 temporary_channel_id,
656 max_htlc_value_in_flight_msat,
657 channel_reserve_satoshis,
663 revocation_basepoint,
665 delayed_payment_basepoint,
667 first_per_commitment_point,
668 shutdown_scriptpubkey
671 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
678 impl Writeable for ChannelReestablish {
679 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
680 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
681 self.channel_id.write(w)?;
682 self.next_local_commitment_number.write(w)?;
683 self.next_remote_commitment_number.write(w)?;
684 if let Some(ref data_loss_protect) = self.data_loss_protect {
685 data_loss_protect.your_last_per_commitment_secret.write(w)?;
686 data_loss_protect.my_current_per_commitment_point.write(w)?;
692 impl<R: Read> Readable<R> for ChannelReestablish{
693 fn read(r: &mut R) -> Result<Self, DecodeError> {
695 channel_id: Readable::read(r)?,
696 next_local_commitment_number: Readable::read(r)?,
697 next_remote_commitment_number: Readable::read(r)?,
699 match <[u8; 32] as Readable<R>>::read(r) {
700 Ok(your_last_per_commitment_secret) =>
701 Some(DataLossProtect {
702 your_last_per_commitment_secret,
703 my_current_per_commitment_point: Readable::read(r)?,
705 Err(DecodeError::ShortRead) => None,
706 Err(e) => return Err(e)
713 impl_writeable!(ClosingSigned, 32+8+64, {
719 impl_writeable_len_match!(CommitmentSigned, {
720 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
727 impl_writeable_len_match!(DecodedOnionErrorPacket, {
728 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
735 impl_writeable!(FundingCreated, 32+32+2+64, {
736 temporary_channel_id,
738 funding_output_index,
742 impl_writeable!(FundingSigned, 32+64, {
747 impl_writeable!(FundingLocked, 32+33, {
749 next_per_commitment_point
752 impl_writeable_len_match!(GlobalFeatures, {
753 { GlobalFeatures { ref flags }, flags.len() + 2 }
758 impl_writeable_len_match!(LocalFeatures, {
759 { LocalFeatures { ref flags }, flags.len() + 2 }
764 impl_writeable_len_match!(Init, {
765 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
771 impl_writeable_len_match!(OpenChannel, {
772 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
773 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
776 temporary_channel_id,
780 max_htlc_value_in_flight_msat,
781 channel_reserve_satoshis,
787 revocation_basepoint,
789 delayed_payment_basepoint,
791 first_per_commitment_point,
793 shutdown_scriptpubkey
796 impl_writeable!(RevokeAndACK, 32+32+33, {
798 per_commitment_secret,
799 next_per_commitment_point
802 impl_writeable_len_match!(Shutdown, {
803 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
809 impl_writeable_len_match!(UpdateFailHTLC, {
810 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
817 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
824 impl_writeable!(UpdateFee, 32+4, {
829 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
835 impl_writeable_len_match!(OnionErrorPacket, {
836 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
841 impl Writeable for OnionPacket {
842 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
843 w.size_hint(1 + 33 + 20*65 + 32);
844 self.version.write(w)?;
845 match self.public_key {
846 Ok(pubkey) => pubkey.write(w)?,
847 Err(_) => [0u8;33].write(w)?,
849 w.write_all(&self.hop_data)?;
855 impl<R: Read> Readable<R> for OnionPacket {
856 fn read(r: &mut R) -> Result<Self, DecodeError> {
858 version: Readable::read(r)?,
860 let mut buf = [0u8;33];
861 r.read_exact(&mut buf)?;
862 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
864 hop_data: Readable::read(r)?,
865 hmac: Readable::read(r)?,
870 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
879 impl Writeable for OnionRealm0HopData {
880 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
882 self.short_channel_id.write(w)?;
883 self.amt_to_forward.write(w)?;
884 self.outgoing_cltv_value.write(w)?;
885 w.write_all(&[0;12])?;
890 impl<R: Read> Readable<R> for OnionRealm0HopData {
891 fn read(r: &mut R) -> Result<Self, DecodeError> {
892 Ok(OnionRealm0HopData {
893 short_channel_id: Readable::read(r)?,
894 amt_to_forward: Readable::read(r)?,
895 outgoing_cltv_value: {
896 let v: u32 = Readable::read(r)?;
897 r.read_exact(&mut [0; 12])?;
904 impl Writeable for OnionHopData {
905 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
907 self.realm.write(w)?;
914 impl<R: Read> Readable<R> for OnionHopData {
915 fn read(r: &mut R) -> Result<Self, DecodeError> {
918 let r: u8 = Readable::read(r)?;
920 return Err(DecodeError::UnknownVersion);
924 data: Readable::read(r)?,
925 hmac: Readable::read(r)?,
930 impl Writeable for Ping {
931 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
932 w.size_hint(self.byteslen as usize + 4);
933 self.ponglen.write(w)?;
934 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
939 impl<R: Read> Readable<R> for Ping {
940 fn read(r: &mut R) -> Result<Self, DecodeError> {
942 ponglen: Readable::read(r)?,
944 let byteslen = Readable::read(r)?;
945 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
952 impl Writeable for Pong {
953 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
954 w.size_hint(self.byteslen as usize + 2);
955 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
960 impl<R: Read> Readable<R> for Pong {
961 fn read(r: &mut R) -> Result<Self, DecodeError> {
964 let byteslen = Readable::read(r)?;
965 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
972 impl Writeable for UnsignedChannelAnnouncement {
973 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
974 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
975 self.features.write(w)?;
976 self.chain_hash.write(w)?;
977 self.short_channel_id.write(w)?;
978 self.node_id_1.write(w)?;
979 self.node_id_2.write(w)?;
980 self.bitcoin_key_1.write(w)?;
981 self.bitcoin_key_2.write(w)?;
982 w.write_all(&self.excess_data[..])?;
987 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
988 fn read(r: &mut R) -> Result<Self, DecodeError> {
991 let f: GlobalFeatures = Readable::read(r)?;
992 if f.requires_unknown_bits() {
993 return Err(DecodeError::UnknownRequiredFeature);
997 chain_hash: Readable::read(r)?,
998 short_channel_id: Readable::read(r)?,
999 node_id_1: Readable::read(r)?,
1000 node_id_2: Readable::read(r)?,
1001 bitcoin_key_1: Readable::read(r)?,
1002 bitcoin_key_2: Readable::read(r)?,
1004 let mut excess_data = vec![];
1005 r.read_to_end(&mut excess_data)?;
1012 impl_writeable_len_match!(ChannelAnnouncement, {
1013 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1014 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1018 bitcoin_signature_1,
1019 bitcoin_signature_2,
1023 impl Writeable for UnsignedChannelUpdate {
1024 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1025 w.size_hint(64 + self.excess_data.len());
1026 self.chain_hash.write(w)?;
1027 self.short_channel_id.write(w)?;
1028 self.timestamp.write(w)?;
1029 self.flags.write(w)?;
1030 self.cltv_expiry_delta.write(w)?;
1031 self.htlc_minimum_msat.write(w)?;
1032 self.fee_base_msat.write(w)?;
1033 self.fee_proportional_millionths.write(w)?;
1034 w.write_all(&self.excess_data[..])?;
1039 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1040 fn read(r: &mut R) -> Result<Self, DecodeError> {
1042 chain_hash: Readable::read(r)?,
1043 short_channel_id: Readable::read(r)?,
1044 timestamp: Readable::read(r)?,
1045 flags: Readable::read(r)?,
1046 cltv_expiry_delta: Readable::read(r)?,
1047 htlc_minimum_msat: Readable::read(r)?,
1048 fee_base_msat: Readable::read(r)?,
1049 fee_proportional_millionths: Readable::read(r)?,
1051 let mut excess_data = vec![];
1052 r.read_to_end(&mut excess_data)?;
1059 impl_writeable_len_match!(ChannelUpdate, {
1060 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1061 64 + excess_data.len() + 64 }
1067 impl Writeable for ErrorMessage {
1068 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1069 w.size_hint(32 + 2 + self.data.len());
1070 self.channel_id.write(w)?;
1071 (self.data.len() as u16).write(w)?;
1072 w.write_all(self.data.as_bytes())?;
1077 impl<R: Read> Readable<R> for ErrorMessage {
1078 fn read(r: &mut R) -> Result<Self, DecodeError> {
1080 channel_id: Readable::read(r)?,
1082 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1083 let mut data = vec![];
1084 let data_len = r.read_to_end(&mut data)?;
1085 sz = cmp::min(data_len, sz);
1086 match String::from_utf8(data[..sz as usize].to_vec()) {
1088 Err(_) => return Err(DecodeError::InvalidValue),
1095 impl Writeable for UnsignedNodeAnnouncement {
1096 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1097 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1098 self.features.write(w)?;
1099 self.timestamp.write(w)?;
1100 self.node_id.write(w)?;
1101 w.write_all(&self.rgb)?;
1102 self.alias.write(w)?;
1104 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1105 let mut addrs_to_encode = self.addresses.clone();
1106 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1107 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1108 for addr in addrs_to_encode.iter() {
1110 &NetAddress::IPv4{addr, port} => {
1112 addr_slice.extend_from_slice(&addr);
1113 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1115 &NetAddress::IPv6{addr, port} => {
1117 addr_slice.extend_from_slice(&addr);
1118 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1120 &NetAddress::OnionV2{addr, port} => {
1122 addr_slice.extend_from_slice(&addr);
1123 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1125 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1127 addr_slice.extend_from_slice(&ed25519_pubkey);
1128 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1129 addr_slice.push(version);
1130 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1134 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1135 w.write_all(&addr_slice[..])?;
1136 w.write_all(&self.excess_address_data[..])?;
1137 w.write_all(&self.excess_data[..])?;
1142 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1143 fn read(r: &mut R) -> Result<Self, DecodeError> {
1144 let features: GlobalFeatures = Readable::read(r)?;
1145 if features.requires_unknown_bits() {
1146 return Err(DecodeError::UnknownRequiredFeature);
1148 let timestamp: u32 = Readable::read(r)?;
1149 let node_id: PublicKey = Readable::read(r)?;
1150 let mut rgb = [0; 3];
1151 r.read_exact(&mut rgb)?;
1152 let alias: [u8; 32] = Readable::read(r)?;
1154 let addrlen: u16 = Readable::read(r)?;
1155 let mut addr_readpos = 0;
1156 let mut addresses = Vec::with_capacity(4);
1160 if addrlen <= addr_readpos { break; }
1161 f = Readable::read(r)?;
1164 if addresses.len() > 0 {
1165 return Err(DecodeError::ExtraAddressesPerType);
1167 if addrlen < addr_readpos + 1 + 6 {
1168 return Err(DecodeError::BadLengthDescriptor);
1170 addresses.push(NetAddress::IPv4 {
1172 let mut addr = [0; 4];
1173 r.read_exact(&mut addr)?;
1176 port: Readable::read(r)?,
1178 addr_readpos += 1 + 6
1181 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1182 return Err(DecodeError::ExtraAddressesPerType);
1184 if addrlen < addr_readpos + 1 + 18 {
1185 return Err(DecodeError::BadLengthDescriptor);
1187 addresses.push(NetAddress::IPv6 {
1189 let mut addr = [0; 16];
1190 r.read_exact(&mut addr)?;
1193 port: Readable::read(r)?,
1195 addr_readpos += 1 + 18
1198 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1199 return Err(DecodeError::ExtraAddressesPerType);
1201 if addrlen < addr_readpos + 1 + 12 {
1202 return Err(DecodeError::BadLengthDescriptor);
1204 addresses.push(NetAddress::OnionV2 {
1206 let mut addr = [0; 10];
1207 r.read_exact(&mut addr)?;
1210 port: Readable::read(r)?,
1212 addr_readpos += 1 + 12
1215 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1216 return Err(DecodeError::ExtraAddressesPerType);
1218 if addrlen < addr_readpos + 1 + 37 {
1219 return Err(DecodeError::BadLengthDescriptor);
1221 addresses.push(NetAddress::OnionV3 {
1222 ed25519_pubkey: Readable::read(r)?,
1223 checksum: Readable::read(r)?,
1224 version: Readable::read(r)?,
1225 port: Readable::read(r)?,
1227 addr_readpos += 1 + 37
1229 _ => { excess = 1; break; }
1233 let mut excess_data = vec![];
1234 let excess_address_data = if addr_readpos < addrlen {
1235 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1236 r.read_exact(&mut excess_address_data[excess..])?;
1238 excess_address_data[0] = f;
1243 excess_data.push(f);
1248 Ok(UnsignedNodeAnnouncement {
1250 timestamp: timestamp,
1254 addresses: addresses,
1255 excess_address_data: excess_address_data,
1257 r.read_to_end(&mut excess_data)?;
1264 impl_writeable_len_match!(NodeAnnouncement, {
1265 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1266 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1276 use util::ser::Writeable;
1277 use secp256k1::key::{PublicKey,SecretKey};
1278 use secp256k1::Secp256k1;
1281 fn encoding_channel_reestablish_no_secret() {
1282 let cr = msgs::ChannelReestablish {
1283 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],
1284 next_local_commitment_number: 3,
1285 next_remote_commitment_number: 4,
1286 data_loss_protect: None,
1289 let encoded_value = cr.encode();
1292 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]
1297 fn encoding_channel_reestablish_with_secret() {
1299 let secp_ctx = Secp256k1::new();
1300 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1303 let cr = msgs::ChannelReestablish {
1304 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],
1305 next_local_commitment_number: 3,
1306 next_remote_commitment_number: 4,
1307 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1310 let encoded_value = cr.encode();
1313 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]