1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
3 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
4 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
5 //! server entirely) which handles only channel-related messages you may wish to implement
6 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
9 //! Note that if you go with such an architecture (instead of passing raw socket events to a
10 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
11 //! source node_id of the message, however this does allow you to significantly reduce bandwidth
12 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
13 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
14 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
15 //! raw socket events into your non-internet-facing system and then send routing events back to
16 //! track the network on the less-secure system.
18 use secp256k1::key::PublicKey;
19 use secp256k1::Signature;
21 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
22 use bitcoin::blockdata::script::Script;
24 use std::error::Error;
27 use std::result::Result;
28 use std::marker::PhantomData;
31 use util::ser::{Readable, Writeable, Writer};
33 use ln::channelmanager::{PaymentPreimage, PaymentHash};
35 /// An error in decoding a message or struct.
37 pub enum DecodeError {
38 /// A version byte specified something we don't know how to handle.
39 /// Includes unknown realm byte in an OnionHopData packet
41 /// Unknown feature mandating we fail to parse message
42 UnknownRequiredFeature,
43 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
44 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
48 /// node_announcement included more than one address of a given type!
49 ExtraAddressesPerType,
50 /// A length descriptor in the packet didn't describe the later data correctly
52 /// Error from std::io
56 /// The context in which a Feature object appears determines which bits of features the node
57 /// supports will be set. We use this when creating our own Feature objects to select which bits to
58 /// set and when passing around Feature objects to ensure the bits we're checking for are
61 /// This Context represents when the Feature appears in the init message, sent between peers and not
62 /// rumored around the P2P network.
63 pub struct FeatureContextInit {}
64 /// The context in which a Feature object appears determines which bits of features the node
65 /// supports will be set. We use this when creating our own Feature objects to select which bits to
66 /// set and when passing around Feature objects to ensure the bits we're checking for are
69 /// This Context represents when the Feature appears in the node_announcement message, as it is
70 /// rumored around the P2P network.
71 pub struct FeatureContextNode {}
72 /// The context in which a Feature object appears determines which bits of features the node
73 /// supports will be set. We use this when creating our own Feature objects to select which bits to
74 /// set and when passing around Feature objects to ensure the bits we're checking for are
77 /// This Context represents when the Feature appears in the ChannelAnnouncement message, as it is
78 /// rumored around the P2P network.
79 pub struct FeatureContextChannel {}
80 /// The context in which a Feature object appears determines which bits of features the node
81 /// supports will be set. We use this when creating our own Feature objects to select which bits to
82 /// set and when passing around Feature objects to ensure the bits we're checking for are
85 /// This Context represents when the Feature appears in an invoice, used to determine the different
86 /// options available for routing a payment.
88 /// Note that this is currently unused as invoices come to us via a different crate and are not
89 /// native to rust-lightning directly.
90 pub struct FeatureContextInvoice {}
92 /// An internal trait capturing the various future context types
93 pub trait FeatureContext {}
94 impl FeatureContext for FeatureContextInit {}
95 impl FeatureContext for FeatureContextNode {}
96 impl FeatureContext for FeatureContextChannel {}
97 impl FeatureContext for FeatureContextInvoice {}
99 /// An internal trait capturing FeatureContextInit and FeatureContextNode
100 pub trait FeatureContextInitNode : FeatureContext {}
101 impl FeatureContextInitNode for FeatureContextInit {}
102 impl FeatureContextInitNode for FeatureContextNode {}
104 /// Tracks the set of features which a node implements, templated by the context in which it
106 pub struct Features<T: FeatureContext> {
108 /// Note that, for convinience, flags is LITTLE endian (despite being big-endian on the wire)
110 // Used to test encoding of diverse msgs
113 mark: PhantomData<T>,
116 impl<T: FeatureContext> Clone for Features<T> {
117 fn clone(&self) -> Self {
119 flags: self.flags.clone(),
124 impl<T: FeatureContext> PartialEq for Features<T> {
125 fn eq(&self, o: &Self) -> bool {
126 self.flags.eq(&o.flags)
129 impl<T: FeatureContext> fmt::Debug for Features<T> {
130 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
135 /// A feature message as it appears in an init message
136 pub type InitFeatures = Features<FeatureContextInit>;
137 /// A feature message as it appears in a node_announcement message
138 pub type NodeFeatures = Features<FeatureContextNode>;
139 /// A feature message as it appears in a channel_announcement message
140 pub type ChannelFeatures = Features<FeatureContextChannel>;
142 impl<T: FeatureContextInitNode> Features<T> {
143 /// Create a Features with the features we support
144 #[cfg(not(feature = "fuzztarget"))]
145 pub(crate) fn supported() -> Features<T> {
147 flags: vec![2 | 1 << 5],
151 #[cfg(feature = "fuzztarget")]
152 pub fn supported() -> Features<T> {
154 flags: vec![2 | 1 << 5],
160 impl Features<FeatureContextChannel> {
161 /// Create a Features with the features we support
162 #[cfg(not(feature = "fuzztarget"))]
163 pub(crate) fn supported() -> Features<FeatureContextChannel> {
169 #[cfg(feature = "fuzztarget")]
170 pub fn supported() -> Features<FeatureContextChannel> {
178 impl<T: FeatureContext> Features<T> {
179 /// Create a blank Features with no fetures set
180 pub fn empty() -> Features<T> {
187 pub(crate) fn requires_unknown_bits(&self) -> bool {
188 self.flags.iter().enumerate().any(|(idx, &byte)| {
189 ( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 )
193 pub(crate) fn supports_unknown_bits(&self) -> bool {
194 self.flags.iter().enumerate().any(|(idx, &byte)| {
195 ( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 )
199 /// The number of bytes required to represent the feaature flags present. This does not include
200 /// the length bytes which are included in the serialized form.
201 pub(crate) fn byte_count(&self) -> usize {
206 pub(crate) fn set_require_unknown_bits(&mut self) {
207 let newlen = cmp::max(2, self.flags.len());
208 self.flags.resize(newlen, 0u8);
209 self.flags[1] |= 0x40;
213 pub(crate) fn clear_require_unknown_bits(&mut self) {
214 let newlen = cmp::max(2, self.flags.len());
215 self.flags.resize(newlen, 0u8);
216 self.flags[1] &= !0x40;
217 if self.flags.len() == 2 && self.flags[1] == 0 {
218 self.flags.resize(1, 0u8);
223 impl<T: FeatureContextInitNode> Features<T> {
224 pub(crate) fn supports_data_loss_protect(&self) -> bool {
225 self.flags.len() > 0 && (self.flags[0] & 3) != 0
228 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
229 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
232 pub(crate) fn unset_upfront_shutdown_script(&mut self) {
233 self.flags[0] ^= 1 << 5;
237 impl Features<FeatureContextInit> {
238 pub(crate) fn initial_routing_sync(&self) -> bool {
239 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
241 pub(crate) fn set_initial_routing_sync(&mut self) {
242 if self.flags.len() == 0 {
243 self.flags.resize(1, 1 << 3);
245 self.flags[0] |= 1 << 3;
249 /// Writes all features present up to, and including, 13.
250 pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
251 let len = cmp::min(2, self.flags.len());
252 w.size_hint(len + 2);
253 (len as u16).write(w)?;
254 for i in (0..len).rev() {
256 self.flags[i].write(w)?;
258 (self.flags[i] & ((1 << (14 - 8)) - 1)).write(w)?;
264 /// or's another InitFeatures into this one.
265 pub(crate) fn or(&mut self, o: &InitFeatures) {
266 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
267 self.flags.resize(total_feature_len, 0u8);
268 for (feature, o_feature) in self.flags.iter_mut().zip(o.flags.iter()) {
269 *feature |= *o_feature;
274 impl<T: FeatureContext> Writeable for Features<T> {
275 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
276 w.size_hint(self.flags.len() + 2);
277 (self.flags.len() as u16).write(w)?;
278 for f in self.flags.iter().rev() { // We have to swap the endianness back to BE for writing
285 impl<R: ::std::io::Read, T: FeatureContext> Readable<R> for Features<T> {
286 fn read(r: &mut R) -> Result<Self, DecodeError> {
287 let mut flags: Vec<u8> = Readable::read(r)?;
288 flags.reverse(); // Swap to big-endian
296 /// An init message to be sent or received from a peer
298 pub(crate) features: InitFeatures,
301 /// An error message to be sent or received from a peer
303 pub struct ErrorMessage {
304 pub(crate) channel_id: [u8; 32],
305 pub(crate) data: String,
308 /// A ping message to be sent or received from a peer
310 pub(crate) ponglen: u16,
311 pub(crate) byteslen: u16,
314 /// A pong message to be sent or received from a peer
316 pub(crate) byteslen: u16,
319 /// An open_channel message to be sent or received from a peer
321 pub struct OpenChannel {
322 pub(crate) chain_hash: Sha256dHash,
323 pub(crate) temporary_channel_id: [u8; 32],
324 pub(crate) funding_satoshis: u64,
325 pub(crate) push_msat: u64,
326 pub(crate) dust_limit_satoshis: u64,
327 pub(crate) max_htlc_value_in_flight_msat: u64,
328 pub(crate) channel_reserve_satoshis: u64,
329 pub(crate) htlc_minimum_msat: u64,
330 pub(crate) feerate_per_kw: u32,
331 pub(crate) to_self_delay: u16,
332 pub(crate) max_accepted_htlcs: u16,
333 pub(crate) funding_pubkey: PublicKey,
334 pub(crate) revocation_basepoint: PublicKey,
335 pub(crate) payment_basepoint: PublicKey,
336 pub(crate) delayed_payment_basepoint: PublicKey,
337 pub(crate) htlc_basepoint: PublicKey,
338 pub(crate) first_per_commitment_point: PublicKey,
339 pub(crate) channel_flags: u8,
340 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
343 /// An accept_channel message to be sent or received from a peer
345 pub struct AcceptChannel {
346 pub(crate) temporary_channel_id: [u8; 32],
347 pub(crate) dust_limit_satoshis: u64,
348 pub(crate) max_htlc_value_in_flight_msat: u64,
349 pub(crate) channel_reserve_satoshis: u64,
350 pub(crate) htlc_minimum_msat: u64,
351 pub(crate) minimum_depth: u32,
352 pub(crate) to_self_delay: u16,
353 pub(crate) max_accepted_htlcs: u16,
354 pub(crate) funding_pubkey: PublicKey,
355 pub(crate) revocation_basepoint: PublicKey,
356 pub(crate) payment_basepoint: PublicKey,
357 pub(crate) delayed_payment_basepoint: PublicKey,
358 pub(crate) htlc_basepoint: PublicKey,
359 pub(crate) first_per_commitment_point: PublicKey,
360 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
363 /// A funding_created message to be sent or received from a peer
365 pub struct FundingCreated {
366 pub(crate) temporary_channel_id: [u8; 32],
367 pub(crate) funding_txid: Sha256dHash,
368 pub(crate) funding_output_index: u16,
369 pub(crate) signature: Signature,
372 /// A funding_signed message to be sent or received from a peer
374 pub struct FundingSigned {
375 pub(crate) channel_id: [u8; 32],
376 pub(crate) signature: Signature,
379 /// A funding_locked message to be sent or received from a peer
380 #[derive(Clone, PartialEq)]
381 pub struct FundingLocked {
382 pub(crate) channel_id: [u8; 32],
383 pub(crate) next_per_commitment_point: PublicKey,
386 /// A shutdown message to be sent or received from a peer
387 #[derive(Clone, PartialEq)]
388 pub struct Shutdown {
389 pub(crate) channel_id: [u8; 32],
390 pub(crate) scriptpubkey: Script,
393 /// A closing_signed message to be sent or received from a peer
394 #[derive(Clone, PartialEq)]
395 pub struct ClosingSigned {
396 pub(crate) channel_id: [u8; 32],
397 pub(crate) fee_satoshis: u64,
398 pub(crate) signature: Signature,
401 /// An update_add_htlc message to be sent or received from a peer
402 #[derive(Clone, PartialEq)]
403 pub struct UpdateAddHTLC {
404 pub(crate) channel_id: [u8; 32],
405 pub(crate) htlc_id: u64,
406 pub(crate) amount_msat: u64,
407 pub(crate) payment_hash: PaymentHash,
408 pub(crate) cltv_expiry: u32,
409 pub(crate) onion_routing_packet: OnionPacket,
412 /// An update_fulfill_htlc message to be sent or received from a peer
413 #[derive(Clone, PartialEq)]
414 pub struct UpdateFulfillHTLC {
415 pub(crate) channel_id: [u8; 32],
416 pub(crate) htlc_id: u64,
417 pub(crate) payment_preimage: PaymentPreimage,
420 /// An update_fail_htlc message to be sent or received from a peer
421 #[derive(Clone, PartialEq)]
422 pub struct UpdateFailHTLC {
423 pub(crate) channel_id: [u8; 32],
424 pub(crate) htlc_id: u64,
425 pub(crate) reason: OnionErrorPacket,
428 /// An update_fail_malformed_htlc message to be sent or received from a peer
429 #[derive(Clone, PartialEq)]
430 pub struct UpdateFailMalformedHTLC {
431 pub(crate) channel_id: [u8; 32],
432 pub(crate) htlc_id: u64,
433 pub(crate) sha256_of_onion: [u8; 32],
434 pub(crate) failure_code: u16,
437 /// A commitment_signed message to be sent or received from a peer
438 #[derive(Clone, PartialEq)]
439 pub struct CommitmentSigned {
440 pub(crate) channel_id: [u8; 32],
441 pub(crate) signature: Signature,
442 pub(crate) htlc_signatures: Vec<Signature>,
445 /// A revoke_and_ack message to be sent or received from a peer
446 #[derive(Clone, PartialEq)]
447 pub struct RevokeAndACK {
448 pub(crate) channel_id: [u8; 32],
449 pub(crate) per_commitment_secret: [u8; 32],
450 pub(crate) next_per_commitment_point: PublicKey,
453 /// An update_fee message to be sent or received from a peer
454 #[derive(PartialEq, Clone)]
455 pub struct UpdateFee {
456 pub(crate) channel_id: [u8; 32],
457 pub(crate) feerate_per_kw: u32,
460 #[derive(PartialEq, Clone)]
461 pub(crate) struct DataLossProtect {
462 pub(crate) your_last_per_commitment_secret: [u8; 32],
463 pub(crate) my_current_per_commitment_point: PublicKey,
466 /// A channel_reestablish message to be sent or received from a peer
467 #[derive(PartialEq, Clone)]
468 pub struct ChannelReestablish {
469 pub(crate) channel_id: [u8; 32],
470 pub(crate) next_local_commitment_number: u64,
471 pub(crate) next_remote_commitment_number: u64,
472 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
475 /// An announcement_signatures message to be sent or received from a peer
476 #[derive(PartialEq, Clone, Debug)]
477 pub struct AnnouncementSignatures {
478 pub(crate) channel_id: [u8; 32],
479 pub(crate) short_channel_id: u64,
480 pub(crate) node_signature: Signature,
481 pub(crate) bitcoin_signature: Signature,
484 /// An address which can be used to connect to a remote peer
485 #[derive(Clone, PartialEq, Debug)]
486 pub enum NetAddress {
487 /// An IPv4 address/port on which the peer is listening.
489 /// The 4-byte IPv4 address
491 /// The port on which the node is listening
494 /// An IPv6 address/port on which the peer is listening.
496 /// The 16-byte IPv6 address
498 /// The port on which the node is listening
501 /// An old-style Tor onion address/port on which the peer is listening.
503 /// The bytes (usually encoded in base32 with ".onion" appended)
505 /// The port on which the node is listening
508 /// A new-style Tor onion address/port on which the peer is listening.
509 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
510 /// wrap as base32 and append ".onion".
512 /// The ed25519 long-term public key of the peer
513 ed25519_pubkey: [u8; 32],
514 /// The checksum of the pubkey and version, as included in the onion address
516 /// The version byte, as defined by the Tor Onion v3 spec.
518 /// The port on which the node is listening
523 fn get_id(&self) -> u8 {
525 &NetAddress::IPv4 {..} => { 1 },
526 &NetAddress::IPv6 {..} => { 2 },
527 &NetAddress::OnionV2 {..} => { 3 },
528 &NetAddress::OnionV3 {..} => { 4 },
532 /// Strict byte-length of address descriptor, 1-byte type not recorded
533 fn len(&self) -> u16 {
535 &NetAddress::IPv4 { .. } => { 6 },
536 &NetAddress::IPv6 { .. } => { 18 },
537 &NetAddress::OnionV2 { .. } => { 12 },
538 &NetAddress::OnionV3 { .. } => { 37 },
543 impl Writeable for NetAddress {
544 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
546 &NetAddress::IPv4 { ref addr, ref port } => {
551 &NetAddress::IPv6 { ref addr, ref port } => {
556 &NetAddress::OnionV2 { ref addr, ref port } => {
561 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
563 ed25519_pubkey.write(writer)?;
564 checksum.write(writer)?;
565 version.write(writer)?;
573 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
574 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
575 let byte = <u8 as Readable<R>>::read(reader)?;
578 Ok(Ok(NetAddress::IPv4 {
579 addr: Readable::read(reader)?,
580 port: Readable::read(reader)?,
584 Ok(Ok(NetAddress::IPv6 {
585 addr: Readable::read(reader)?,
586 port: Readable::read(reader)?,
590 Ok(Ok(NetAddress::OnionV2 {
591 addr: Readable::read(reader)?,
592 port: Readable::read(reader)?,
596 Ok(Ok(NetAddress::OnionV3 {
597 ed25519_pubkey: Readable::read(reader)?,
598 checksum: Readable::read(reader)?,
599 version: Readable::read(reader)?,
600 port: Readable::read(reader)?,
603 _ => return Ok(Err(byte)),
608 // Only exposed as broadcast of node_announcement should be filtered by node_id
609 /// The unsigned part of a node_announcement
610 #[derive(PartialEq, Clone, Debug)]
611 pub struct UnsignedNodeAnnouncement {
612 pub(crate) features: NodeFeatures,
613 pub(crate) timestamp: u32,
614 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
616 pub node_id: PublicKey,
617 pub(crate) rgb: [u8; 3],
618 pub(crate) alias: [u8; 32],
619 /// List of addresses on which this node is reachable. Note that you may only have up to one
620 /// address of each type, if you have more, they may be silently discarded or we may panic!
621 pub(crate) addresses: Vec<NetAddress>,
622 pub(crate) excess_address_data: Vec<u8>,
623 pub(crate) excess_data: Vec<u8>,
625 #[derive(PartialEq, Clone)]
626 /// A node_announcement message to be sent or received from a peer
627 pub struct NodeAnnouncement {
628 pub(crate) signature: Signature,
629 pub(crate) contents: UnsignedNodeAnnouncement,
632 // Only exposed as broadcast of channel_announcement should be filtered by node_id
633 /// The unsigned part of a channel_announcement
634 #[derive(PartialEq, Clone, Debug)]
635 pub struct UnsignedChannelAnnouncement {
636 pub(crate) features: ChannelFeatures,
637 pub(crate) chain_hash: Sha256dHash,
638 pub(crate) short_channel_id: u64,
639 /// One of the two node_ids which are endpoints of this channel
640 pub node_id_1: PublicKey,
641 /// The other of the two node_ids which are endpoints of this channel
642 pub node_id_2: PublicKey,
643 pub(crate) bitcoin_key_1: PublicKey,
644 pub(crate) bitcoin_key_2: PublicKey,
645 pub(crate) excess_data: Vec<u8>,
647 /// A channel_announcement message to be sent or received from a peer
648 #[derive(PartialEq, Clone, Debug)]
649 pub struct ChannelAnnouncement {
650 pub(crate) node_signature_1: Signature,
651 pub(crate) node_signature_2: Signature,
652 pub(crate) bitcoin_signature_1: Signature,
653 pub(crate) bitcoin_signature_2: Signature,
654 pub(crate) contents: UnsignedChannelAnnouncement,
657 #[derive(PartialEq, Clone, Debug)]
658 pub(crate) struct UnsignedChannelUpdate {
659 pub(crate) chain_hash: Sha256dHash,
660 pub(crate) short_channel_id: u64,
661 pub(crate) timestamp: u32,
662 pub(crate) flags: u16,
663 pub(crate) cltv_expiry_delta: u16,
664 pub(crate) htlc_minimum_msat: u64,
665 pub(crate) fee_base_msat: u32,
666 pub(crate) fee_proportional_millionths: u32,
667 pub(crate) excess_data: Vec<u8>,
669 /// A channel_update message to be sent or received from a peer
670 #[derive(PartialEq, Clone, Debug)]
671 pub struct ChannelUpdate {
672 pub(crate) signature: Signature,
673 pub(crate) contents: UnsignedChannelUpdate,
676 /// Used to put an error message in a LightningError
678 pub enum ErrorAction {
679 /// The peer took some action which made us think they were useless. Disconnect them.
681 /// An error message which we should make an effort to send before we disconnect.
682 msg: Option<ErrorMessage>
684 /// The peer did something harmless that we weren't able to process, just log and ignore
686 /// The peer did something incorrect. Tell them.
688 /// The message to send.
693 /// An Err type for failure to process messages.
694 pub struct LightningError {
695 /// A human-readable message describing the error
696 pub err: &'static str,
697 /// The action which should be taken against the offending peer.
698 pub action: ErrorAction,
701 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
702 /// transaction updates if they were pending.
703 #[derive(PartialEq, Clone)]
704 pub struct CommitmentUpdate {
705 /// update_add_htlc messages which should be sent
706 pub update_add_htlcs: Vec<UpdateAddHTLC>,
707 /// update_fulfill_htlc messages which should be sent
708 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
709 /// update_fail_htlc messages which should be sent
710 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
711 /// update_fail_malformed_htlc messages which should be sent
712 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
713 /// An update_fee message which should be sent
714 pub update_fee: Option<UpdateFee>,
715 /// Finally, the commitment_signed message which should be sent
716 pub commitment_signed: CommitmentSigned,
719 /// The information we received from a peer along the route of a payment we originated. This is
720 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
721 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
723 pub enum HTLCFailChannelUpdate {
724 /// We received an error which included a full ChannelUpdate message.
725 ChannelUpdateMessage {
726 /// The unwrapped message we received
729 /// We received an error which indicated only that a channel has been closed
731 /// The short_channel_id which has now closed.
732 short_channel_id: u64,
733 /// when this true, this channel should be permanently removed from the
734 /// consideration. Otherwise, this channel can be restored as new channel_update is received
737 /// We received an error which indicated only that a node has failed
739 /// The node_id that has failed.
741 /// when this true, node should be permanently removed from the
742 /// consideration. Otherwise, the channels connected to this node can be
743 /// restored as new channel_update is received
748 /// Messages could have optional fields to use with extended features
749 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
750 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
751 /// separate enum type for them.
752 #[derive(Clone, PartialEq)]
753 pub enum OptionalField<T> {
754 /// Optional field is included in message
756 /// Optional field is absent in message
760 /// A trait to describe an object which can receive channel messages.
762 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
763 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
764 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
766 /// Handle an incoming open_channel message from the given peer.
767 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
768 /// Handle an incoming accept_channel message from the given peer.
769 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
770 /// Handle an incoming funding_created message from the given peer.
771 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
772 /// Handle an incoming funding_signed message from the given peer.
773 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
774 /// Handle an incoming funding_locked message from the given peer.
775 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
778 /// Handle an incoming shutdown message from the given peer.
779 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
780 /// Handle an incoming closing_signed message from the given peer.
781 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
784 /// Handle an incoming update_add_htlc message from the given peer.
785 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
786 /// Handle an incoming update_fulfill_htlc message from the given peer.
787 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
788 /// Handle an incoming update_fail_htlc message from the given peer.
789 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
790 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
791 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
792 /// Handle an incoming commitment_signed message from the given peer.
793 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
794 /// Handle an incoming revoke_and_ack message from the given peer.
795 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
797 /// Handle an incoming update_fee message from the given peer.
798 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
800 // Channel-to-announce:
801 /// Handle an incoming announcement_signatures message from the given peer.
802 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
804 // Connection loss/reestablish:
805 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
806 /// is believed to be possible in the future (eg they're sending us messages we don't
807 /// understand or indicate they require unknown feature bits), no_connection_possible is set
808 /// and any outstanding channels should be failed.
809 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
811 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
812 fn peer_connected(&self, their_node_id: &PublicKey);
813 /// Handle an incoming channel_reestablish message from the given peer.
814 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
817 /// Handle an incoming error message from the given peer.
818 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
821 /// A trait to describe an object which can receive routing messages.
822 pub trait RoutingMessageHandler : Send + Sync {
823 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
824 /// false or returning an Err otherwise.
825 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
826 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
827 /// or returning an Err otherwise.
828 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
829 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
830 /// false or returning an Err otherwise.
831 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
832 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
833 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
834 /// Gets a subset of the channel announcements and updates required to dump our routing table
835 /// to a remote node, starting at the short_channel_id indicated by starting_point and
836 /// including batch_amount entries.
837 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
838 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
839 /// starting at the node *after* the provided publickey and including batch_amount entries.
840 /// If None is provided for starting_point, we start at the first node.
841 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
844 pub(crate) struct OnionRealm0HopData {
845 pub(crate) short_channel_id: u64,
846 pub(crate) amt_to_forward: u64,
847 pub(crate) outgoing_cltv_value: u32,
848 // 12 bytes of 0-padding
851 mod fuzzy_internal_msgs {
852 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
853 // them from untrusted input):
855 use super::OnionRealm0HopData;
856 pub struct OnionHopData {
857 pub(crate) realm: u8,
858 pub(crate) data: OnionRealm0HopData,
859 pub(crate) hmac: [u8; 32],
862 pub struct DecodedOnionErrorPacket {
863 pub(crate) hmac: [u8; 32],
864 pub(crate) failuremsg: Vec<u8>,
865 pub(crate) pad: Vec<u8>,
868 #[cfg(feature = "fuzztarget")]
869 pub use self::fuzzy_internal_msgs::*;
870 #[cfg(not(feature = "fuzztarget"))]
871 pub(crate) use self::fuzzy_internal_msgs::*;
874 pub(crate) struct OnionPacket {
875 pub(crate) version: u8,
876 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
877 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
878 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
879 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
880 pub(crate) hop_data: [u8; 20*65],
881 pub(crate) hmac: [u8; 32],
884 impl PartialEq for OnionPacket {
885 fn eq(&self, other: &OnionPacket) -> bool {
886 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
887 if i != j { return false; }
889 self.version == other.version &&
890 self.public_key == other.public_key &&
891 self.hmac == other.hmac
895 #[derive(Clone, PartialEq)]
896 pub(crate) struct OnionErrorPacket {
897 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
898 // (TODO) We limit it in decode to much lower...
899 pub(crate) data: Vec<u8>,
902 impl Error for DecodeError {
903 fn description(&self) -> &str {
905 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
906 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
907 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
908 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
909 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
910 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
911 DecodeError::Io(ref e) => e.description(),
915 impl fmt::Display for DecodeError {
916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
917 f.write_str(self.description())
921 impl fmt::Debug for LightningError {
922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923 f.write_str(self.err)
927 impl From<::std::io::Error> for DecodeError {
928 fn from(e: ::std::io::Error) -> Self {
929 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
930 DecodeError::ShortRead
937 impl Writeable for OptionalField<Script> {
938 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
940 OptionalField::Present(ref script) => {
941 // Note that Writeable for script includes the 16-bit length tag for us
944 OptionalField::Absent => {}
950 impl<R: Read> Readable<R> for OptionalField<Script> {
951 fn read(r: &mut R) -> Result<Self, DecodeError> {
952 match <u16 as Readable<R>>::read(r) {
954 let mut buf = vec![0; len as usize];
955 r.read_exact(&mut buf)?;
956 Ok(OptionalField::Present(Script::from(buf)))
958 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
964 impl_writeable_len_match!(AcceptChannel, {
965 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
968 temporary_channel_id,
970 max_htlc_value_in_flight_msat,
971 channel_reserve_satoshis,
977 revocation_basepoint,
979 delayed_payment_basepoint,
981 first_per_commitment_point,
982 shutdown_scriptpubkey
985 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
992 impl Writeable for ChannelReestablish {
993 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
994 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
995 self.channel_id.write(w)?;
996 self.next_local_commitment_number.write(w)?;
997 self.next_remote_commitment_number.write(w)?;
998 match self.data_loss_protect {
999 OptionalField::Present(ref data_loss_protect) => {
1000 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
1001 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
1003 OptionalField::Absent => {}
1009 impl<R: Read> Readable<R> for ChannelReestablish{
1010 fn read(r: &mut R) -> Result<Self, DecodeError> {
1012 channel_id: Readable::read(r)?,
1013 next_local_commitment_number: Readable::read(r)?,
1014 next_remote_commitment_number: Readable::read(r)?,
1015 data_loss_protect: {
1016 match <[u8; 32] as Readable<R>>::read(r) {
1017 Ok(your_last_per_commitment_secret) =>
1018 OptionalField::Present(DataLossProtect {
1019 your_last_per_commitment_secret,
1020 my_current_per_commitment_point: Readable::read(r)?,
1022 Err(DecodeError::ShortRead) => OptionalField::Absent,
1023 Err(e) => return Err(e)
1030 impl_writeable!(ClosingSigned, 32+8+64, {
1036 impl_writeable_len_match!(CommitmentSigned, {
1037 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
1044 impl_writeable_len_match!(DecodedOnionErrorPacket, {
1045 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
1052 impl_writeable!(FundingCreated, 32+32+2+64, {
1053 temporary_channel_id,
1055 funding_output_index,
1059 impl_writeable!(FundingSigned, 32+64, {
1064 impl_writeable!(FundingLocked, 32+33, {
1066 next_per_commitment_point
1069 impl Writeable for Init {
1070 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1071 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1072 // our relevant feature bits. This keeps us compatible with old nodes.
1073 self.features.write_up_to_13(w)?;
1074 self.features.write(w)
1078 impl<R: Read> Readable<R> for Init {
1079 fn read(r: &mut R) -> Result<Self, DecodeError> {
1080 let global_features: InitFeatures = Readable::read(r)?;
1081 let mut features: InitFeatures = Readable::read(r)?;
1082 features.or(&global_features);
1089 impl_writeable_len_match!(OpenChannel, {
1090 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
1094 temporary_channel_id,
1097 dust_limit_satoshis,
1098 max_htlc_value_in_flight_msat,
1099 channel_reserve_satoshis,
1105 revocation_basepoint,
1107 delayed_payment_basepoint,
1109 first_per_commitment_point,
1111 shutdown_scriptpubkey
1114 impl_writeable!(RevokeAndACK, 32+32+33, {
1116 per_commitment_secret,
1117 next_per_commitment_point
1120 impl_writeable_len_match!(Shutdown, {
1121 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
1127 impl_writeable_len_match!(UpdateFailHTLC, {
1128 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
1135 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
1142 impl_writeable!(UpdateFee, 32+4, {
1147 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1153 impl_writeable_len_match!(OnionErrorPacket, {
1154 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1159 impl Writeable for OnionPacket {
1160 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1161 w.size_hint(1 + 33 + 20*65 + 32);
1162 self.version.write(w)?;
1163 match self.public_key {
1164 Ok(pubkey) => pubkey.write(w)?,
1165 Err(_) => [0u8;33].write(w)?,
1167 w.write_all(&self.hop_data)?;
1168 self.hmac.write(w)?;
1173 impl<R: Read> Readable<R> for OnionPacket {
1174 fn read(r: &mut R) -> Result<Self, DecodeError> {
1176 version: Readable::read(r)?,
1178 let mut buf = [0u8;33];
1179 r.read_exact(&mut buf)?;
1180 PublicKey::from_slice(&buf)
1182 hop_data: Readable::read(r)?,
1183 hmac: Readable::read(r)?,
1188 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1194 onion_routing_packet
1197 impl Writeable for OnionRealm0HopData {
1198 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1200 self.short_channel_id.write(w)?;
1201 self.amt_to_forward.write(w)?;
1202 self.outgoing_cltv_value.write(w)?;
1203 w.write_all(&[0;12])?;
1208 impl<R: Read> Readable<R> for OnionRealm0HopData {
1209 fn read(r: &mut R) -> Result<Self, DecodeError> {
1210 Ok(OnionRealm0HopData {
1211 short_channel_id: Readable::read(r)?,
1212 amt_to_forward: Readable::read(r)?,
1213 outgoing_cltv_value: {
1214 let v: u32 = Readable::read(r)?;
1215 r.read_exact(&mut [0; 12])?;
1222 impl Writeable for OnionHopData {
1223 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1225 self.realm.write(w)?;
1226 self.data.write(w)?;
1227 self.hmac.write(w)?;
1232 impl<R: Read> Readable<R> for OnionHopData {
1233 fn read(r: &mut R) -> Result<Self, DecodeError> {
1236 let r: u8 = Readable::read(r)?;
1238 return Err(DecodeError::UnknownVersion);
1242 data: Readable::read(r)?,
1243 hmac: Readable::read(r)?,
1248 impl Writeable for Ping {
1249 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1250 w.size_hint(self.byteslen as usize + 4);
1251 self.ponglen.write(w)?;
1252 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1257 impl<R: Read> Readable<R> for Ping {
1258 fn read(r: &mut R) -> Result<Self, DecodeError> {
1260 ponglen: Readable::read(r)?,
1262 let byteslen = Readable::read(r)?;
1263 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1270 impl Writeable for Pong {
1271 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1272 w.size_hint(self.byteslen as usize + 2);
1273 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1278 impl<R: Read> Readable<R> for Pong {
1279 fn read(r: &mut R) -> Result<Self, DecodeError> {
1282 let byteslen = Readable::read(r)?;
1283 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1290 impl Writeable for UnsignedChannelAnnouncement {
1291 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1292 w.size_hint(2 + 2*32 + 4*33 + self.features.byte_count() + self.excess_data.len());
1293 self.features.write(w)?;
1294 self.chain_hash.write(w)?;
1295 self.short_channel_id.write(w)?;
1296 self.node_id_1.write(w)?;
1297 self.node_id_2.write(w)?;
1298 self.bitcoin_key_1.write(w)?;
1299 self.bitcoin_key_2.write(w)?;
1300 w.write_all(&self.excess_data[..])?;
1305 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1306 fn read(r: &mut R) -> Result<Self, DecodeError> {
1308 features: Readable::read(r)?,
1309 chain_hash: Readable::read(r)?,
1310 short_channel_id: Readable::read(r)?,
1311 node_id_1: Readable::read(r)?,
1312 node_id_2: Readable::read(r)?,
1313 bitcoin_key_1: Readable::read(r)?,
1314 bitcoin_key_2: Readable::read(r)?,
1316 let mut excess_data = vec![];
1317 r.read_to_end(&mut excess_data)?;
1324 impl_writeable_len_match!(ChannelAnnouncement, {
1325 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1326 2 + 2*32 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1330 bitcoin_signature_1,
1331 bitcoin_signature_2,
1335 impl Writeable for UnsignedChannelUpdate {
1336 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1337 w.size_hint(64 + self.excess_data.len());
1338 self.chain_hash.write(w)?;
1339 self.short_channel_id.write(w)?;
1340 self.timestamp.write(w)?;
1341 self.flags.write(w)?;
1342 self.cltv_expiry_delta.write(w)?;
1343 self.htlc_minimum_msat.write(w)?;
1344 self.fee_base_msat.write(w)?;
1345 self.fee_proportional_millionths.write(w)?;
1346 w.write_all(&self.excess_data[..])?;
1351 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1352 fn read(r: &mut R) -> Result<Self, DecodeError> {
1354 chain_hash: Readable::read(r)?,
1355 short_channel_id: Readable::read(r)?,
1356 timestamp: Readable::read(r)?,
1357 flags: Readable::read(r)?,
1358 cltv_expiry_delta: Readable::read(r)?,
1359 htlc_minimum_msat: Readable::read(r)?,
1360 fee_base_msat: Readable::read(r)?,
1361 fee_proportional_millionths: Readable::read(r)?,
1363 let mut excess_data = vec![];
1364 r.read_to_end(&mut excess_data)?;
1371 impl_writeable_len_match!(ChannelUpdate, {
1372 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1373 64 + excess_data.len() + 64 }
1379 impl Writeable for ErrorMessage {
1380 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1381 w.size_hint(32 + 2 + self.data.len());
1382 self.channel_id.write(w)?;
1383 (self.data.len() as u16).write(w)?;
1384 w.write_all(self.data.as_bytes())?;
1389 impl<R: Read> Readable<R> for ErrorMessage {
1390 fn read(r: &mut R) -> Result<Self, DecodeError> {
1392 channel_id: Readable::read(r)?,
1394 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1395 let mut data = vec![];
1396 let data_len = r.read_to_end(&mut data)?;
1397 sz = cmp::min(data_len, sz);
1398 match String::from_utf8(data[..sz as usize].to_vec()) {
1400 Err(_) => return Err(DecodeError::InvalidValue),
1407 impl Writeable for UnsignedNodeAnnouncement {
1408 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1409 w.size_hint(64 + 76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1410 self.features.write(w)?;
1411 self.timestamp.write(w)?;
1412 self.node_id.write(w)?;
1413 w.write_all(&self.rgb)?;
1414 self.alias.write(w)?;
1416 let mut addrs_to_encode = self.addresses.clone();
1417 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1418 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1419 let mut addr_len = 0;
1420 for addr in &addrs_to_encode {
1421 addr_len += 1 + addr.len();
1423 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1424 for addr in addrs_to_encode {
1427 w.write_all(&self.excess_address_data[..])?;
1428 w.write_all(&self.excess_data[..])?;
1433 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1434 fn read(r: &mut R) -> Result<Self, DecodeError> {
1435 let features: NodeFeatures = Readable::read(r)?;
1436 let timestamp: u32 = Readable::read(r)?;
1437 let node_id: PublicKey = Readable::read(r)?;
1438 let mut rgb = [0; 3];
1439 r.read_exact(&mut rgb)?;
1440 let alias: [u8; 32] = Readable::read(r)?;
1442 let addr_len: u16 = Readable::read(r)?;
1443 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1444 let mut addr_readpos = 0;
1445 let mut excess = false;
1446 let mut excess_byte = 0;
1448 if addr_len <= addr_readpos { break; }
1449 match Readable::read(r) {
1452 NetAddress::IPv4 { .. } => {
1453 if addresses.len() > 0 {
1454 return Err(DecodeError::ExtraAddressesPerType);
1457 NetAddress::IPv6 { .. } => {
1458 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1459 return Err(DecodeError::ExtraAddressesPerType);
1462 NetAddress::OnionV2 { .. } => {
1463 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1464 return Err(DecodeError::ExtraAddressesPerType);
1467 NetAddress::OnionV3 { .. } => {
1468 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1469 return Err(DecodeError::ExtraAddressesPerType);
1473 if addr_len < addr_readpos + 1 + addr.len() {
1474 return Err(DecodeError::BadLengthDescriptor);
1476 addr_readpos += (1 + addr.len()) as u16;
1477 addresses.push(addr);
1479 Ok(Err(unknown_descriptor)) => {
1481 excess_byte = unknown_descriptor;
1484 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1485 Err(e) => return Err(e),
1489 let mut excess_data = vec![];
1490 let excess_address_data = if addr_readpos < addr_len {
1491 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1492 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1494 excess_address_data[0] = excess_byte;
1499 excess_data.push(excess_byte);
1503 r.read_to_end(&mut excess_data)?;
1504 Ok(UnsignedNodeAnnouncement {
1511 excess_address_data,
1517 impl_writeable_len_match!(NodeAnnouncement, {
1518 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1519 64 + 76 + features.byte_count() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1529 use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket};
1530 use ln::channelmanager::{PaymentPreimage, PaymentHash};
1531 use util::ser::Writeable;
1533 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1534 use bitcoin_hashes::hex::FromHex;
1535 use bitcoin::util::address::Address;
1536 use bitcoin::network::constants::Network;
1537 use bitcoin::blockdata::script::Builder;
1538 use bitcoin::blockdata::opcodes;
1540 use secp256k1::key::{PublicKey,SecretKey};
1541 use secp256k1::{Secp256k1, Message};
1543 use std::marker::PhantomData;
1546 fn encoding_channel_reestablish_no_secret() {
1547 let cr = msgs::ChannelReestablish {
1548 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],
1549 next_local_commitment_number: 3,
1550 next_remote_commitment_number: 4,
1551 data_loss_protect: OptionalField::Absent,
1554 let encoded_value = cr.encode();
1557 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]
1562 fn encoding_channel_reestablish_with_secret() {
1564 let secp_ctx = Secp256k1::new();
1565 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1568 let cr = msgs::ChannelReestablish {
1569 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],
1570 next_local_commitment_number: 3,
1571 next_remote_commitment_number: 4,
1572 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1575 let encoded_value = cr.encode();
1578 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]
1582 macro_rules! get_keys_from {
1583 ($slice: expr, $secp_ctx: expr) => {
1585 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1586 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1592 macro_rules! get_sig_on {
1593 ($privkey: expr, $ctx: expr, $string: expr) => {
1595 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1596 $ctx.sign(&sighash, &$privkey)
1602 fn encoding_announcement_signatures() {
1603 let secp_ctx = Secp256k1::new();
1604 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1605 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1606 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1607 let announcement_signatures = msgs::AnnouncementSignatures {
1608 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],
1609 short_channel_id: 2316138423780173,
1610 node_signature: sig_1,
1611 bitcoin_signature: sig_2,
1614 let encoded_value = announcement_signatures.encode();
1615 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1618 fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
1619 let secp_ctx = Secp256k1::new();
1620 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1621 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1622 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1623 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1624 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1625 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1626 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1627 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1628 let mut features = ChannelFeatures::supported();
1629 if unknown_features_bits {
1630 features.flags = vec![0xFF, 0xFF];
1632 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1634 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1635 short_channel_id: 2316138423780173,
1636 node_id_1: pubkey_1,
1637 node_id_2: pubkey_2,
1638 bitcoin_key_1: pubkey_3,
1639 bitcoin_key_2: pubkey_4,
1640 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1642 let channel_announcement = msgs::ChannelAnnouncement {
1643 node_signature_1: sig_1,
1644 node_signature_2: sig_2,
1645 bitcoin_signature_1: sig_3,
1646 bitcoin_signature_2: sig_4,
1647 contents: unsigned_channel_announcement,
1649 let encoded_value = channel_announcement.encode();
1650 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1651 if unknown_features_bits {
1652 target_value.append(&mut hex::decode("0002ffff").unwrap());
1654 target_value.append(&mut hex::decode("0000").unwrap());
1656 if non_bitcoin_chain_hash {
1657 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1659 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1661 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1663 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1665 assert_eq!(encoded_value, target_value);
1669 fn encoding_channel_announcement() {
1670 do_encoding_channel_announcement(false, false, false);
1671 do_encoding_channel_announcement(true, false, false);
1672 do_encoding_channel_announcement(true, true, false);
1673 do_encoding_channel_announcement(true, true, true);
1674 do_encoding_channel_announcement(false, true, true);
1675 do_encoding_channel_announcement(false, false, true);
1676 do_encoding_channel_announcement(false, true, false);
1677 do_encoding_channel_announcement(true, false, true);
1680 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1681 let secp_ctx = Secp256k1::new();
1682 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1683 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1684 let mut features = NodeFeatures::empty();
1685 if unknown_features_bits {
1686 features.flags = vec![0xFF, 0xFF];
1688 // Set to some features we may support
1689 features.flags = vec![2 | 1 << 5];
1691 let mut addresses = Vec::new();
1693 addresses.push(msgs::NetAddress::IPv4 {
1694 addr: [255, 254, 253, 252],
1699 addresses.push(msgs::NetAddress::IPv6 {
1700 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1705 addresses.push(msgs::NetAddress::OnionV2 {
1706 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1711 addresses.push(msgs::NetAddress::OnionV3 {
1712 ed25519_pubkey: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224],
1718 let mut addr_len = 0;
1719 for addr in &addresses {
1720 addr_len += addr.len() + 1;
1722 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1724 timestamp: 20190119,
1729 excess_address_data: if excess_address_data { vec![33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34, 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84, 174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42, 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105] } else { Vec::new() },
1730 excess_data: if excess_data { vec![59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160, 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8, 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17, 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253] } else { Vec::new() },
1732 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1733 let node_announcement = msgs::NodeAnnouncement {
1735 contents: unsigned_node_announcement,
1737 let encoded_value = node_announcement.encode();
1738 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1739 if unknown_features_bits {
1740 target_value.append(&mut hex::decode("0002ffff").unwrap());
1742 target_value.append(&mut hex::decode("000122").unwrap());
1744 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1745 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1747 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1750 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1753 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1756 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1758 if excess_address_data {
1759 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1762 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1764 assert_eq!(encoded_value, target_value);
1768 fn encoding_node_announcement() {
1769 do_encoding_node_announcement(true, true, true, true, true, true, true);
1770 do_encoding_node_announcement(false, false, false, false, false, false, false);
1771 do_encoding_node_announcement(false, true, false, false, false, false, false);
1772 do_encoding_node_announcement(false, false, true, false, false, false, false);
1773 do_encoding_node_announcement(false, false, false, true, false, false, false);
1774 do_encoding_node_announcement(false, false, false, false, true, false, false);
1775 do_encoding_node_announcement(false, false, false, false, false, true, false);
1776 do_encoding_node_announcement(false, true, false, true, false, true, false);
1777 do_encoding_node_announcement(false, false, true, false, true, false, false);
1780 fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
1781 let secp_ctx = Secp256k1::new();
1782 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1783 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1784 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1785 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1786 short_channel_id: 2316138423780173,
1787 timestamp: 20190119,
1788 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
1789 cltv_expiry_delta: 144,
1790 htlc_minimum_msat: 1000000,
1791 fee_base_msat: 10000,
1792 fee_proportional_millionths: 20,
1793 excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1795 let channel_update = msgs::ChannelUpdate {
1797 contents: unsigned_channel_update
1799 let encoded_value = channel_update.encode();
1800 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1801 if non_bitcoin_chain_hash {
1802 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1804 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1806 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1807 if htlc_maximum_msat {
1808 target_value.append(&mut hex::decode("01").unwrap());
1810 target_value.append(&mut hex::decode("00").unwrap());
1812 target_value.append(&mut hex::decode("00").unwrap());
1814 let flag = target_value.last_mut().unwrap();
1818 let flag = target_value.last_mut().unwrap();
1819 *flag = *flag | 1 << 1;
1821 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1822 if htlc_maximum_msat {
1823 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1825 assert_eq!(encoded_value, target_value);
1829 fn encoding_channel_update() {
1830 do_encoding_channel_update(false, false, false, false);
1831 do_encoding_channel_update(true, false, false, false);
1832 do_encoding_channel_update(false, true, false, false);
1833 do_encoding_channel_update(false, false, true, false);
1834 do_encoding_channel_update(false, false, false, true);
1835 do_encoding_channel_update(true, true, true, true);
1838 fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
1839 let secp_ctx = Secp256k1::new();
1840 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1841 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1842 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1843 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1844 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1845 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1846 let open_channel = msgs::OpenChannel {
1847 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1848 temporary_channel_id: [2; 32],
1849 funding_satoshis: 1311768467284833366,
1850 push_msat: 2536655962884945560,
1851 dust_limit_satoshis: 3608586615801332854,
1852 max_htlc_value_in_flight_msat: 8517154655701053848,
1853 channel_reserve_satoshis: 8665828695742877976,
1854 htlc_minimum_msat: 2316138423780173,
1855 feerate_per_kw: 821716,
1856 to_self_delay: 49340,
1857 max_accepted_htlcs: 49340,
1858 funding_pubkey: pubkey_1,
1859 revocation_basepoint: pubkey_2,
1860 payment_basepoint: pubkey_3,
1861 delayed_payment_basepoint: pubkey_4,
1862 htlc_basepoint: pubkey_5,
1863 first_per_commitment_point: pubkey_6,
1864 channel_flags: if random_bit { 1 << 5 } else { 0 },
1865 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1867 let encoded_value = open_channel.encode();
1868 let mut target_value = Vec::new();
1869 if non_bitcoin_chain_hash {
1870 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1872 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1874 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1876 target_value.append(&mut hex::decode("20").unwrap());
1878 target_value.append(&mut hex::decode("00").unwrap());
1881 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1883 assert_eq!(encoded_value, target_value);
1887 fn encoding_open_channel() {
1888 do_encoding_open_channel(false, false, false);
1889 do_encoding_open_channel(true, false, false);
1890 do_encoding_open_channel(false, true, false);
1891 do_encoding_open_channel(false, false, true);
1892 do_encoding_open_channel(true, true, true);
1895 fn do_encoding_accept_channel(shutdown: bool) {
1896 let secp_ctx = Secp256k1::new();
1897 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1898 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1899 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1900 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1901 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1902 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1903 let accept_channel = msgs::AcceptChannel {
1904 temporary_channel_id: [2; 32],
1905 dust_limit_satoshis: 1311768467284833366,
1906 max_htlc_value_in_flight_msat: 2536655962884945560,
1907 channel_reserve_satoshis: 3608586615801332854,
1908 htlc_minimum_msat: 2316138423780173,
1909 minimum_depth: 821716,
1910 to_self_delay: 49340,
1911 max_accepted_htlcs: 49340,
1912 funding_pubkey: pubkey_1,
1913 revocation_basepoint: pubkey_2,
1914 payment_basepoint: pubkey_3,
1915 delayed_payment_basepoint: pubkey_4,
1916 htlc_basepoint: pubkey_5,
1917 first_per_commitment_point: pubkey_6,
1918 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1920 let encoded_value = accept_channel.encode();
1921 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1923 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1925 assert_eq!(encoded_value, target_value);
1929 fn encoding_accept_channel() {
1930 do_encoding_accept_channel(false);
1931 do_encoding_accept_channel(true);
1935 fn encoding_funding_created() {
1936 let secp_ctx = Secp256k1::new();
1937 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1938 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1939 let funding_created = msgs::FundingCreated {
1940 temporary_channel_id: [2; 32],
1941 funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1942 funding_output_index: 255,
1945 let encoded_value = funding_created.encode();
1946 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1947 assert_eq!(encoded_value, target_value);
1951 fn encoding_funding_signed() {
1952 let secp_ctx = Secp256k1::new();
1953 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1954 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1955 let funding_signed = msgs::FundingSigned {
1956 channel_id: [2; 32],
1959 let encoded_value = funding_signed.encode();
1960 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1961 assert_eq!(encoded_value, target_value);
1965 fn encoding_funding_locked() {
1966 let secp_ctx = Secp256k1::new();
1967 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1968 let funding_locked = msgs::FundingLocked {
1969 channel_id: [2; 32],
1970 next_per_commitment_point: pubkey_1,
1972 let encoded_value = funding_locked.encode();
1973 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1974 assert_eq!(encoded_value, target_value);
1977 fn do_encoding_shutdown(script_type: u8) {
1978 let secp_ctx = Secp256k1::new();
1979 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1980 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1981 let shutdown = msgs::Shutdown {
1982 channel_id: [2; 32],
1983 scriptpubkey: if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() } else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
1985 let encoded_value = shutdown.encode();
1986 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1987 if script_type == 1 {
1988 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1989 } else if script_type == 2 {
1990 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1991 } else if script_type == 3 {
1992 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1993 } else if script_type == 4 {
1994 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1996 assert_eq!(encoded_value, target_value);
2000 fn encoding_shutdown() {
2001 do_encoding_shutdown(1);
2002 do_encoding_shutdown(2);
2003 do_encoding_shutdown(3);
2004 do_encoding_shutdown(4);
2008 fn encoding_closing_signed() {
2009 let secp_ctx = Secp256k1::new();
2010 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2011 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2012 let closing_signed = msgs::ClosingSigned {
2013 channel_id: [2; 32],
2014 fee_satoshis: 2316138423780173,
2017 let encoded_value = closing_signed.encode();
2018 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2019 assert_eq!(encoded_value, target_value);
2023 fn encoding_update_add_htlc() {
2024 let secp_ctx = Secp256k1::new();
2025 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2026 let onion_routing_packet = msgs::OnionPacket {
2028 public_key: Ok(pubkey_1),
2029 hop_data: [1; 20*65],
2032 let update_add_htlc = msgs::UpdateAddHTLC {
2033 channel_id: [2; 32],
2034 htlc_id: 2316138423780173,
2035 amount_msat: 3608586615801332854,
2036 payment_hash: PaymentHash([1; 32]),
2037 cltv_expiry: 821716,
2038 onion_routing_packet
2040 let encoded_value = update_add_htlc.encode();
2041 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
2042 assert_eq!(encoded_value, target_value);
2046 fn encoding_update_fulfill_htlc() {
2047 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
2048 channel_id: [2; 32],
2049 htlc_id: 2316138423780173,
2050 payment_preimage: PaymentPreimage([1; 32]),
2052 let encoded_value = update_fulfill_htlc.encode();
2053 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
2054 assert_eq!(encoded_value, target_value);
2058 fn encoding_update_fail_htlc() {
2059 let reason = OnionErrorPacket {
2060 data: [1; 32].to_vec(),
2062 let update_fail_htlc = msgs::UpdateFailHTLC {
2063 channel_id: [2; 32],
2064 htlc_id: 2316138423780173,
2067 let encoded_value = update_fail_htlc.encode();
2068 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
2069 assert_eq!(encoded_value, target_value);
2073 fn encoding_update_fail_malformed_htlc() {
2074 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
2075 channel_id: [2; 32],
2076 htlc_id: 2316138423780173,
2077 sha256_of_onion: [1; 32],
2080 let encoded_value = update_fail_malformed_htlc.encode();
2081 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
2082 assert_eq!(encoded_value, target_value);
2085 fn do_encoding_commitment_signed(htlcs: bool) {
2086 let secp_ctx = Secp256k1::new();
2087 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2088 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2089 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2090 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2091 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2092 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2093 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2094 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2095 let commitment_signed = msgs::CommitmentSigned {
2096 channel_id: [2; 32],
2098 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
2100 let encoded_value = commitment_signed.encode();
2101 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2103 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2105 target_value.append(&mut hex::decode("0000").unwrap());
2107 assert_eq!(encoded_value, target_value);
2111 fn encoding_commitment_signed() {
2112 do_encoding_commitment_signed(true);
2113 do_encoding_commitment_signed(false);
2117 fn encoding_revoke_and_ack() {
2118 let secp_ctx = Secp256k1::new();
2119 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2120 let raa = msgs::RevokeAndACK {
2121 channel_id: [2; 32],
2122 per_commitment_secret: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
2123 next_per_commitment_point: pubkey_1,
2125 let encoded_value = raa.encode();
2126 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2127 assert_eq!(encoded_value, target_value);
2131 fn encoding_update_fee() {
2132 let update_fee = msgs::UpdateFee {
2133 channel_id: [2; 32],
2134 feerate_per_kw: 20190119,
2136 let encoded_value = update_fee.encode();
2137 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2138 assert_eq!(encoded_value, target_value);
2142 fn encoding_init() {
2143 assert_eq!(msgs::Init {
2144 features: InitFeatures {
2145 flags: vec![0xFF, 0xFF, 0xFF],
2148 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2149 assert_eq!(msgs::Init {
2150 features: InitFeatures {
2154 }.encode(), hex::decode("0001ff0001ff").unwrap());
2155 assert_eq!(msgs::Init {
2156 features: InitFeatures {
2160 }.encode(), hex::decode("00000000").unwrap());
2164 fn encoding_error() {
2165 let error = msgs::ErrorMessage {
2166 channel_id: [2; 32],
2167 data: String::from("rust-lightning"),
2169 let encoded_value = error.encode();
2170 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2171 assert_eq!(encoded_value, target_value);
2175 fn encoding_ping() {
2176 let ping = msgs::Ping {
2180 let encoded_value = ping.encode();
2181 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2182 assert_eq!(encoded_value, target_value);
2186 fn encoding_pong() {
2187 let pong = msgs::Pong {
2190 let encoded_value = pong.encode();
2191 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2192 assert_eq!(encoded_value, target_value);