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 /// Unknown realm byte in an OnionHopData packet
35 /// Unknown feature mandating we fail to parse message
36 UnknownRequiredFeature,
37 /// Failed to decode a public key (ie it's invalid)
39 /// Failed to decode a signature (ie it's invalid)
41 /// Value expected to be text wasn't decodable as text
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
52 /// 1 or 0 is not found for boolean value
56 /// Tracks localfeatures which are only in init messages
57 #[derive(Clone, PartialEq)]
58 pub struct LocalFeatures {
63 pub(crate) fn new() -> LocalFeatures {
69 pub(crate) fn supports_data_loss_protect(&self) -> bool {
70 self.flags.len() > 0 && (self.flags[0] & 3) != 0
72 pub(crate) fn requires_data_loss_protect(&self) -> bool {
73 self.flags.len() > 0 && (self.flags[0] & 1) != 0
76 pub(crate) fn initial_routing_sync(&self) -> bool {
77 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
79 pub(crate) fn set_initial_routing_sync(&mut self) {
80 if self.flags.len() == 0 {
81 self.flags.resize(1, 1 << 3);
83 self.flags[0] |= 1 << 3;
87 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
88 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
90 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
91 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
94 pub(crate) fn requires_unknown_bits(&self) -> bool {
95 for (idx, &byte) in self.flags.iter().enumerate() {
96 if idx != 0 && (byte & 0x55) != 0 {
98 } else if idx == 0 && (byte & 0x14) != 0 {
105 pub(crate) fn supports_unknown_bits(&self) -> bool {
106 for (idx, &byte) in self.flags.iter().enumerate() {
107 if idx != 0 && byte != 0 {
109 } else if idx == 0 && (byte & 0xc4) != 0 {
117 /// Tracks globalfeatures which are in init messages and routing announcements
118 #[derive(Clone, PartialEq)]
119 pub struct GlobalFeatures {
123 impl GlobalFeatures {
124 pub(crate) fn new() -> GlobalFeatures {
130 pub(crate) fn requires_unknown_bits(&self) -> bool {
131 for &byte in self.flags.iter() {
132 if (byte & 0x55) != 0 {
139 pub(crate) fn supports_unknown_bits(&self) -> bool {
140 for &byte in self.flags.iter() {
149 /// An init message to be sent or received from a peer
151 pub(crate) global_features: GlobalFeatures,
152 pub(crate) local_features: LocalFeatures,
155 /// 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
173 pub struct OpenChannel {
174 pub(crate) chain_hash: Sha256dHash,
175 pub(crate) temporary_channel_id: [u8; 32],
176 pub(crate) funding_satoshis: u64,
177 pub(crate) push_msat: u64,
178 pub(crate) dust_limit_satoshis: u64,
179 pub(crate) max_htlc_value_in_flight_msat: u64,
180 pub(crate) channel_reserve_satoshis: u64,
181 pub(crate) htlc_minimum_msat: u64,
182 pub(crate) feerate_per_kw: u32,
183 pub(crate) to_self_delay: u16,
184 pub(crate) max_accepted_htlcs: u16,
185 pub(crate) funding_pubkey: PublicKey,
186 pub(crate) revocation_basepoint: PublicKey,
187 pub(crate) payment_basepoint: PublicKey,
188 pub(crate) delayed_payment_basepoint: PublicKey,
189 pub(crate) htlc_basepoint: PublicKey,
190 pub(crate) first_per_commitment_point: PublicKey,
191 pub(crate) channel_flags: u8,
192 pub(crate) shutdown_scriptpubkey: Option<Script>,
195 /// An accept_channel message to be sent or received from a peer
196 pub struct AcceptChannel {
197 pub(crate) temporary_channel_id: [u8; 32],
198 pub(crate) dust_limit_satoshis: u64,
199 pub(crate) max_htlc_value_in_flight_msat: u64,
200 pub(crate) channel_reserve_satoshis: u64,
201 pub(crate) htlc_minimum_msat: u64,
202 pub(crate) minimum_depth: u32,
203 pub(crate) to_self_delay: u16,
204 pub(crate) max_accepted_htlcs: u16,
205 pub(crate) funding_pubkey: PublicKey,
206 pub(crate) revocation_basepoint: PublicKey,
207 pub(crate) payment_basepoint: PublicKey,
208 pub(crate) delayed_payment_basepoint: PublicKey,
209 pub(crate) htlc_basepoint: PublicKey,
210 pub(crate) first_per_commitment_point: PublicKey,
211 pub(crate) shutdown_scriptpubkey: Option<Script>,
214 /// A funding_created message to be sent or received from a peer
215 pub struct FundingCreated {
216 pub(crate) temporary_channel_id: [u8; 32],
217 pub(crate) funding_txid: Sha256dHash,
218 pub(crate) funding_output_index: u16,
219 pub(crate) signature: Signature,
222 /// A funding_signed message to be sent or received from a peer
223 pub struct FundingSigned {
224 pub(crate) channel_id: [u8; 32],
225 pub(crate) signature: Signature,
228 /// A funding_locked message to be sent or received from a peer
229 pub struct FundingLocked {
230 pub(crate) channel_id: [u8; 32],
231 pub(crate) next_per_commitment_point: PublicKey,
234 /// A shutdown message to be sent or received from a peer
235 pub struct Shutdown {
236 pub(crate) channel_id: [u8; 32],
237 pub(crate) scriptpubkey: Script,
240 /// A closing_signed message to be sent or received from a peer
241 pub struct ClosingSigned {
242 pub(crate) channel_id: [u8; 32],
243 pub(crate) fee_satoshis: u64,
244 pub(crate) signature: Signature,
247 /// An update_add_htlc message to be sent or received from a peer
249 pub struct UpdateAddHTLC {
250 pub(crate) channel_id: [u8; 32],
251 pub(crate) htlc_id: u64,
252 pub(crate) amount_msat: u64,
253 pub(crate) payment_hash: [u8; 32],
254 pub(crate) cltv_expiry: u32,
255 pub(crate) onion_routing_packet: OnionPacket,
258 /// An update_fulfill_htlc message to be sent or received from a peer
260 pub struct UpdateFulfillHTLC {
261 pub(crate) channel_id: [u8; 32],
262 pub(crate) htlc_id: u64,
263 pub(crate) payment_preimage: [u8; 32],
266 /// An update_fail_htlc message to be sent or received from a peer
268 pub struct UpdateFailHTLC {
269 pub(crate) channel_id: [u8; 32],
270 pub(crate) htlc_id: u64,
271 pub(crate) reason: OnionErrorPacket,
274 /// An update_fail_malformed_htlc message to be sent or received from a peer
276 pub struct UpdateFailMalformedHTLC {
277 pub(crate) channel_id: [u8; 32],
278 pub(crate) htlc_id: u64,
279 pub(crate) sha256_of_onion: [u8; 32],
280 pub(crate) failure_code: u16,
283 /// A commitment_signed message to be sent or received from a peer
285 pub struct CommitmentSigned {
286 pub(crate) channel_id: [u8; 32],
287 pub(crate) signature: Signature,
288 pub(crate) htlc_signatures: Vec<Signature>,
291 /// A revoke_and_ack message to be sent or received from a peer
292 pub struct RevokeAndACK {
293 pub(crate) channel_id: [u8; 32],
294 pub(crate) per_commitment_secret: [u8; 32],
295 pub(crate) next_per_commitment_point: PublicKey,
298 /// An update_fee message to be sent or received from a peer
299 pub struct UpdateFee {
300 pub(crate) channel_id: [u8; 32],
301 pub(crate) feerate_per_kw: u32,
304 pub(crate) struct DataLossProtect {
305 pub(crate) your_last_per_commitment_secret: [u8; 32],
306 pub(crate) my_current_per_commitment_point: PublicKey,
309 /// A channel_reestablish message to be sent or received from a peer
310 pub struct ChannelReestablish {
311 pub(crate) channel_id: [u8; 32],
312 pub(crate) next_local_commitment_number: u64,
313 pub(crate) next_remote_commitment_number: u64,
314 pub(crate) data_loss_protect: Option<DataLossProtect>,
317 /// An announcement_signatures message to be sent or received from a peer
319 pub struct AnnouncementSignatures {
320 pub(crate) channel_id: [u8; 32],
321 pub(crate) short_channel_id: u64,
322 pub(crate) node_signature: Signature,
323 pub(crate) bitcoin_signature: Signature,
326 /// An address which can be used to connect to a remote peer
328 pub enum NetAddress {
329 /// An IPv4 address/port on which the peer is listenting.
331 /// The 4-byte IPv4 address
333 /// The port on which the node is listenting
336 /// An IPv6 address/port on which the peer is listenting.
338 /// The 16-byte IPv6 address
340 /// The port on which the node is listenting
343 /// An old-style Tor onion address/port on which the peer is listening.
345 /// The bytes (usually encoded in base32 with ".onion" appended)
347 /// The port on which the node is listenting
350 /// A new-style Tor onion address/port on which the peer is listening.
351 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
352 /// wrap as base32 and append ".onion".
354 /// The ed25519 long-term public key of the peer
355 ed25519_pubkey: [u8; 32],
356 /// The checksum of the pubkey and version, as included in the onion address
358 /// The version byte, as defined by the Tor Onion v3 spec.
360 /// The port on which the node is listenting
365 fn get_id(&self) -> u8 {
367 &NetAddress::IPv4 {..} => { 1 },
368 &NetAddress::IPv6 {..} => { 2 },
369 &NetAddress::OnionV2 {..} => { 3 },
370 &NetAddress::OnionV3 {..} => { 4 },
375 // Only exposed as broadcast of node_announcement should be filtered by node_id
376 /// The unsigned part of a node_announcement
377 pub struct UnsignedNodeAnnouncement {
378 pub(crate) features: GlobalFeatures,
379 pub(crate) timestamp: u32,
380 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
382 pub node_id: PublicKey,
383 pub(crate) rgb: [u8; 3],
384 pub(crate) alias: [u8; 32],
385 /// List of addresses on which this node is reachable. Note that you may only have up to one
386 /// address of each type, if you have more, they may be silently discarded or we may panic!
387 pub(crate) addresses: Vec<NetAddress>,
388 pub(crate) excess_address_data: Vec<u8>,
389 pub(crate) excess_data: Vec<u8>,
391 /// A node_announcement message to be sent or received from a peer
392 pub struct NodeAnnouncement {
393 pub(crate) signature: Signature,
394 pub(crate) contents: UnsignedNodeAnnouncement,
397 // Only exposed as broadcast of channel_announcement should be filtered by node_id
398 /// The unsigned part of a channel_announcement
399 #[derive(PartialEq, Clone)]
400 pub struct UnsignedChannelAnnouncement {
401 pub(crate) features: GlobalFeatures,
402 pub(crate) chain_hash: Sha256dHash,
403 pub(crate) short_channel_id: u64,
404 /// One of the two node_ids which are endpoints of this channel
405 pub node_id_1: PublicKey,
406 /// The other of the two node_ids which are endpoints of this channel
407 pub node_id_2: PublicKey,
408 pub(crate) bitcoin_key_1: PublicKey,
409 pub(crate) bitcoin_key_2: PublicKey,
410 pub(crate) excess_data: Vec<u8>,
412 /// A channel_announcement message to be sent or received from a peer
413 #[derive(PartialEq, Clone)]
414 pub struct ChannelAnnouncement {
415 pub(crate) node_signature_1: Signature,
416 pub(crate) node_signature_2: Signature,
417 pub(crate) bitcoin_signature_1: Signature,
418 pub(crate) bitcoin_signature_2: Signature,
419 pub(crate) contents: UnsignedChannelAnnouncement,
422 #[derive(PartialEq, Clone)]
423 pub(crate) struct UnsignedChannelUpdate {
424 pub(crate) chain_hash: Sha256dHash,
425 pub(crate) short_channel_id: u64,
426 pub(crate) timestamp: u32,
427 pub(crate) flags: u16,
428 pub(crate) cltv_expiry_delta: u16,
429 pub(crate) htlc_minimum_msat: u64,
430 pub(crate) fee_base_msat: u32,
431 pub(crate) fee_proportional_millionths: u32,
432 pub(crate) excess_data: Vec<u8>,
434 /// A channel_update message to be sent or received from a peer
435 #[derive(PartialEq, Clone)]
436 pub struct ChannelUpdate {
437 pub(crate) signature: Signature,
438 pub(crate) contents: UnsignedChannelUpdate,
441 /// Used to put an error message in a HandleError
442 pub enum ErrorAction {
443 /// The peer took some action which made us think they were useless. Disconnect them.
445 /// An error message which we should make an effort to send before we disconnect.
446 msg: Option<ErrorMessage>
448 /// The peer did something harmless that we weren't able to process, just log and ignore
450 /// The peer did something incorrect. Tell them.
452 /// The message to send.
457 /// An Err type for failure to process messages.
458 pub struct HandleError { //TODO: rename me
459 /// A human-readable message describing the error
460 pub err: &'static str,
461 /// The action which should be taken against the offending peer.
462 pub action: Option<ErrorAction>, //TODO: Make this required
465 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
466 /// transaction updates if they were pending.
467 pub struct CommitmentUpdate {
468 pub(crate) update_add_htlcs: Vec<UpdateAddHTLC>,
469 pub(crate) update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
470 pub(crate) update_fail_htlcs: Vec<UpdateFailHTLC>,
471 pub(crate) update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
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. Messages MAY be called in
492 /// parallel when they originate from different their_node_ids, however they MUST NOT be called in
493 /// parallel when the two calls have the same their_node_id.
494 pub trait ChannelMessageHandler : events::EventsProvider + Send + Sync {
496 /// Handle an incoming open_channel message from the given peer.
497 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<AcceptChannel, HandleError>;
498 /// Handle an incoming accept_channel message from the given peer.
499 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
500 /// Handle an incoming funding_created message from the given peer.
501 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<FundingSigned, HandleError>;
502 /// Handle an incoming funding_signed message from the given peer.
503 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
504 /// Handle an incoming funding_locked message from the given peer.
505 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<Option<AnnouncementSignatures>, HandleError>;
508 /// Handle an incoming shutdown message from the given peer.
509 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(Option<Shutdown>, Option<ClosingSigned>), HandleError>;
510 /// Handle an incoming closing_signed message from the given peer.
511 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<Option<ClosingSigned>, HandleError>;
514 /// Handle an incoming update_add_htlc message from the given peer.
515 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
516 /// Handle an incoming update_fulfill_htlc message from the given peer.
517 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
518 /// Handle an incoming update_fail_htlc message from the given peer.
519 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<Option<HTLCFailChannelUpdate>, HandleError>;
520 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
521 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
522 /// Handle an incoming commitment_signed message from the given peer.
523 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(RevokeAndACK, Option<CommitmentSigned>), HandleError>;
524 /// Handle an incoming revoke_and_ack message from the given peer.
525 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<Option<CommitmentUpdate>, HandleError>;
527 /// Handle an incoming update_fee message from the given peer.
528 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
530 // Channel-to-announce:
531 /// Handle an incoming announcement_signatures message from the given peer.
532 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
534 // Connection loss/reestablish:
535 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
536 /// is believed to be possible in the future (eg they're sending us messages we don't
537 /// understand or indicate they require unknown feature bits), no_connection_possible is set
538 /// and any outstanding channels should be failed.
539 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
541 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
542 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<ChannelReestablish>;
543 /// Handle an incoming channel_reestablish message from the given peer.
544 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(Option<FundingLocked>, Option<RevokeAndACK>, Option<CommitmentUpdate>), HandleError>;
547 /// Handle an incoming error message from the given peer.
548 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
551 /// A trait to describe an object which can receive routing messages.
552 pub trait RoutingMessageHandler : Send + Sync {
553 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
554 /// false or returning an Err otherwise.
555 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
556 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
557 /// or returning an Err otherwise.
558 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
559 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
560 /// false or returning an Err otherwise.
561 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
562 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
563 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
566 pub(crate) struct OnionRealm0HopData {
567 pub(crate) short_channel_id: u64,
568 pub(crate) amt_to_forward: u64,
569 pub(crate) outgoing_cltv_value: u32,
570 // 12 bytes of 0-padding
573 mod fuzzy_internal_msgs {
574 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
575 // them from untrusted input):
577 use super::OnionRealm0HopData;
578 pub struct OnionHopData {
579 pub(crate) realm: u8,
580 pub(crate) data: OnionRealm0HopData,
581 pub(crate) hmac: [u8; 32],
583 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
585 pub struct DecodedOnionErrorPacket {
586 pub(crate) hmac: [u8; 32],
587 pub(crate) failuremsg: Vec<u8>,
588 pub(crate) pad: Vec<u8>,
591 #[cfg(feature = "fuzztarget")]
592 pub use self::fuzzy_internal_msgs::*;
593 #[cfg(not(feature = "fuzztarget"))]
594 pub(crate) use self::fuzzy_internal_msgs::*;
597 pub(crate) struct OnionPacket {
598 pub(crate) version: u8,
599 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
600 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
601 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
602 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
603 pub(crate) hop_data: [u8; 20*65],
604 pub(crate) hmac: [u8; 32],
608 pub(crate) struct OnionErrorPacket {
609 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
610 // (TODO) We limit it in decode to much lower...
611 pub(crate) data: Vec<u8>,
614 impl Error for DecodeError {
615 fn description(&self) -> &str {
617 DecodeError::UnknownRealmByte => "Unknown realm byte in Onion packet",
618 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
619 DecodeError::BadPublicKey => "Invalid public key in packet",
620 DecodeError::BadSignature => "Invalid signature in packet",
621 DecodeError::BadText => "Invalid text in packet",
622 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
623 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
624 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
625 DecodeError::Io(ref e) => e.description(),
626 DecodeError::InvalidValue => "0 or 1 is not found for boolean",
630 impl fmt::Display for DecodeError {
631 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
632 f.write_str(self.description())
636 impl fmt::Debug for HandleError {
637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
638 f.write_str(self.err)
642 impl From<::std::io::Error> for DecodeError {
643 fn from(e: ::std::io::Error) -> Self {
644 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
645 DecodeError::ShortRead
652 impl_writeable_len_match!(AcceptChannel, {
653 {AcceptChannel{ shutdown_scriptpubkey: Some(ref script), ..}, 270 + 2 + script.len()},
656 temporary_channel_id,
658 max_htlc_value_in_flight_msat,
659 channel_reserve_satoshis,
665 revocation_basepoint,
667 delayed_payment_basepoint,
669 first_per_commitment_point,
670 shutdown_scriptpubkey
673 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
680 impl Writeable for ChannelReestablish {
681 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
682 w.size_hint(if self.data_loss_protect.is_some() { 32+2*8+33+32 } else { 32+2*8 });
683 self.channel_id.write(w)?;
684 self.next_local_commitment_number.write(w)?;
685 self.next_remote_commitment_number.write(w)?;
686 if let Some(ref data_loss_protect) = self.data_loss_protect {
687 data_loss_protect.your_last_per_commitment_secret.write(w)?;
688 data_loss_protect.my_current_per_commitment_point.write(w)?;
694 impl<R: Read> Readable<R> for ChannelReestablish{
695 fn read(r: &mut R) -> Result<Self, DecodeError> {
697 channel_id: Readable::read(r)?,
698 next_local_commitment_number: Readable::read(r)?,
699 next_remote_commitment_number: Readable::read(r)?,
701 match <[u8; 32] as Readable<R>>::read(r) {
702 Ok(your_last_per_commitment_secret) =>
703 Some(DataLossProtect {
704 your_last_per_commitment_secret,
705 my_current_per_commitment_point: Readable::read(r)?,
707 Err(DecodeError::ShortRead) => None,
708 Err(e) => return Err(e)
715 impl_writeable!(ClosingSigned, 32+8+64, {
721 impl_writeable_len_match!(CommitmentSigned, {
722 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
729 impl_writeable_len_match!(DecodedOnionErrorPacket, {
730 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
737 impl_writeable!(FundingCreated, 32+32+2+64, {
738 temporary_channel_id,
740 funding_output_index,
744 impl_writeable!(FundingSigned, 32+64, {
749 impl_writeable!(FundingLocked, 32+33, {
751 next_per_commitment_point
754 impl_writeable_len_match!(GlobalFeatures, {
755 { GlobalFeatures { ref flags }, flags.len() + 2 }
760 impl_writeable_len_match!(LocalFeatures, {
761 { LocalFeatures { ref flags }, flags.len() + 2 }
766 impl_writeable_len_match!(Init, {
767 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
773 impl_writeable_len_match!(OpenChannel, {
774 { OpenChannel { shutdown_scriptpubkey: Some(ref script), .. }, 319 + 2 + script.len() },
775 { OpenChannel { shutdown_scriptpubkey: None, .. }, 319 }
778 temporary_channel_id,
782 max_htlc_value_in_flight_msat,
783 channel_reserve_satoshis,
789 revocation_basepoint,
791 delayed_payment_basepoint,
793 first_per_commitment_point,
795 shutdown_scriptpubkey
798 impl_writeable!(RevokeAndACK, 32+32+33, {
800 per_commitment_secret,
801 next_per_commitment_point
804 impl_writeable_len_match!(Shutdown, {
805 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
811 impl_writeable_len_match!(UpdateFailHTLC, {
812 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
819 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
826 impl_writeable!(UpdateFee, 32+4, {
831 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
837 impl_writeable_len_match!(OnionErrorPacket, {
838 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
843 impl Writeable for OnionPacket {
844 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
845 w.size_hint(1 + 33 + 20*65 + 32);
846 self.version.write(w)?;
847 match self.public_key {
848 Ok(pubkey) => pubkey.write(w)?,
849 Err(_) => [0u8;33].write(w)?,
851 w.write_all(&self.hop_data)?;
857 impl<R: Read> Readable<R> for OnionPacket {
858 fn read(r: &mut R) -> Result<Self, DecodeError> {
860 version: Readable::read(r)?,
862 let mut buf = [0u8;33];
863 r.read_exact(&mut buf)?;
864 PublicKey::from_slice(&Secp256k1::without_caps(), &buf)
866 hop_data: Readable::read(r)?,
867 hmac: Readable::read(r)?,
872 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
881 impl Writeable for OnionRealm0HopData {
882 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
884 self.short_channel_id.write(w)?;
885 self.amt_to_forward.write(w)?;
886 self.outgoing_cltv_value.write(w)?;
887 w.write_all(&[0;12])?;
892 impl<R: Read> Readable<R> for OnionRealm0HopData {
893 fn read(r: &mut R) -> Result<Self, DecodeError> {
894 Ok(OnionRealm0HopData {
895 short_channel_id: Readable::read(r)?,
896 amt_to_forward: Readable::read(r)?,
897 outgoing_cltv_value: {
898 let v: u32 = Readable::read(r)?;
899 r.read_exact(&mut [0; 12])?;
906 impl Writeable for OnionHopData {
907 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
909 self.realm.write(w)?;
916 impl<R: Read> Readable<R> for OnionHopData {
917 fn read(r: &mut R) -> Result<Self, DecodeError> {
920 let r: u8 = Readable::read(r)?;
922 return Err(DecodeError::UnknownRealmByte);
926 data: Readable::read(r)?,
927 hmac: Readable::read(r)?,
932 impl Writeable for Ping {
933 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
934 w.size_hint(self.byteslen as usize + 4);
935 self.ponglen.write(w)?;
936 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
941 impl<R: Read> Readable<R> for Ping {
942 fn read(r: &mut R) -> Result<Self, DecodeError> {
944 ponglen: Readable::read(r)?,
946 let byteslen = Readable::read(r)?;
947 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
954 impl Writeable for Pong {
955 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
956 w.size_hint(self.byteslen as usize + 2);
957 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
962 impl<R: Read> Readable<R> for Pong {
963 fn read(r: &mut R) -> Result<Self, DecodeError> {
966 let byteslen = Readable::read(r)?;
967 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
974 impl Writeable for UnsignedChannelAnnouncement {
975 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
976 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
977 self.features.write(w)?;
978 self.chain_hash.write(w)?;
979 self.short_channel_id.write(w)?;
980 self.node_id_1.write(w)?;
981 self.node_id_2.write(w)?;
982 self.bitcoin_key_1.write(w)?;
983 self.bitcoin_key_2.write(w)?;
984 w.write_all(&self.excess_data[..])?;
989 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
990 fn read(r: &mut R) -> Result<Self, DecodeError> {
993 let f: GlobalFeatures = Readable::read(r)?;
994 if f.requires_unknown_bits() {
995 return Err(DecodeError::UnknownRequiredFeature);
999 chain_hash: Readable::read(r)?,
1000 short_channel_id: Readable::read(r)?,
1001 node_id_1: Readable::read(r)?,
1002 node_id_2: Readable::read(r)?,
1003 bitcoin_key_1: Readable::read(r)?,
1004 bitcoin_key_2: Readable::read(r)?,
1006 let mut excess_data = vec![];
1007 r.read_to_end(&mut excess_data)?;
1014 impl_writeable_len_match!(ChannelAnnouncement, {
1015 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1016 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1020 bitcoin_signature_1,
1021 bitcoin_signature_2,
1025 impl Writeable for UnsignedChannelUpdate {
1026 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1027 w.size_hint(64 + self.excess_data.len());
1028 self.chain_hash.write(w)?;
1029 self.short_channel_id.write(w)?;
1030 self.timestamp.write(w)?;
1031 self.flags.write(w)?;
1032 self.cltv_expiry_delta.write(w)?;
1033 self.htlc_minimum_msat.write(w)?;
1034 self.fee_base_msat.write(w)?;
1035 self.fee_proportional_millionths.write(w)?;
1036 w.write_all(&self.excess_data[..])?;
1041 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1042 fn read(r: &mut R) -> Result<Self, DecodeError> {
1044 chain_hash: Readable::read(r)?,
1045 short_channel_id: Readable::read(r)?,
1046 timestamp: Readable::read(r)?,
1047 flags: Readable::read(r)?,
1048 cltv_expiry_delta: Readable::read(r)?,
1049 htlc_minimum_msat: Readable::read(r)?,
1050 fee_base_msat: Readable::read(r)?,
1051 fee_proportional_millionths: Readable::read(r)?,
1053 let mut excess_data = vec![];
1054 r.read_to_end(&mut excess_data)?;
1061 impl_writeable_len_match!(ChannelUpdate, {
1062 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1063 64 + excess_data.len() + 64 }
1069 impl Writeable for ErrorMessage {
1070 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1071 w.size_hint(32 + 2 + self.data.len());
1072 self.channel_id.write(w)?;
1073 (self.data.len() as u16).write(w)?;
1074 w.write_all(self.data.as_bytes())?;
1079 impl<R: Read> Readable<R> for ErrorMessage {
1080 fn read(r: &mut R) -> Result<Self, DecodeError> {
1082 channel_id: Readable::read(r)?,
1084 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1085 let mut data = vec![];
1086 let data_len = r.read_to_end(&mut data)?;
1087 sz = cmp::min(data_len, sz);
1088 match String::from_utf8(data[..sz as usize].to_vec()) {
1090 Err(_) => return Err(DecodeError::BadText),
1097 impl Writeable for UnsignedNodeAnnouncement {
1098 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1099 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1100 self.features.write(w)?;
1101 self.timestamp.write(w)?;
1102 self.node_id.write(w)?;
1103 w.write_all(&self.rgb)?;
1104 self.alias.write(w)?;
1106 let mut addr_slice = Vec::with_capacity(self.addresses.len() * 18);
1107 let mut addrs_to_encode = self.addresses.clone();
1108 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1109 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1110 for addr in addrs_to_encode.iter() {
1112 &NetAddress::IPv4{addr, port} => {
1114 addr_slice.extend_from_slice(&addr);
1115 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1117 &NetAddress::IPv6{addr, port} => {
1119 addr_slice.extend_from_slice(&addr);
1120 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1122 &NetAddress::OnionV2{addr, port} => {
1124 addr_slice.extend_from_slice(&addr);
1125 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1127 &NetAddress::OnionV3{ed25519_pubkey, checksum, version, port} => {
1129 addr_slice.extend_from_slice(&ed25519_pubkey);
1130 addr_slice.extend_from_slice(&byte_utils::be16_to_array(checksum));
1131 addr_slice.push(version);
1132 addr_slice.extend_from_slice(&byte_utils::be16_to_array(port));
1136 ((addr_slice.len() + self.excess_address_data.len()) as u16).write(w)?;
1137 w.write_all(&addr_slice[..])?;
1138 w.write_all(&self.excess_address_data[..])?;
1139 w.write_all(&self.excess_data[..])?;
1144 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1145 fn read(r: &mut R) -> Result<Self, DecodeError> {
1146 let features: GlobalFeatures = Readable::read(r)?;
1147 if features.requires_unknown_bits() {
1148 return Err(DecodeError::UnknownRequiredFeature);
1150 let timestamp: u32 = Readable::read(r)?;
1151 let node_id: PublicKey = Readable::read(r)?;
1152 let mut rgb = [0; 3];
1153 r.read_exact(&mut rgb)?;
1154 let alias: [u8; 32] = Readable::read(r)?;
1156 let addrlen: u16 = Readable::read(r)?;
1157 let mut addr_readpos = 0;
1158 let mut addresses = Vec::with_capacity(4);
1162 if addrlen <= addr_readpos { break; }
1163 f = Readable::read(r)?;
1166 if addresses.len() > 0 {
1167 return Err(DecodeError::ExtraAddressesPerType);
1169 if addrlen < addr_readpos + 1 + 6 {
1170 return Err(DecodeError::BadLengthDescriptor);
1172 addresses.push(NetAddress::IPv4 {
1174 let mut addr = [0; 4];
1175 r.read_exact(&mut addr)?;
1178 port: Readable::read(r)?,
1180 addr_readpos += 1 + 6
1183 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1184 return Err(DecodeError::ExtraAddressesPerType);
1186 if addrlen < addr_readpos + 1 + 18 {
1187 return Err(DecodeError::BadLengthDescriptor);
1189 addresses.push(NetAddress::IPv6 {
1191 let mut addr = [0; 16];
1192 r.read_exact(&mut addr)?;
1195 port: Readable::read(r)?,
1197 addr_readpos += 1 + 18
1200 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1201 return Err(DecodeError::ExtraAddressesPerType);
1203 if addrlen < addr_readpos + 1 + 12 {
1204 return Err(DecodeError::BadLengthDescriptor);
1206 addresses.push(NetAddress::OnionV2 {
1208 let mut addr = [0; 10];
1209 r.read_exact(&mut addr)?;
1212 port: Readable::read(r)?,
1214 addr_readpos += 1 + 12
1217 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1218 return Err(DecodeError::ExtraAddressesPerType);
1220 if addrlen < addr_readpos + 1 + 37 {
1221 return Err(DecodeError::BadLengthDescriptor);
1223 addresses.push(NetAddress::OnionV3 {
1224 ed25519_pubkey: Readable::read(r)?,
1225 checksum: Readable::read(r)?,
1226 version: Readable::read(r)?,
1227 port: Readable::read(r)?,
1229 addr_readpos += 1 + 37
1231 _ => { excess = 1; break; }
1235 let mut excess_data = vec![];
1236 let excess_address_data = if addr_readpos < addrlen {
1237 let mut excess_address_data = vec![0; (addrlen - addr_readpos) as usize];
1238 r.read_exact(&mut excess_address_data[excess..])?;
1240 excess_address_data[0] = f;
1245 excess_data.push(f);
1250 Ok(UnsignedNodeAnnouncement {
1252 timestamp: timestamp,
1256 addresses: addresses,
1257 excess_address_data: excess_address_data,
1259 r.read_to_end(&mut excess_data)?;
1266 impl_writeable_len_match!(NodeAnnouncement, {
1267 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1268 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1278 use util::ser::Writeable;
1279 use secp256k1::key::{PublicKey,SecretKey};
1280 use secp256k1::Secp256k1;
1283 fn encoding_channel_reestablish_no_secret() {
1284 let cr = msgs::ChannelReestablish {
1285 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],
1286 next_local_commitment_number: 3,
1287 next_remote_commitment_number: 4,
1288 data_loss_protect: None,
1291 let encoded_value = cr.encode();
1294 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]
1299 fn encoding_channel_reestablish_with_secret() {
1301 let secp_ctx = Secp256k1::new();
1302 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1305 let cr = msgs::ChannelReestablish {
1306 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],
1307 next_local_commitment_number: 3,
1308 next_remote_commitment_number: 4,
1309 data_loss_protect: Some(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1312 let encoded_value = cr.encode();
1315 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]