1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
2 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
3 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
4 //! server entirely) which handles only channel-related messages you may wish to implement
5 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
7 //! Note that if you go with such an architecture (instead of passing raw socket events to a
8 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
9 //! source node_id of the mssage, however this does allow you to significantly reduce bandwidth
10 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
11 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
12 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
13 //! raw socket events into your non-internet-facing system and then send routing events back to
14 //! track the network on the less-secure system.
16 use secp256k1::key::PublicKey;
17 use secp256k1::{Secp256k1, Signature};
19 use bitcoin::util::hash::Sha256dHash;
20 use bitcoin::blockdata::script::Script;
22 use std::error::Error;
25 use std::result::Result;
27 use util::{byte_utils, events};
28 use util::ser::{Readable, Writeable, Writer};
30 /// An error in decoding a message or struct.
32 pub enum DecodeError {
33 /// A version byte specified something we don't know how to handle.
34 /// Includes unknown realm byte in an OnionHopData packet
36 /// Unknown feature mandating we fail to parse message
37 UnknownRequiredFeature,
38 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
39 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
43 /// node_announcement included more than one address of a given type!
44 ExtraAddressesPerType,
45 /// A length descriptor in the packet didn't describe the later data correctly
46 /// (currently only generated in node_announcement)
48 /// Error from std::io
52 /// Tracks localfeatures which are only in init messages
53 #[derive(Clone, PartialEq)]
54 pub struct LocalFeatures {
59 pub(crate) fn new() -> LocalFeatures {
65 pub(crate) fn supports_data_loss_protect(&self) -> bool {
66 self.flags.len() > 0 && (self.flags[0] & 3) != 0
68 pub(crate) fn requires_data_loss_protect(&self) -> bool {
69 self.flags.len() > 0 && (self.flags[0] & 1) != 0
72 pub(crate) fn initial_routing_sync(&self) -> bool {
73 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
75 pub(crate) fn set_initial_routing_sync(&mut self) {
76 if self.flags.len() == 0 {
77 self.flags.resize(1, 1 << 3);
79 self.flags[0] |= 1 << 3;
83 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
84 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
86 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
87 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
90 pub(crate) fn requires_unknown_bits(&self) -> bool {
91 for (idx, &byte) in self.flags.iter().enumerate() {
92 if idx != 0 && (byte & 0x55) != 0 {
94 } else if idx == 0 && (byte & 0x14) != 0 {
101 pub(crate) fn supports_unknown_bits(&self) -> bool {
102 for (idx, &byte) in self.flags.iter().enumerate() {
103 if idx != 0 && byte != 0 {
105 } else if idx == 0 && (byte & 0xc4) != 0 {
113 /// Tracks globalfeatures which are in init messages and routing announcements
114 #[derive(Clone, PartialEq)]
115 pub struct GlobalFeatures {
119 impl GlobalFeatures {
120 pub(crate) fn new() -> GlobalFeatures {
126 pub(crate) fn requires_unknown_bits(&self) -> bool {
127 for &byte in self.flags.iter() {
128 if (byte & 0x55) != 0 {
135 pub(crate) fn supports_unknown_bits(&self) -> bool {
136 for &byte in self.flags.iter() {
145 /// An init message to be sent or received from a peer
147 pub(crate) global_features: GlobalFeatures,
148 pub(crate) local_features: LocalFeatures,
151 /// An error message to be sent or received from a peer
152 pub struct ErrorMessage {
153 pub(crate) channel_id: [u8; 32],
154 pub(crate) data: String,
157 /// A ping message to be sent or received from a peer
159 pub(crate) ponglen: u16,
160 pub(crate) byteslen: u16,
163 /// A pong message to be sent or received from a peer
165 pub(crate) byteslen: u16,
168 /// An open_channel message to be sent or received from a peer
169 pub struct OpenChannel {
170 pub(crate) chain_hash: Sha256dHash,
171 pub(crate) temporary_channel_id: [u8; 32],
172 pub(crate) funding_satoshis: u64,
173 pub(crate) push_msat: u64,
174 pub(crate) dust_limit_satoshis: u64,
175 pub(crate) max_htlc_value_in_flight_msat: u64,
176 pub(crate) channel_reserve_satoshis: u64,
177 pub(crate) htlc_minimum_msat: u64,
178 pub(crate) feerate_per_kw: u32,
179 pub(crate) to_self_delay: u16,
180 pub(crate) max_accepted_htlcs: u16,
181 pub(crate) funding_pubkey: PublicKey,
182 pub(crate) revocation_basepoint: PublicKey,
183 pub(crate) payment_basepoint: PublicKey,
184 pub(crate) delayed_payment_basepoint: PublicKey,
185 pub(crate) htlc_basepoint: PublicKey,
186 pub(crate) first_per_commitment_point: PublicKey,
187 pub(crate) channel_flags: u8,
188 pub(crate) shutdown_scriptpubkey: Option<Script>,
191 /// An accept_channel message to be sent or received from a peer
192 pub struct AcceptChannel {
193 pub(crate) temporary_channel_id: [u8; 32],
194 pub(crate) dust_limit_satoshis: u64,
195 pub(crate) max_htlc_value_in_flight_msat: u64,
196 pub(crate) channel_reserve_satoshis: u64,
197 pub(crate) htlc_minimum_msat: u64,
198 pub(crate) minimum_depth: u32,
199 pub(crate) to_self_delay: u16,
200 pub(crate) max_accepted_htlcs: u16,
201 pub(crate) funding_pubkey: PublicKey,
202 pub(crate) revocation_basepoint: PublicKey,
203 pub(crate) payment_basepoint: PublicKey,
204 pub(crate) delayed_payment_basepoint: PublicKey,
205 pub(crate) htlc_basepoint: PublicKey,
206 pub(crate) first_per_commitment_point: PublicKey,
207 pub(crate) shutdown_scriptpubkey: Option<Script>,
210 /// A funding_created message to be sent or received from a peer
211 pub struct FundingCreated {
212 pub(crate) temporary_channel_id: [u8; 32],
213 pub(crate) funding_txid: Sha256dHash,
214 pub(crate) funding_output_index: u16,
215 pub(crate) signature: Signature,
218 /// A funding_signed message to be sent or received from a peer
219 pub struct FundingSigned {
220 pub(crate) channel_id: [u8; 32],
221 pub(crate) signature: Signature,
224 /// A funding_locked message to be sent or received from a peer
225 pub struct FundingLocked {
226 pub(crate) channel_id: [u8; 32],
227 pub(crate) next_per_commitment_point: PublicKey,
230 /// A shutdown message to be sent or received from a peer
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 pub struct ClosingSigned {
238 pub(crate) channel_id: [u8; 32],
239 pub(crate) fee_satoshis: u64,
240 pub(crate) signature: Signature,
243 /// An update_add_htlc message to be sent or received from a peer
245 pub struct UpdateAddHTLC {
246 pub(crate) channel_id: [u8; 32],
247 pub(crate) htlc_id: u64,
248 pub(crate) amount_msat: u64,
249 pub(crate) payment_hash: [u8; 32],
250 pub(crate) cltv_expiry: u32,
251 pub(crate) onion_routing_packet: OnionPacket,
254 /// An update_fulfill_htlc message to be sent or received from a peer
256 pub struct UpdateFulfillHTLC {
257 pub(crate) channel_id: [u8; 32],
258 pub(crate) htlc_id: u64,
259 pub(crate) payment_preimage: [u8; 32],
262 /// An update_fail_htlc message to be sent or received from a peer
264 pub struct UpdateFailHTLC {
265 pub(crate) channel_id: [u8; 32],
266 pub(crate) htlc_id: u64,
267 pub(crate) reason: OnionErrorPacket,
270 /// An update_fail_malformed_htlc message to be sent or received from a peer
272 pub struct UpdateFailMalformedHTLC {
273 pub(crate) channel_id: [u8; 32],
274 pub(crate) htlc_id: u64,
275 pub(crate) sha256_of_onion: [u8; 32],
276 pub(crate) failure_code: u16,
279 /// A commitment_signed message to be sent or received from a peer
281 pub struct CommitmentSigned {
282 pub(crate) channel_id: [u8; 32],
283 pub(crate) signature: Signature,
284 pub(crate) htlc_signatures: Vec<Signature>,
287 /// A revoke_and_ack message to be sent or received from a peer
288 pub struct RevokeAndACK {
289 pub(crate) channel_id: [u8; 32],
290 pub(crate) per_commitment_secret: [u8; 32],
291 pub(crate) next_per_commitment_point: PublicKey,
294 /// An update_fee message to be sent or received from a peer
295 pub struct UpdateFee {
296 pub(crate) channel_id: [u8; 32],
297 pub(crate) feerate_per_kw: u32,
300 pub(crate) struct DataLossProtect {
301 pub(crate) your_last_per_commitment_secret: [u8; 32],
302 pub(crate) my_current_per_commitment_point: PublicKey,
305 /// A channel_reestablish message to be sent or received from a peer
306 pub struct ChannelReestablish {
307 pub(crate) channel_id: [u8; 32],
308 pub(crate) next_local_commitment_number: u64,
309 pub(crate) next_remote_commitment_number: u64,
310 pub(crate) data_loss_protect: Option<DataLossProtect>,
313 /// An announcement_signatures message to be sent or received from a peer
315 pub struct AnnouncementSignatures {
316 pub(crate) channel_id: [u8; 32],
317 pub(crate) short_channel_id: u64,
318 pub(crate) node_signature: Signature,
319 pub(crate) bitcoin_signature: Signature,
322 /// An address which can be used to connect to a remote peer
324 pub enum NetAddress {
325 /// An IPv4 address/port on which the peer is listenting.
327 /// The 4-byte IPv4 address
329 /// The port on which the node is listenting
332 /// An IPv6 address/port on which the peer is listenting.
334 /// The 16-byte IPv6 address
336 /// The port on which the node is listenting
339 /// An old-style Tor onion address/port on which the peer is listening.
341 /// The bytes (usually encoded in base32 with ".onion" appended)
343 /// The port on which the node is listenting
346 /// A new-style Tor onion address/port on which the peer is listening.
347 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
348 /// wrap as base32 and append ".onion".
350 /// The ed25519 long-term public key of the peer
351 ed25519_pubkey: [u8; 32],
352 /// The checksum of the pubkey and version, as included in the onion address
354 /// The version byte, as defined by the Tor Onion v3 spec.
356 /// The port on which the node is listenting
361 fn get_id(&self) -> u8 {
363 &NetAddress::IPv4 {..} => { 1 },
364 &NetAddress::IPv6 {..} => { 2 },
365 &NetAddress::OnionV2 {..} => { 3 },
366 &NetAddress::OnionV3 {..} => { 4 },
371 // Only exposed as broadcast of node_announcement should be filtered by node_id
372 /// The unsigned part of a node_announcement
373 pub struct UnsignedNodeAnnouncement {
374 pub(crate) features: GlobalFeatures,
375 pub(crate) timestamp: u32,
376 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
378 pub node_id: PublicKey,
379 pub(crate) rgb: [u8; 3],
380 pub(crate) alias: [u8; 32],
381 /// List of addresses on which this node is reachable. Note that you may only have up to one
382 /// address of each type, if you have more, they may be silently discarded or we may panic!
383 pub(crate) addresses: Vec<NetAddress>,
384 pub(crate) excess_address_data: Vec<u8>,
385 pub(crate) excess_data: Vec<u8>,
387 /// A node_announcement message to be sent or received from a peer
388 pub struct NodeAnnouncement {
389 pub(crate) signature: Signature,
390 pub(crate) contents: UnsignedNodeAnnouncement,
393 // Only exposed as broadcast of channel_announcement should be filtered by node_id
394 /// The unsigned part of a channel_announcement
395 #[derive(PartialEq, Clone)]
396 pub struct UnsignedChannelAnnouncement {
397 pub(crate) features: GlobalFeatures,
398 pub(crate) chain_hash: Sha256dHash,
399 pub(crate) short_channel_id: u64,
400 /// One of the two node_ids which are endpoints of this channel
401 pub node_id_1: PublicKey,
402 /// The other of the two node_ids which are endpoints of this channel
403 pub node_id_2: PublicKey,
404 pub(crate) bitcoin_key_1: PublicKey,
405 pub(crate) bitcoin_key_2: PublicKey,
406 pub(crate) excess_data: Vec<u8>,
408 /// A channel_announcement message to be sent or received from a peer
409 #[derive(PartialEq, Clone)]
410 pub struct ChannelAnnouncement {
411 pub(crate) node_signature_1: Signature,
412 pub(crate) node_signature_2: Signature,
413 pub(crate) bitcoin_signature_1: Signature,
414 pub(crate) bitcoin_signature_2: Signature,
415 pub(crate) contents: UnsignedChannelAnnouncement,
418 #[derive(PartialEq, Clone)]
419 pub(crate) struct UnsignedChannelUpdate {
420 pub(crate) chain_hash: Sha256dHash,
421 pub(crate) short_channel_id: u64,
422 pub(crate) timestamp: u32,
423 pub(crate) flags: u16,
424 pub(crate) cltv_expiry_delta: u16,
425 pub(crate) htlc_minimum_msat: u64,
426 pub(crate) fee_base_msat: u32,
427 pub(crate) fee_proportional_millionths: u32,
428 pub(crate) excess_data: Vec<u8>,
430 /// A channel_update message to be sent or received from a peer
431 #[derive(PartialEq, Clone)]
432 pub struct ChannelUpdate {
433 pub(crate) signature: Signature,
434 pub(crate) contents: UnsignedChannelUpdate,
437 /// Used to put an error message in a HandleError
438 pub enum ErrorAction {
439 /// The peer took some action which made us think they were useless. Disconnect them.
441 /// An error message which we should make an effort to send before we disconnect.
442 msg: Option<ErrorMessage>
444 /// The peer did something harmless that we weren't able to process, just log and ignore
446 /// The peer did something incorrect. Tell them.
448 /// The message to send.
453 /// An Err type for failure to process messages.
454 pub struct HandleError { //TODO: rename me
455 /// A human-readable message describing the error
456 pub err: &'static str,
457 /// The action which should be taken against the offending peer.
458 pub action: Option<ErrorAction>, //TODO: Make this required
461 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
462 /// transaction updates if they were pending.
463 pub struct CommitmentUpdate {
464 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
465 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
466 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
467 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
468 pub(crate) commitment_signed: CommitmentSigned,
471 /// The information we received from a peer along the route of a payment we originated. This is
472 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
473 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
474 pub enum HTLCFailChannelUpdate {
475 /// We received an error which included a full ChannelUpdate message.
476 ChannelUpdateMessage {
477 /// The unwrapped message we received
480 /// We received an error which indicated only that a channel has been closed
482 /// The short_channel_id which has now closed.
483 short_channel_id: u64,
487 /// A trait to describe an object which can receive channel messages. Messages MAY be called in
488 /// parallel when they originate from different their_node_ids, however they MUST NOT be called in
489 /// parallel when the two calls have the same their_node_id.
490 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
492 /// Handle an incoming open_channel message from the given peer.
493 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
494 /// Handle an incoming accept_channel message from the given peer.
495 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
496 /// Handle an incoming funding_created message from the given peer.
497 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
498 /// Handle an incoming funding_signed message from the given peer.
499 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
500 /// Handle an incoming funding_locked message from the given peer.
501 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
504 /// Handle an incoming shutdown message from the given peer.
505 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
506 /// Handle an incoming closing_signed message from the given peer.
507 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
510 /// Handle an incoming update_add_htlc message from the given peer.
511 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
512 /// Handle an incoming update_fulfill_htlc message from the given peer.
513 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
514 /// Handle an incoming update_fail_htlc message from the given peer.
515 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
516 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
517 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
518 /// Handle an incoming commitment_signed message from the given peer.
519 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
520 /// Handle an incoming revoke_and_ack message from the given peer.
521 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
523 /// Handle an incoming update_fee message from the given peer.
524 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
526 // Channel-to-announce:
527 /// Handle an incoming announcement_signatures message from the given peer.
528 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
530 // Connection loss/reestablish:
531 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
532 /// is believed to be possible in the future (eg they're sending us messages we don't
533 /// understand or indicate they require unknown feature bits), no_connection_possible is set
534 /// and any outstanding channels should be failed.
535 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
537 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
538 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
539 /// Handle an incoming channel_reestablish message from the given peer.
540 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
543 /// Handle an incoming error message from the given peer.
544 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
547 /// A trait to describe an object which can receive routing messages.
548 pub trait RoutingMessageHandler : Send + Sync {
549 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
550 /// false or returning an Err otherwise.
551 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
552 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
553 /// or returning an Err otherwise.
554 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
555 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
556 /// false or returning an Err otherwise.
557 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
558 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
559 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
562 pub(crate) struct OnionRealm0HopData {
563 pub(crate) short_channel_id: u64,
564 pub(crate) amt_to_forward: u64,
565 pub(crate) outgoing_cltv_value: u32,
566 // 12 bytes of 0-padding
569 mod fuzzy_internal_msgs {
570 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
571 // them from untrusted input):
573 use super::OnionRealm0HopData;
574 pub struct OnionHopData {
575 pub(crate) realm: u8,
576 pub(crate) data: OnionRealm0HopData,
577 pub(crate) hmac: [u8; 32],
579 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
581 pub struct DecodedOnionErrorPacket {
582 pub(crate) hmac: [u8; 32],
583 pub(crate) failuremsg: Vec<u8>,
584 pub(crate) pad: Vec<u8>,
587 #[cfg(feature = "fuzztarget")]
588 pub use self::fuzzy_internal_msgs::*;
589 #[cfg(not(feature = "fuzztarget"))]
590 pub(crate) use self::fuzzy_internal_msgs::*;
593 pub(crate) struct OnionPacket {
594 pub(crate) version: u8,
595 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
596 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
597 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
598 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
599 pub(crate) hop_data: [u8; 20*65],
600 pub(crate) hmac: [u8; 32],
604 pub(crate) struct OnionErrorPacket {
605 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
606 // (TODO) We limit it in decode to much lower...
607 pub(crate) data: Vec<u8>,
610 impl Error for DecodeError {
611 fn description(&self) -> &str {
613 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
614 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
615 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
616 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
617 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
618 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
619 DecodeError::Io(ref e) => e.description(),
623 impl fmt::Display for DecodeError {
624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
625 f.write_str(self.description())
629 impl fmt::Debug for HandleError {
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 f.write_str(self.err)
635 impl From<::std::io::Error> for DecodeError {
636 fn from(e: ::std::io::Error) -> Self {
637 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
638 DecodeError::ShortRead
645 impl_writeable_len_match!(AcceptChannel, {
646 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
649 temporary_channel_id,
651 max_htlc_value_in_flight_msat,
652 channel_reserve_satoshis,
658 revocation_basepoint,
660 delayed_payment_basepoint,
662 first_per_commitment_point,
663 shutdown_scriptpubkey
666 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
673 impl Writeable for ChannelReestablish {
674 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
675 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
676 self.channel_id.write(w)?;
677 self.next_local_commitment_number.write(w)?;
678 self.next_remote_commitment_number.write(w)?;
679 if let Some(ref data_loss_protect) = self.data_loss_protect {
680 data_loss_protect.your_last_per_commitment_secret.write(w)?;
681 data_loss_protect.my_current_per_commitment_point.write(w)?;
687 impl<R: Read> Readable<R> for ChannelReestablish{
688 fn read(r: &mut R) -> Result<Self, DecodeError> {
690 channel_id: Readable::read(r)?,
691 next_local_commitment_number: Readable::read(r)?,
692 next_remote_commitment_number: Readable::read(r)?,
694 match <[u8; 32] as Readable<R>>::read(r) {
695 Ok(your_last_per_commitment_secret) =>
696 Some(DataLossProtect {
697 your_last_per_commitment_secret,
698 my_current_per_commitment_point: Readable::read(r)?,
700 Err(DecodeError::ShortRead) => None,
701 Err(e) => return Err(e)
708 impl_writeable!(ClosingSigned, 32+8+64, {
714 impl_writeable_len_match!(CommitmentSigned, {
715 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
722 impl_writeable_len_match!(DecodedOnionErrorPacket, {
723 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
730 impl_writeable!(FundingCreated, 32+32+2+64, {
731 temporary_channel_id,
733 funding_output_index,
737 impl_writeable!(FundingSigned, 32+64, {
742 impl_writeable!(FundingLocked, 32+33, {
744 next_per_commitment_point
747 impl_writeable_len_match!(GlobalFeatures, {
748 { GlobalFeatures { ref flags }, flags.len() + 2 }
753 impl_writeable_len_match!(LocalFeatures, {
754 { LocalFeatures { ref flags }, flags.len() + 2 }
759 impl_writeable_len_match!(Init, {
760 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
766 impl_writeable_len_match!(OpenChannel, {
767 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
768 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
771 temporary_channel_id,
775 max_htlc_value_in_flight_msat,
776 channel_reserve_satoshis,
782 revocation_basepoint,
784 delayed_payment_basepoint,
786 first_per_commitment_point,
788 shutdown_scriptpubkey
791 impl_writeable!(RevokeAndACK, 32+32+33, {
793 per_commitment_secret,
794 next_per_commitment_point
797 impl_writeable_len_match!(Shutdown, {
798 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
804 impl_writeable_len_match!(UpdateFailHTLC, {
805 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
812 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
819 impl_writeable!(UpdateFee, 32+4, {
824 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
830 impl_writeable_len_match!(OnionErrorPacket, {
831 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
836 impl Writeable for OnionPacket {
837 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
838 w.size_hint(1 + 33 + 20*65 + 32);
839 self.version.write(w)?;
840 match self.public_key {
841 Ok(pubkey) => pubkey.write(w)?,
842 Err(_) => [0u8;33].write(w)?,
844 w.write_all(&self.hop_data)?;
850 impl<R: Read> Readable<R> for OnionPacket {
851 fn read(r: &mut R) -> Result<Self, DecodeError> {
853 version: Readable::read(r)?,
855 let mut buf = [0u8;33];
856 r.read_exact(&mut buf)?;
857 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
859 hop_data: Readable::read(r)?,
860 hmac: Readable::read(r)?,
865 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
874 impl Writeable for OnionRealm0HopData {
875 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
877 self.short_channel_id.write(w)?;
878 self.amt_to_forward.write(w)?;
879 self.outgoing_cltv_value.write(w)?;
880 w.write_all(&[0;12])?;
885 impl<R: Read> Readable<R> for OnionRealm0HopData {
886 fn read(r: &mut R) -> Result<Self, DecodeError> {
887 Ok(OnionRealm0HopData {
888 short_channel_id: Readable::read(r)?,
889 amt_to_forward: Readable::read(r)?,
890 outgoing_cltv_value: {
891 let v: u32 = Readable::read(r)?;
892 r.read_exact(&mut [0; 12])?;
899 impl Writeable for OnionHopData {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
902 self.realm.write(w)?;
909 impl<R: Read> Readable<R> for OnionHopData {
910 fn read(r: &mut R) -> Result<Self, DecodeError> {
913 let r: u8 = Readable::read(r)?;
915 return Err(DecodeError::UnknownVersion);
919 data: Readable::read(r)?,
920 hmac: Readable::read(r)?,
925 impl Writeable for Ping {
926 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
927 w.size_hint(self.byteslen as usize + 4);
928 self.ponglen.write(w)?;
929 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
934 impl<R: Read> Readable<R> for Ping {
935 fn read(r: &mut R) -> Result<Self, DecodeError> {
937 ponglen: Readable::read(r)?,
939 let byteslen = Readable::read(r)?;
940 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
947 impl Writeable for Pong {
948 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
949 w.size_hint(self.byteslen as usize + 2);
950 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
955 impl<R: Read> Readable<R> for Pong {
956 fn read(r: &mut R) -> Result<Self, DecodeError> {
959 let byteslen = Readable::read(r)?;
960 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
967 impl Writeable for UnsignedChannelAnnouncement {
968 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
969 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
970 self.features.write(w)?;
971 self.chain_hash.write(w)?;
972 self.short_channel_id.write(w)?;
973 self.node_id_1.write(w)?;
974 self.node_id_2.write(w)?;
975 self.bitcoin_key_1.write(w)?;
976 self.bitcoin_key_2.write(w)?;
977 w.write_all(&self.excess_data[..])?;
982 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
983 fn read(r: &mut R) -> Result<Self, DecodeError> {
986 let f: GlobalFeatures = Readable::read(r)?;
987 if f.requires_unknown_bits() {
988 return Err(DecodeError::UnknownRequiredFeature);
992 chain_hash: Readable::read(r)?,
993 short_channel_id: Readable::read(r)?,
994 node_id_1: Readable::read(r)?,
995 node_id_2: Readable::read(r)?,
996 bitcoin_key_1: Readable::read(r)?,
997 bitcoin_key_2: Readable::read(r)?,
999 let mut excess_data = vec![];
1000 r.read_to_end(&mut excess_data)?;
1007 impl_writeable_len_match!(ChannelAnnouncement, {
1008 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1009 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1013 bitcoin_signature_1,
1014 bitcoin_signature_2,
1018 impl Writeable for UnsignedChannelUpdate {
1019 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1020 w.size_hint(64 + self.excess_data.len());
1021 self.chain_hash.write(w)?;
1022 self.short_channel_id.write(w)?;
1023 self.timestamp.write(w)?;
1024 self.flags.write(w)?;
1025 self.cltv_expiry_delta.write(w)?;
1026 self.htlc_minimum_msat.write(w)?;
1027 self.fee_base_msat.write(w)?;
1028 self.fee_proportional_millionths.write(w)?;
1029 w.write_all(&self.excess_data[..])?;
1034 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1035 fn read(r: &mut R) -> Result<Self, DecodeError> {
1037 chain_hash: Readable::read(r)?,
1038 short_channel_id: Readable::read(r)?,
1039 timestamp: Readable::read(r)?,
1040 flags: Readable::read(r)?,
1041 cltv_expiry_delta: Readable::read(r)?,
1042 htlc_minimum_msat: Readable::read(r)?,
1043 fee_base_msat: Readable::read(r)?,
1044 fee_proportional_millionths: Readable::read(r)?,
1046 let mut excess_data = vec![];
1047 r.read_to_end(&mut excess_data)?;
1054 impl_writeable_len_match!(ChannelUpdate, {
1055 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1056 64 + excess_data.len() + 64 }
1062 impl Writeable for ErrorMessage {
1063 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1064 w.size_hint(32 + 2 + self.data.len());
1065 self.channel_id.write(w)?;
1066 (self.data.len() as u16).write(w)?;
1067 w.write_all(self.data.as_bytes())?;
1072 impl<R: Read> Readable<R> for ErrorMessage {
1073 fn read(r: &mut R) -> Result<Self, DecodeError> {
1075 channel_id: Readable::read(r)?,
1077 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1078 let mut data = vec![];
1079 let data_len = r.read_to_end(&mut data)?;
1080 sz = cmp::min(data_len, sz);
1081 match String::from_utf8(data[..sz as usize].to_vec()) {
1083 Err(_) => return Err(DecodeError::InvalidValue),
1090 impl Writeable for UnsignedNodeAnnouncement {
1091 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1092 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1093 self.features.write(w)?;
1094 self.timestamp.write(w)?;
1095 self.node_id.write(w)?;
1096 w.write_all(&self.rgb)?;
1097 self.alias.write(w)?;
1099 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1100 let mut addrs_to_encode = self.addresses.clone();
1101 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1102 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1103 for addr in addrs_to_encode.iter() {
1105 &NetAddress::IPv4{addr, port} => {
1107 addr_slice.extend_from_slice(&addr);
1108 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1110 &NetAddress::IPv6{addr, port} => {
1112 addr_slice.extend_from_slice(&addr);
1113 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1115 &NetAddress::OnionV2{addr, port} => {
1117 addr_slice.extend_from_slice(&addr);
1118 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1120 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1122 addr_slice.extend_from_slice(&ed25519_pubkey);
1123 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1124 addr_slice.push(version);
1125 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1129 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1130 w.write_all(&addr_slice[..])?;
1131 w.write_all(&self.excess_address_data[..])?;
1132 w.write_all(&self.excess_data[..])?;
1137 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1138 fn read(r: &mut R) -> Result<Self, DecodeError> {
1139 let features: GlobalFeatures = Readable::read(r)?;
1140 if features.requires_unknown_bits() {
1141 return Err(DecodeError::UnknownRequiredFeature);
1143 let timestamp: u32 = Readable::read(r)?;
1144 let node_id: PublicKey = Readable::read(r)?;
1145 let mut rgb = [0; 3];
1146 r.read_exact(&mut rgb)?;
1147 let alias: [u8; 32] = Readable::read(r)?;
1149 let addrlen: u16 = Readable::read(r)?;
1150 let mut addr_readpos = 0;
1151 let mut addresses = Vec::with_capacity(4);
1155 if addrlen <= addr_readpos { break; }
1156 f = Readable::read(r)?;
1159 if addresses.len() > 0 {
1160 return Err(DecodeError::ExtraAddressesPerType);
1162 if addrlen < addr_readpos + 1 + 6 {
1163 return Err(DecodeError::BadLengthDescriptor);
1165 addresses.push(NetAddress::IPv4 {
1167 let mut addr = [0; 4];
1168 r.read_exact(&mut addr)?;
1171 port: Readable::read(r)?,
1173 addr_readpos += 1 + 6
1176 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1177 return Err(DecodeError::ExtraAddressesPerType);
1179 if addrlen < addr_readpos + 1 + 18 {
1180 return Err(DecodeError::BadLengthDescriptor);
1182 addresses.push(NetAddress::IPv6 {
1184 let mut addr = [0; 16];
1185 r.read_exact(&mut addr)?;
1188 port: Readable::read(r)?,
1190 addr_readpos += 1 + 18
1193 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1194 return Err(DecodeError::ExtraAddressesPerType);
1196 if addrlen < addr_readpos + 1 + 12 {
1197 return Err(DecodeError::BadLengthDescriptor);
1199 addresses.push(NetAddress::OnionV2 {
1201 let mut addr = [0; 10];
1202 r.read_exact(&mut addr)?;
1205 port: Readable::read(r)?,
1207 addr_readpos += 1 + 12
1210 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1211 return Err(DecodeError::ExtraAddressesPerType);
1213 if addrlen < addr_readpos + 1 + 37 {
1214 return Err(DecodeError::BadLengthDescriptor);
1216 addresses.push(NetAddress::OnionV3 {
1217 ed25519_pubkey: Readable::read(r)?,
1218 checksum: Readable::read(r)?,
1219 version: Readable::read(r)?,
1220 port: Readable::read(r)?,
1222 addr_readpos += 1 + 37
1224 _ => { excess = 1; break; }
1228 let mut excess_data = vec![];
1229 let excess_address_data = if addr_readpos < addrlen {
1230 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1231 r.read_exact(&mut excess_address_data[excess..])?;
1233 excess_address_data[0] = f;
1238 excess_data.push(f);
1243 Ok(UnsignedNodeAnnouncement {
1245 timestamp: timestamp,
1249 addresses: addresses,
1250 excess_address_data: excess_address_data,
1252 r.read_to_end(&mut excess_data)?;
1259 impl_writeable_len_match!(NodeAnnouncement, {
1260 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1261 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1271 use util::ser::Writeable;
1272 use secp256k1::key::{PublicKey,SecretKey};
1273 use secp256k1::Secp256k1;
1276 fn encoding_channel_reestablish_no_secret() {
1277 let cr = msgs::ChannelReestablish {
1278 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],
1279 next_local_commitment_number: 3,
1280 next_remote_commitment_number: 4,
1281 data_loss_protect: None,
1284 let encoded_value = cr.encode();
1287 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]
1292 fn encoding_channel_reestablish_with_secret() {
1294 let secp_ctx = Secp256k1::new();
1295 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1298 let cr = msgs::ChannelReestablish {
1299 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],
1300 next_local_commitment_number: 3,
1301 next_remote_commitment_number: 4,
1302 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1305 let encoded_value = cr.encode();
1308 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]