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> {
109 // Used to test encoding of diverse msgs
112 mark: PhantomData<T>,
115 impl<T: FeatureContext> Clone for Features<T> {
116 fn clone(&self) -> Self {
118 flags: self.flags.clone(),
123 impl<T: FeatureContext> PartialEq for Features<T> {
124 fn eq(&self, o: &Self) -> bool {
125 self.flags.eq(&o.flags)
128 impl<T: FeatureContext> fmt::Debug for Features<T> {
129 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
134 /// A feature message as it appears in an init message
135 pub type InitFeatures = Features<FeatureContextInit>;
136 /// A feature message as it appears in a node_announcement message
137 pub type NodeFeatures = Features<FeatureContextNode>;
138 /// A feature message as it appears in a channel_announcement message
139 pub type ChannelFeatures = Features<FeatureContextChannel>;
141 impl<T: FeatureContextInitNode> Features<T> {
142 /// Create a blank Features flags (visibility extended for fuzz tests)
143 #[cfg(not(feature = "fuzztarget"))]
144 pub(crate) fn new() -> Features<T> {
146 flags: vec![2 | 1 << 5],
150 #[cfg(feature = "fuzztarget")]
151 pub fn new() -> Features<T> {
153 flags: vec![2 | 1 << 5],
159 impl Features<FeatureContextChannel> {
160 /// Create a blank Features flags (visibility extended for fuzz tests)
161 #[cfg(not(feature = "fuzztarget"))]
162 pub(crate) fn new() -> Features<FeatureContextChannel> {
168 #[cfg(feature = "fuzztarget")]
169 pub fn new() -> Features<FeatureContextChannel> {
177 impl<T: FeatureContext> Features<T> {
178 pub(crate) fn requires_unknown_bits(&self) -> bool {
179 self.flags.iter().enumerate().any(|(idx, &byte)| {
180 ( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 )
184 pub(crate) fn supports_unknown_bits(&self) -> bool {
185 self.flags.iter().enumerate().any(|(idx, &byte)| {
186 ( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 )
190 /// The number of bytes required to represent the feaature flags present. This does not include
191 /// the length bytes which are included in the serialized form.
192 pub(crate) fn byte_count(&self) -> usize {
197 pub(crate) fn set_require_unknown_bits(&mut self) {
198 let newlen = cmp::max(2, self.flags.len());
199 self.flags.resize(newlen, 0u8);
200 self.flags[1] |= 0x40;
204 pub(crate) fn clear_require_unknown_bits(&mut self) {
205 let newlen = cmp::max(2, self.flags.len());
206 self.flags.resize(newlen, 0u8);
207 self.flags[1] &= !0x40;
208 if self.flags.len() == 2 && self.flags[1] == 0 {
209 self.flags.resize(1, 0u8);
214 impl<T: FeatureContextInitNode> Features<T> {
215 pub(crate) fn supports_data_loss_protect(&self) -> bool {
216 self.flags.len() > 0 && (self.flags[0] & 3) != 0
219 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
220 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
223 pub(crate) fn unset_upfront_shutdown_script(&mut self) {
224 self.flags[0] ^= 1 << 5;
228 impl Features<FeatureContextInit> {
229 pub(crate) fn initial_routing_sync(&self) -> bool {
230 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
232 pub(crate) fn set_initial_routing_sync(&mut self) {
233 if self.flags.len() == 0 {
234 self.flags.resize(1, 1 << 3);
236 self.flags[0] |= 1 << 3;
240 /// Writes all features present up to, and including, 13.
241 pub(crate) fn write_up_to_13<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
242 let len = cmp::min(2, self.flags.len());
243 w.size_hint(len + 2);
244 (len as u16).write(w)?;
245 for i in (0..len).rev() {
247 self.flags[i].write(w)?;
249 (self.flags[i] & ((1 << (14 - 8)) - 1)).write(w)?;
255 /// or's another InitFeatures into this one.
256 pub(crate) fn or(&mut self, o: &InitFeatures) {
257 let total_feature_len = cmp::max(self.flags.len(), o.flags.len());
258 self.flags.resize(total_feature_len, 0u8);
259 for (feature, o_feature) in self.flags.iter_mut().zip(o.flags.iter()) {
260 *feature |= *o_feature;
265 impl<T: FeatureContext> Writeable for Features<T> {
266 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
267 w.size_hint(self.flags.len() + 2);
272 impl<R: ::std::io::Read, T: FeatureContext> Readable<R> for Features<T> {
273 fn read(r: &mut R) -> Result<Self, DecodeError> {
275 flags: Readable::read(r)?,
280 /// An init message to be sent or received from a peer
282 pub(crate) features: InitFeatures,
285 /// An error message to be sent or received from a peer
287 pub struct ErrorMessage {
288 pub(crate) channel_id: [u8; 32],
289 pub(crate) data: String,
292 /// A ping message to be sent or received from a peer
294 pub(crate) ponglen: u16,
295 pub(crate) byteslen: u16,
298 /// A pong message to be sent or received from a peer
300 pub(crate) byteslen: u16,
303 /// An open_channel message to be sent or received from a peer
305 pub struct OpenChannel {
306 pub(crate) chain_hash: Sha256dHash,
307 pub(crate) temporary_channel_id: [u8; 32],
308 pub(crate) funding_satoshis: u64,
309 pub(crate) push_msat: u64,
310 pub(crate) dust_limit_satoshis: u64,
311 pub(crate) max_htlc_value_in_flight_msat: u64,
312 pub(crate) channel_reserve_satoshis: u64,
313 pub(crate) htlc_minimum_msat: u64,
314 pub(crate) feerate_per_kw: u32,
315 pub(crate) to_self_delay: u16,
316 pub(crate) max_accepted_htlcs: u16,
317 pub(crate) funding_pubkey: PublicKey,
318 pub(crate) revocation_basepoint: PublicKey,
319 pub(crate) payment_basepoint: PublicKey,
320 pub(crate) delayed_payment_basepoint: PublicKey,
321 pub(crate) htlc_basepoint: PublicKey,
322 pub(crate) first_per_commitment_point: PublicKey,
323 pub(crate) channel_flags: u8,
324 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
327 /// An accept_channel message to be sent or received from a peer
329 pub struct AcceptChannel {
330 pub(crate) temporary_channel_id: [u8; 32],
331 pub(crate) dust_limit_satoshis: u64,
332 pub(crate) max_htlc_value_in_flight_msat: u64,
333 pub(crate) channel_reserve_satoshis: u64,
334 pub(crate) htlc_minimum_msat: u64,
335 pub(crate) minimum_depth: u32,
336 pub(crate) to_self_delay: u16,
337 pub(crate) max_accepted_htlcs: u16,
338 pub(crate) funding_pubkey: PublicKey,
339 pub(crate) revocation_basepoint: PublicKey,
340 pub(crate) payment_basepoint: PublicKey,
341 pub(crate) delayed_payment_basepoint: PublicKey,
342 pub(crate) htlc_basepoint: PublicKey,
343 pub(crate) first_per_commitment_point: PublicKey,
344 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
347 /// A funding_created message to be sent or received from a peer
349 pub struct FundingCreated {
350 pub(crate) temporary_channel_id: [u8; 32],
351 pub(crate) funding_txid: Sha256dHash,
352 pub(crate) funding_output_index: u16,
353 pub(crate) signature: Signature,
356 /// A funding_signed message to be sent or received from a peer
358 pub struct FundingSigned {
359 pub(crate) channel_id: [u8; 32],
360 pub(crate) signature: Signature,
363 /// A funding_locked message to be sent or received from a peer
364 #[derive(Clone, PartialEq)]
365 pub struct FundingLocked {
366 pub(crate) channel_id: [u8; 32],
367 pub(crate) next_per_commitment_point: PublicKey,
370 /// A shutdown message to be sent or received from a peer
371 #[derive(Clone, PartialEq)]
372 pub struct Shutdown {
373 pub(crate) channel_id: [u8; 32],
374 pub(crate) scriptpubkey: Script,
377 /// A closing_signed message to be sent or received from a peer
378 #[derive(Clone, PartialEq)]
379 pub struct ClosingSigned {
380 pub(crate) channel_id: [u8; 32],
381 pub(crate) fee_satoshis: u64,
382 pub(crate) signature: Signature,
385 /// An update_add_htlc message to be sent or received from a peer
386 #[derive(Clone, PartialEq)]
387 pub struct UpdateAddHTLC {
388 pub(crate) channel_id: [u8; 32],
389 pub(crate) htlc_id: u64,
390 pub(crate) amount_msat: u64,
391 pub(crate) payment_hash: PaymentHash,
392 pub(crate) cltv_expiry: u32,
393 pub(crate) onion_routing_packet: OnionPacket,
396 /// An update_fulfill_htlc message to be sent or received from a peer
397 #[derive(Clone, PartialEq)]
398 pub struct UpdateFulfillHTLC {
399 pub(crate) channel_id: [u8; 32],
400 pub(crate) htlc_id: u64,
401 pub(crate) payment_preimage: PaymentPreimage,
404 /// An update_fail_htlc message to be sent or received from a peer
405 #[derive(Clone, PartialEq)]
406 pub struct UpdateFailHTLC {
407 pub(crate) channel_id: [u8; 32],
408 pub(crate) htlc_id: u64,
409 pub(crate) reason: OnionErrorPacket,
412 /// An update_fail_malformed_htlc message to be sent or received from a peer
413 #[derive(Clone, PartialEq)]
414 pub struct UpdateFailMalformedHTLC {
415 pub(crate) channel_id: [u8; 32],
416 pub(crate) htlc_id: u64,
417 pub(crate) sha256_of_onion: [u8; 32],
418 pub(crate) failure_code: u16,
421 /// A commitment_signed message to be sent or received from a peer
422 #[derive(Clone, PartialEq)]
423 pub struct CommitmentSigned {
424 pub(crate) channel_id: [u8; 32],
425 pub(crate) signature: Signature,
426 pub(crate) htlc_signatures: Vec<Signature>,
429 /// A revoke_and_ack message to be sent or received from a peer
430 #[derive(Clone, PartialEq)]
431 pub struct RevokeAndACK {
432 pub(crate) channel_id: [u8; 32],
433 pub(crate) per_commitment_secret: [u8; 32],
434 pub(crate) next_per_commitment_point: PublicKey,
437 /// An update_fee message to be sent or received from a peer
438 #[derive(PartialEq, Clone)]
439 pub struct UpdateFee {
440 pub(crate) channel_id: [u8; 32],
441 pub(crate) feerate_per_kw: u32,
444 #[derive(PartialEq, Clone)]
445 pub(crate) struct DataLossProtect {
446 pub(crate) your_last_per_commitment_secret: [u8; 32],
447 pub(crate) my_current_per_commitment_point: PublicKey,
450 /// A channel_reestablish message to be sent or received from a peer
451 #[derive(PartialEq, Clone)]
452 pub struct ChannelReestablish {
453 pub(crate) channel_id: [u8; 32],
454 pub(crate) next_local_commitment_number: u64,
455 pub(crate) next_remote_commitment_number: u64,
456 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
459 /// An announcement_signatures message to be sent or received from a peer
460 #[derive(PartialEq, Clone, Debug)]
461 pub struct AnnouncementSignatures {
462 pub(crate) channel_id: [u8; 32],
463 pub(crate) short_channel_id: u64,
464 pub(crate) node_signature: Signature,
465 pub(crate) bitcoin_signature: Signature,
468 /// An address which can be used to connect to a remote peer
469 #[derive(Clone, PartialEq, Debug)]
470 pub enum NetAddress {
471 /// An IPv4 address/port on which the peer is listening.
473 /// The 4-byte IPv4 address
475 /// The port on which the node is listening
478 /// An IPv6 address/port on which the peer is listening.
480 /// The 16-byte IPv6 address
482 /// The port on which the node is listening
485 /// An old-style Tor onion address/port on which the peer is listening.
487 /// The bytes (usually encoded in base32 with ".onion" appended)
489 /// The port on which the node is listening
492 /// A new-style Tor onion address/port on which the peer is listening.
493 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
494 /// wrap as base32 and append ".onion".
496 /// The ed25519 long-term public key of the peer
497 ed25519_pubkey: [u8; 32],
498 /// The checksum of the pubkey and version, as included in the onion address
500 /// The version byte, as defined by the Tor Onion v3 spec.
502 /// The port on which the node is listening
507 fn get_id(&self) -> u8 {
509 &NetAddress::IPv4 {..} => { 1 },
510 &NetAddress::IPv6 {..} => { 2 },
511 &NetAddress::OnionV2 {..} => { 3 },
512 &NetAddress::OnionV3 {..} => { 4 },
516 /// Strict byte-length of address descriptor, 1-byte type not recorded
517 fn len(&self) -> u16 {
519 &NetAddress::IPv4 { .. } => { 6 },
520 &NetAddress::IPv6 { .. } => { 18 },
521 &NetAddress::OnionV2 { .. } => { 12 },
522 &NetAddress::OnionV3 { .. } => { 37 },
527 impl Writeable for NetAddress {
528 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
530 &NetAddress::IPv4 { ref addr, ref port } => {
535 &NetAddress::IPv6 { ref addr, ref port } => {
540 &NetAddress::OnionV2 { ref addr, ref port } => {
545 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
547 ed25519_pubkey.write(writer)?;
548 checksum.write(writer)?;
549 version.write(writer)?;
557 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
558 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
559 let byte = <u8 as Readable<R>>::read(reader)?;
562 Ok(Ok(NetAddress::IPv4 {
563 addr: Readable::read(reader)?,
564 port: Readable::read(reader)?,
568 Ok(Ok(NetAddress::IPv6 {
569 addr: Readable::read(reader)?,
570 port: Readable::read(reader)?,
574 Ok(Ok(NetAddress::OnionV2 {
575 addr: Readable::read(reader)?,
576 port: Readable::read(reader)?,
580 Ok(Ok(NetAddress::OnionV3 {
581 ed25519_pubkey: Readable::read(reader)?,
582 checksum: Readable::read(reader)?,
583 version: Readable::read(reader)?,
584 port: Readable::read(reader)?,
587 _ => return Ok(Err(byte)),
592 // Only exposed as broadcast of node_announcement should be filtered by node_id
593 /// The unsigned part of a node_announcement
594 #[derive(PartialEq, Clone, Debug)]
595 pub struct UnsignedNodeAnnouncement {
596 pub(crate) features: NodeFeatures,
597 pub(crate) timestamp: u32,
598 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
600 pub node_id: PublicKey,
601 pub(crate) rgb: [u8; 3],
602 pub(crate) alias: [u8; 32],
603 /// List of addresses on which this node is reachable. Note that you may only have up to one
604 /// address of each type, if you have more, they may be silently discarded or we may panic!
605 pub(crate) addresses: Vec<NetAddress>,
606 pub(crate) excess_address_data: Vec<u8>,
607 pub(crate) excess_data: Vec<u8>,
609 #[derive(PartialEq, Clone)]
610 /// A node_announcement message to be sent or received from a peer
611 pub struct NodeAnnouncement {
612 pub(crate) signature: Signature,
613 pub(crate) contents: UnsignedNodeAnnouncement,
616 // Only exposed as broadcast of channel_announcement should be filtered by node_id
617 /// The unsigned part of a channel_announcement
618 #[derive(PartialEq, Clone, Debug)]
619 pub struct UnsignedChannelAnnouncement {
620 pub(crate) features: ChannelFeatures,
621 pub(crate) chain_hash: Sha256dHash,
622 pub(crate) short_channel_id: u64,
623 /// One of the two node_ids which are endpoints of this channel
624 pub node_id_1: PublicKey,
625 /// The other of the two node_ids which are endpoints of this channel
626 pub node_id_2: PublicKey,
627 pub(crate) bitcoin_key_1: PublicKey,
628 pub(crate) bitcoin_key_2: PublicKey,
629 pub(crate) excess_data: Vec<u8>,
631 /// A channel_announcement message to be sent or received from a peer
632 #[derive(PartialEq, Clone, Debug)]
633 pub struct ChannelAnnouncement {
634 pub(crate) node_signature_1: Signature,
635 pub(crate) node_signature_2: Signature,
636 pub(crate) bitcoin_signature_1: Signature,
637 pub(crate) bitcoin_signature_2: Signature,
638 pub(crate) contents: UnsignedChannelAnnouncement,
641 #[derive(PartialEq, Clone, Debug)]
642 pub(crate) struct UnsignedChannelUpdate {
643 pub(crate) chain_hash: Sha256dHash,
644 pub(crate) short_channel_id: u64,
645 pub(crate) timestamp: u32,
646 pub(crate) flags: u16,
647 pub(crate) cltv_expiry_delta: u16,
648 pub(crate) htlc_minimum_msat: u64,
649 pub(crate) fee_base_msat: u32,
650 pub(crate) fee_proportional_millionths: u32,
651 pub(crate) excess_data: Vec<u8>,
653 /// A channel_update message to be sent or received from a peer
654 #[derive(PartialEq, Clone, Debug)]
655 pub struct ChannelUpdate {
656 pub(crate) signature: Signature,
657 pub(crate) contents: UnsignedChannelUpdate,
660 /// Used to put an error message in a LightningError
662 pub enum ErrorAction {
663 /// The peer took some action which made us think they were useless. Disconnect them.
665 /// An error message which we should make an effort to send before we disconnect.
666 msg: Option<ErrorMessage>
668 /// The peer did something harmless that we weren't able to process, just log and ignore
670 /// The peer did something incorrect. Tell them.
672 /// The message to send.
677 /// An Err type for failure to process messages.
678 pub struct LightningError {
679 /// A human-readable message describing the error
680 pub err: &'static str,
681 /// The action which should be taken against the offending peer.
682 pub action: ErrorAction,
685 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
686 /// transaction updates if they were pending.
687 #[derive(PartialEq, Clone)]
688 pub struct CommitmentUpdate {
689 /// update_add_htlc messages which should be sent
690 pub update_add_htlcs: Vec<UpdateAddHTLC>,
691 /// update_fulfill_htlc messages which should be sent
692 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
693 /// update_fail_htlc messages which should be sent
694 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
695 /// update_fail_malformed_htlc messages which should be sent
696 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
697 /// An update_fee message which should be sent
698 pub update_fee: Option<UpdateFee>,
699 /// Finally, the commitment_signed message which should be sent
700 pub commitment_signed: CommitmentSigned,
703 /// The information we received from a peer along the route of a payment we originated. This is
704 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
705 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
707 pub enum HTLCFailChannelUpdate {
708 /// We received an error which included a full ChannelUpdate message.
709 ChannelUpdateMessage {
710 /// The unwrapped message we received
713 /// We received an error which indicated only that a channel has been closed
715 /// The short_channel_id which has now closed.
716 short_channel_id: u64,
717 /// when this true, this channel should be permanently removed from the
718 /// consideration. Otherwise, this channel can be restored as new channel_update is received
721 /// We received an error which indicated only that a node has failed
723 /// The node_id that has failed.
725 /// when this true, node should be permanently removed from the
726 /// consideration. Otherwise, the channels connected to this node can be
727 /// restored as new channel_update is received
732 /// Messages could have optional fields to use with extended features
733 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
734 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
735 /// separate enum type for them.
736 #[derive(Clone, PartialEq)]
737 pub enum OptionalField<T> {
738 /// Optional field is included in message
740 /// Optional field is absent in message
744 /// A trait to describe an object which can receive channel messages.
746 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
747 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
748 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
750 /// Handle an incoming open_channel message from the given peer.
751 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
752 /// Handle an incoming accept_channel message from the given peer.
753 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
754 /// Handle an incoming funding_created message from the given peer.
755 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
756 /// Handle an incoming funding_signed message from the given peer.
757 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
758 /// Handle an incoming funding_locked message from the given peer.
759 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
762 /// Handle an incoming shutdown message from the given peer.
763 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
764 /// Handle an incoming closing_signed message from the given peer.
765 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
768 /// Handle an incoming update_add_htlc message from the given peer.
769 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
770 /// Handle an incoming update_fulfill_htlc message from the given peer.
771 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
772 /// Handle an incoming update_fail_htlc message from the given peer.
773 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
774 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
775 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
776 /// Handle an incoming commitment_signed message from the given peer.
777 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
778 /// Handle an incoming revoke_and_ack message from the given peer.
779 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
781 /// Handle an incoming update_fee message from the given peer.
782 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
784 // Channel-to-announce:
785 /// Handle an incoming announcement_signatures message from the given peer.
786 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
788 // Connection loss/reestablish:
789 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
790 /// is believed to be possible in the future (eg they're sending us messages we don't
791 /// understand or indicate they require unknown feature bits), no_connection_possible is set
792 /// and any outstanding channels should be failed.
793 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
795 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
796 fn peer_connected(&self, their_node_id: &PublicKey);
797 /// Handle an incoming channel_reestablish message from the given peer.
798 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
801 /// Handle an incoming error message from the given peer.
802 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
805 /// A trait to describe an object which can receive routing messages.
806 pub trait RoutingMessageHandler : Send + Sync {
807 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
808 /// false or returning an Err otherwise.
809 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
810 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
811 /// or returning an Err otherwise.
812 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
813 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
814 /// false or returning an Err otherwise.
815 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
816 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
817 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
818 /// Gets a subset of the channel announcements and updates required to dump our routing table
819 /// to a remote node, starting at the short_channel_id indicated by starting_point and
820 /// including batch_amount entries.
821 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
822 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
823 /// starting at the node *after* the provided publickey and including batch_amount entries.
824 /// If None is provided for starting_point, we start at the first node.
825 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
828 pub(crate) struct OnionRealm0HopData {
829 pub(crate) short_channel_id: u64,
830 pub(crate) amt_to_forward: u64,
831 pub(crate) outgoing_cltv_value: u32,
832 // 12 bytes of 0-padding
835 mod fuzzy_internal_msgs {
836 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
837 // them from untrusted input):
839 use super::OnionRealm0HopData;
840 pub struct OnionHopData {
841 pub(crate) realm: u8,
842 pub(crate) data: OnionRealm0HopData,
843 pub(crate) hmac: [u8; 32],
846 pub struct DecodedOnionErrorPacket {
847 pub(crate) hmac: [u8; 32],
848 pub(crate) failuremsg: Vec<u8>,
849 pub(crate) pad: Vec<u8>,
852 #[cfg(feature = "fuzztarget")]
853 pub use self::fuzzy_internal_msgs::*;
854 #[cfg(not(feature = "fuzztarget"))]
855 pub(crate) use self::fuzzy_internal_msgs::*;
858 pub(crate) struct OnionPacket {
859 pub(crate) version: u8,
860 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
861 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
862 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
863 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
864 pub(crate) hop_data: [u8; 20*65],
865 pub(crate) hmac: [u8; 32],
868 impl PartialEq for OnionPacket {
869 fn eq(&self, other: &OnionPacket) -> bool {
870 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
871 if i != j { return false; }
873 self.version == other.version &&
874 self.public_key == other.public_key &&
875 self.hmac == other.hmac
879 #[derive(Clone, PartialEq)]
880 pub(crate) struct OnionErrorPacket {
881 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
882 // (TODO) We limit it in decode to much lower...
883 pub(crate) data: Vec<u8>,
886 impl Error for DecodeError {
887 fn description(&self) -> &str {
889 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
890 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
891 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
892 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
893 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
894 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
895 DecodeError::Io(ref e) => e.description(),
899 impl fmt::Display for DecodeError {
900 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
901 f.write_str(self.description())
905 impl fmt::Debug for LightningError {
906 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
907 f.write_str(self.err)
911 impl From<::std::io::Error> for DecodeError {
912 fn from(e: ::std::io::Error) -> Self {
913 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
914 DecodeError::ShortRead
921 impl Writeable for OptionalField<Script> {
922 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
924 OptionalField::Present(ref script) => {
925 // Note that Writeable for script includes the 16-bit length tag for us
928 OptionalField::Absent => {}
934 impl<R: Read> Readable<R> for OptionalField<Script> {
935 fn read(r: &mut R) -> Result<Self, DecodeError> {
936 match <u16 as Readable<R>>::read(r) {
938 let mut buf = vec![0; len as usize];
939 r.read_exact(&mut buf)?;
940 Ok(OptionalField::Present(Script::from(buf)))
942 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
948 impl_writeable_len_match!(AcceptChannel, {
949 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
952 temporary_channel_id,
954 max_htlc_value_in_flight_msat,
955 channel_reserve_satoshis,
961 revocation_basepoint,
963 delayed_payment_basepoint,
965 first_per_commitment_point,
966 shutdown_scriptpubkey
969 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
976 impl Writeable for ChannelReestablish {
977 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
978 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
979 self.channel_id.write(w)?;
980 self.next_local_commitment_number.write(w)?;
981 self.next_remote_commitment_number.write(w)?;
982 match self.data_loss_protect {
983 OptionalField::Present(ref data_loss_protect) => {
984 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
985 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
987 OptionalField::Absent => {}
993 impl<R: Read> Readable<R> for ChannelReestablish{
994 fn read(r: &mut R) -> Result<Self, DecodeError> {
996 channel_id: Readable::read(r)?,
997 next_local_commitment_number: Readable::read(r)?,
998 next_remote_commitment_number: Readable::read(r)?,
1000 match <[u8; 32] as Readable<R>>::read(r) {
1001 Ok(your_last_per_commitment_secret) =>
1002 OptionalField::Present(DataLossProtect {
1003 your_last_per_commitment_secret,
1004 my_current_per_commitment_point: Readable::read(r)?,
1006 Err(DecodeError::ShortRead) => OptionalField::Absent,
1007 Err(e) => return Err(e)
1014 impl_writeable!(ClosingSigned, 32+8+64, {
1020 impl_writeable_len_match!(CommitmentSigned, {
1021 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
1028 impl_writeable_len_match!(DecodedOnionErrorPacket, {
1029 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
1036 impl_writeable!(FundingCreated, 32+32+2+64, {
1037 temporary_channel_id,
1039 funding_output_index,
1043 impl_writeable!(FundingSigned, 32+64, {
1048 impl_writeable!(FundingLocked, 32+33, {
1050 next_per_commitment_point
1053 impl Writeable for Init {
1054 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1055 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1056 // our relevant feature bits. This keeps us compatible with old nodes.
1057 self.features.write_up_to_13(w)?;
1058 self.features.write(w)
1062 impl<R: Read> Readable<R> for Init {
1063 fn read(r: &mut R) -> Result<Self, DecodeError> {
1064 let global_features: InitFeatures = Readable::read(r)?;
1065 let mut features: InitFeatures = Readable::read(r)?;
1066 features.or(&global_features);
1073 impl_writeable_len_match!(OpenChannel, {
1074 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
1078 temporary_channel_id,
1081 dust_limit_satoshis,
1082 max_htlc_value_in_flight_msat,
1083 channel_reserve_satoshis,
1089 revocation_basepoint,
1091 delayed_payment_basepoint,
1093 first_per_commitment_point,
1095 shutdown_scriptpubkey
1098 impl_writeable!(RevokeAndACK, 32+32+33, {
1100 per_commitment_secret,
1101 next_per_commitment_point
1104 impl_writeable_len_match!(Shutdown, {
1105 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
1111 impl_writeable_len_match!(UpdateFailHTLC, {
1112 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
1119 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
1126 impl_writeable!(UpdateFee, 32+4, {
1131 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1137 impl_writeable_len_match!(OnionErrorPacket, {
1138 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1143 impl Writeable for OnionPacket {
1144 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1145 w.size_hint(1 + 33 + 20*65 + 32);
1146 self.version.write(w)?;
1147 match self.public_key {
1148 Ok(pubkey) => pubkey.write(w)?,
1149 Err(_) => [0u8;33].write(w)?,
1151 w.write_all(&self.hop_data)?;
1152 self.hmac.write(w)?;
1157 impl<R: Read> Readable<R> for OnionPacket {
1158 fn read(r: &mut R) -> Result<Self, DecodeError> {
1160 version: Readable::read(r)?,
1162 let mut buf = [0u8;33];
1163 r.read_exact(&mut buf)?;
1164 PublicKey::from_slice(&buf)
1166 hop_data: Readable::read(r)?,
1167 hmac: Readable::read(r)?,
1172 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1178 onion_routing_packet
1181 impl Writeable for OnionRealm0HopData {
1182 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1184 self.short_channel_id.write(w)?;
1185 self.amt_to_forward.write(w)?;
1186 self.outgoing_cltv_value.write(w)?;
1187 w.write_all(&[0;12])?;
1192 impl<R: Read> Readable<R> for OnionRealm0HopData {
1193 fn read(r: &mut R) -> Result<Self, DecodeError> {
1194 Ok(OnionRealm0HopData {
1195 short_channel_id: Readable::read(r)?,
1196 amt_to_forward: Readable::read(r)?,
1197 outgoing_cltv_value: {
1198 let v: u32 = Readable::read(r)?;
1199 r.read_exact(&mut [0; 12])?;
1206 impl Writeable for OnionHopData {
1207 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1209 self.realm.write(w)?;
1210 self.data.write(w)?;
1211 self.hmac.write(w)?;
1216 impl<R: Read> Readable<R> for OnionHopData {
1217 fn read(r: &mut R) -> Result<Self, DecodeError> {
1220 let r: u8 = Readable::read(r)?;
1222 return Err(DecodeError::UnknownVersion);
1226 data: Readable::read(r)?,
1227 hmac: Readable::read(r)?,
1232 impl Writeable for Ping {
1233 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1234 w.size_hint(self.byteslen as usize + 4);
1235 self.ponglen.write(w)?;
1236 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1241 impl<R: Read> Readable<R> for Ping {
1242 fn read(r: &mut R) -> Result<Self, DecodeError> {
1244 ponglen: Readable::read(r)?,
1246 let byteslen = Readable::read(r)?;
1247 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1254 impl Writeable for Pong {
1255 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1256 w.size_hint(self.byteslen as usize + 2);
1257 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1262 impl<R: Read> Readable<R> for Pong {
1263 fn read(r: &mut R) -> Result<Self, DecodeError> {
1266 let byteslen = Readable::read(r)?;
1267 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1274 impl Writeable for UnsignedChannelAnnouncement {
1275 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1276 w.size_hint(2 + 2*32 + 4*33 + self.features.byte_count() + self.excess_data.len());
1277 self.features.write(w)?;
1278 self.chain_hash.write(w)?;
1279 self.short_channel_id.write(w)?;
1280 self.node_id_1.write(w)?;
1281 self.node_id_2.write(w)?;
1282 self.bitcoin_key_1.write(w)?;
1283 self.bitcoin_key_2.write(w)?;
1284 w.write_all(&self.excess_data[..])?;
1289 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1290 fn read(r: &mut R) -> Result<Self, DecodeError> {
1292 features: Readable::read(r)?,
1293 chain_hash: Readable::read(r)?,
1294 short_channel_id: Readable::read(r)?,
1295 node_id_1: Readable::read(r)?,
1296 node_id_2: Readable::read(r)?,
1297 bitcoin_key_1: Readable::read(r)?,
1298 bitcoin_key_2: Readable::read(r)?,
1300 let mut excess_data = vec![];
1301 r.read_to_end(&mut excess_data)?;
1308 impl_writeable_len_match!(ChannelAnnouncement, {
1309 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1310 2 + 2*32 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1314 bitcoin_signature_1,
1315 bitcoin_signature_2,
1319 impl Writeable for UnsignedChannelUpdate {
1320 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1321 w.size_hint(64 + self.excess_data.len());
1322 self.chain_hash.write(w)?;
1323 self.short_channel_id.write(w)?;
1324 self.timestamp.write(w)?;
1325 self.flags.write(w)?;
1326 self.cltv_expiry_delta.write(w)?;
1327 self.htlc_minimum_msat.write(w)?;
1328 self.fee_base_msat.write(w)?;
1329 self.fee_proportional_millionths.write(w)?;
1330 w.write_all(&self.excess_data[..])?;
1335 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1336 fn read(r: &mut R) -> Result<Self, DecodeError> {
1338 chain_hash: Readable::read(r)?,
1339 short_channel_id: Readable::read(r)?,
1340 timestamp: Readable::read(r)?,
1341 flags: Readable::read(r)?,
1342 cltv_expiry_delta: Readable::read(r)?,
1343 htlc_minimum_msat: Readable::read(r)?,
1344 fee_base_msat: Readable::read(r)?,
1345 fee_proportional_millionths: Readable::read(r)?,
1347 let mut excess_data = vec![];
1348 r.read_to_end(&mut excess_data)?;
1355 impl_writeable_len_match!(ChannelUpdate, {
1356 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1357 64 + excess_data.len() + 64 }
1363 impl Writeable for ErrorMessage {
1364 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1365 w.size_hint(32 + 2 + self.data.len());
1366 self.channel_id.write(w)?;
1367 (self.data.len() as u16).write(w)?;
1368 w.write_all(self.data.as_bytes())?;
1373 impl<R: Read> Readable<R> for ErrorMessage {
1374 fn read(r: &mut R) -> Result<Self, DecodeError> {
1376 channel_id: Readable::read(r)?,
1378 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1379 let mut data = vec![];
1380 let data_len = r.read_to_end(&mut data)?;
1381 sz = cmp::min(data_len, sz);
1382 match String::from_utf8(data[..sz as usize].to_vec()) {
1384 Err(_) => return Err(DecodeError::InvalidValue),
1391 impl Writeable for UnsignedNodeAnnouncement {
1392 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1393 w.size_hint(64 + 76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1394 self.features.write(w)?;
1395 self.timestamp.write(w)?;
1396 self.node_id.write(w)?;
1397 w.write_all(&self.rgb)?;
1398 self.alias.write(w)?;
1400 let mut addrs_to_encode = self.addresses.clone();
1401 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1402 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1403 let mut addr_len = 0;
1404 for addr in &addrs_to_encode {
1405 addr_len += 1 + addr.len();
1407 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1408 for addr in addrs_to_encode {
1411 w.write_all(&self.excess_address_data[..])?;
1412 w.write_all(&self.excess_data[..])?;
1417 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1418 fn read(r: &mut R) -> Result<Self, DecodeError> {
1419 let features: NodeFeatures = Readable::read(r)?;
1420 let timestamp: u32 = Readable::read(r)?;
1421 let node_id: PublicKey = Readable::read(r)?;
1422 let mut rgb = [0; 3];
1423 r.read_exact(&mut rgb)?;
1424 let alias: [u8; 32] = Readable::read(r)?;
1426 let addr_len: u16 = Readable::read(r)?;
1427 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1428 let mut addr_readpos = 0;
1429 let mut excess = false;
1430 let mut excess_byte = 0;
1432 if addr_len <= addr_readpos { break; }
1433 match Readable::read(r) {
1436 NetAddress::IPv4 { .. } => {
1437 if addresses.len() > 0 {
1438 return Err(DecodeError::ExtraAddressesPerType);
1441 NetAddress::IPv6 { .. } => {
1442 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1443 return Err(DecodeError::ExtraAddressesPerType);
1446 NetAddress::OnionV2 { .. } => {
1447 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1448 return Err(DecodeError::ExtraAddressesPerType);
1451 NetAddress::OnionV3 { .. } => {
1452 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1453 return Err(DecodeError::ExtraAddressesPerType);
1457 if addr_len < addr_readpos + 1 + addr.len() {
1458 return Err(DecodeError::BadLengthDescriptor);
1460 addr_readpos += (1 + addr.len()) as u16;
1461 addresses.push(addr);
1463 Ok(Err(unknown_descriptor)) => {
1465 excess_byte = unknown_descriptor;
1468 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1469 Err(e) => return Err(e),
1473 let mut excess_data = vec![];
1474 let excess_address_data = if addr_readpos < addr_len {
1475 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1476 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1478 excess_address_data[0] = excess_byte;
1483 excess_data.push(excess_byte);
1487 r.read_to_end(&mut excess_data)?;
1488 Ok(UnsignedNodeAnnouncement {
1495 excess_address_data,
1501 impl_writeable_len_match!(NodeAnnouncement, {
1502 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1503 64 + 76 + features.byte_count() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1513 use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket};
1514 use ln::channelmanager::{PaymentPreimage, PaymentHash};
1515 use util::ser::Writeable;
1517 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1518 use bitcoin_hashes::hex::FromHex;
1519 use bitcoin::util::address::Address;
1520 use bitcoin::network::constants::Network;
1521 use bitcoin::blockdata::script::Builder;
1522 use bitcoin::blockdata::opcodes;
1524 use secp256k1::key::{PublicKey,SecretKey};
1525 use secp256k1::{Secp256k1, Message};
1527 use std::marker::PhantomData;
1530 fn encoding_channel_reestablish_no_secret() {
1531 let cr = msgs::ChannelReestablish {
1532 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],
1533 next_local_commitment_number: 3,
1534 next_remote_commitment_number: 4,
1535 data_loss_protect: OptionalField::Absent,
1538 let encoded_value = cr.encode();
1541 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]
1546 fn encoding_channel_reestablish_with_secret() {
1548 let secp_ctx = Secp256k1::new();
1549 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1552 let cr = msgs::ChannelReestablish {
1553 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],
1554 next_local_commitment_number: 3,
1555 next_remote_commitment_number: 4,
1556 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1559 let encoded_value = cr.encode();
1562 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]
1566 macro_rules! get_keys_from {
1567 ($slice: expr, $secp_ctx: expr) => {
1569 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1570 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1576 macro_rules! get_sig_on {
1577 ($privkey: expr, $ctx: expr, $string: expr) => {
1579 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1580 $ctx.sign(&sighash, &$privkey)
1586 fn encoding_announcement_signatures() {
1587 let secp_ctx = Secp256k1::new();
1588 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1589 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1590 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1591 let announcement_signatures = msgs::AnnouncementSignatures {
1592 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],
1593 short_channel_id: 2316138423780173,
1594 node_signature: sig_1,
1595 bitcoin_signature: sig_2,
1598 let encoded_value = announcement_signatures.encode();
1599 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1602 fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
1603 let secp_ctx = Secp256k1::new();
1604 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1605 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1606 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1607 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1608 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1609 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1610 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1611 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1612 let mut features = ChannelFeatures::new();
1613 if unknown_features_bits {
1614 features.flags = vec![0xFF, 0xFF];
1616 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1618 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1619 short_channel_id: 2316138423780173,
1620 node_id_1: pubkey_1,
1621 node_id_2: pubkey_2,
1622 bitcoin_key_1: pubkey_3,
1623 bitcoin_key_2: pubkey_4,
1624 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1626 let channel_announcement = msgs::ChannelAnnouncement {
1627 node_signature_1: sig_1,
1628 node_signature_2: sig_2,
1629 bitcoin_signature_1: sig_3,
1630 bitcoin_signature_2: sig_4,
1631 contents: unsigned_channel_announcement,
1633 let encoded_value = channel_announcement.encode();
1634 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1635 if unknown_features_bits {
1636 target_value.append(&mut hex::decode("0002ffff").unwrap());
1638 target_value.append(&mut hex::decode("0000").unwrap());
1640 if non_bitcoin_chain_hash {
1641 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1643 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1645 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1647 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1649 assert_eq!(encoded_value, target_value);
1653 fn encoding_channel_announcement() {
1654 do_encoding_channel_announcement(false, false, false);
1655 do_encoding_channel_announcement(true, false, false);
1656 do_encoding_channel_announcement(true, true, false);
1657 do_encoding_channel_announcement(true, true, true);
1658 do_encoding_channel_announcement(false, true, true);
1659 do_encoding_channel_announcement(false, false, true);
1660 do_encoding_channel_announcement(false, true, false);
1661 do_encoding_channel_announcement(true, false, true);
1664 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1665 let secp_ctx = Secp256k1::new();
1666 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1667 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1668 let mut features = NodeFeatures::new();
1669 if unknown_features_bits {
1670 features.flags = vec![0xFF, 0xFF];
1672 let mut addresses = Vec::new();
1674 addresses.push(msgs::NetAddress::IPv4 {
1675 addr: [255, 254, 253, 252],
1680 addresses.push(msgs::NetAddress::IPv6 {
1681 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1686 addresses.push(msgs::NetAddress::OnionV2 {
1687 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1692 addresses.push(msgs::NetAddress::OnionV3 {
1693 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],
1699 let mut addr_len = 0;
1700 for addr in &addresses {
1701 addr_len += addr.len() + 1;
1703 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1705 timestamp: 20190119,
1710 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() },
1711 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() },
1713 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1714 let node_announcement = msgs::NodeAnnouncement {
1716 contents: unsigned_node_announcement,
1718 let encoded_value = node_announcement.encode();
1719 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1720 if unknown_features_bits {
1721 target_value.append(&mut hex::decode("0002ffff").unwrap());
1723 target_value.append(&mut hex::decode("000122").unwrap());
1725 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1726 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1728 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1731 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1734 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1737 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1739 if excess_address_data {
1740 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1743 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1745 assert_eq!(encoded_value, target_value);
1749 fn encoding_node_announcement() {
1750 do_encoding_node_announcement(true, true, true, true, true, true, true);
1751 do_encoding_node_announcement(false, false, false, false, false, false, false);
1752 do_encoding_node_announcement(false, true, false, false, false, false, false);
1753 do_encoding_node_announcement(false, false, true, false, false, false, false);
1754 do_encoding_node_announcement(false, false, false, true, false, false, false);
1755 do_encoding_node_announcement(false, false, false, false, true, false, false);
1756 do_encoding_node_announcement(false, false, false, false, false, true, false);
1757 do_encoding_node_announcement(false, true, false, true, false, true, false);
1758 do_encoding_node_announcement(false, false, true, false, true, false, false);
1761 fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
1762 let secp_ctx = Secp256k1::new();
1763 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1764 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1765 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1766 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1767 short_channel_id: 2316138423780173,
1768 timestamp: 20190119,
1769 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
1770 cltv_expiry_delta: 144,
1771 htlc_minimum_msat: 1000000,
1772 fee_base_msat: 10000,
1773 fee_proportional_millionths: 20,
1774 excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1776 let channel_update = msgs::ChannelUpdate {
1778 contents: unsigned_channel_update
1780 let encoded_value = channel_update.encode();
1781 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1782 if non_bitcoin_chain_hash {
1783 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1785 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1787 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1788 if htlc_maximum_msat {
1789 target_value.append(&mut hex::decode("01").unwrap());
1791 target_value.append(&mut hex::decode("00").unwrap());
1793 target_value.append(&mut hex::decode("00").unwrap());
1795 let flag = target_value.last_mut().unwrap();
1799 let flag = target_value.last_mut().unwrap();
1800 *flag = *flag | 1 << 1;
1802 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1803 if htlc_maximum_msat {
1804 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1806 assert_eq!(encoded_value, target_value);
1810 fn encoding_channel_update() {
1811 do_encoding_channel_update(false, false, false, false);
1812 do_encoding_channel_update(true, false, false, false);
1813 do_encoding_channel_update(false, true, false, false);
1814 do_encoding_channel_update(false, false, true, false);
1815 do_encoding_channel_update(false, false, false, true);
1816 do_encoding_channel_update(true, true, true, true);
1819 fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
1820 let secp_ctx = Secp256k1::new();
1821 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1822 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1823 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1824 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1825 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1826 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1827 let open_channel = msgs::OpenChannel {
1828 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1829 temporary_channel_id: [2; 32],
1830 funding_satoshis: 1311768467284833366,
1831 push_msat: 2536655962884945560,
1832 dust_limit_satoshis: 3608586615801332854,
1833 max_htlc_value_in_flight_msat: 8517154655701053848,
1834 channel_reserve_satoshis: 8665828695742877976,
1835 htlc_minimum_msat: 2316138423780173,
1836 feerate_per_kw: 821716,
1837 to_self_delay: 49340,
1838 max_accepted_htlcs: 49340,
1839 funding_pubkey: pubkey_1,
1840 revocation_basepoint: pubkey_2,
1841 payment_basepoint: pubkey_3,
1842 delayed_payment_basepoint: pubkey_4,
1843 htlc_basepoint: pubkey_5,
1844 first_per_commitment_point: pubkey_6,
1845 channel_flags: if random_bit { 1 << 5 } else { 0 },
1846 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1848 let encoded_value = open_channel.encode();
1849 let mut target_value = Vec::new();
1850 if non_bitcoin_chain_hash {
1851 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1853 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1855 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1857 target_value.append(&mut hex::decode("20").unwrap());
1859 target_value.append(&mut hex::decode("00").unwrap());
1862 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1864 assert_eq!(encoded_value, target_value);
1868 fn encoding_open_channel() {
1869 do_encoding_open_channel(false, false, false);
1870 do_encoding_open_channel(true, false, false);
1871 do_encoding_open_channel(false, true, false);
1872 do_encoding_open_channel(false, false, true);
1873 do_encoding_open_channel(true, true, true);
1876 fn do_encoding_accept_channel(shutdown: bool) {
1877 let secp_ctx = Secp256k1::new();
1878 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1879 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1880 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1881 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1882 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1883 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1884 let accept_channel = msgs::AcceptChannel {
1885 temporary_channel_id: [2; 32],
1886 dust_limit_satoshis: 1311768467284833366,
1887 max_htlc_value_in_flight_msat: 2536655962884945560,
1888 channel_reserve_satoshis: 3608586615801332854,
1889 htlc_minimum_msat: 2316138423780173,
1890 minimum_depth: 821716,
1891 to_self_delay: 49340,
1892 max_accepted_htlcs: 49340,
1893 funding_pubkey: pubkey_1,
1894 revocation_basepoint: pubkey_2,
1895 payment_basepoint: pubkey_3,
1896 delayed_payment_basepoint: pubkey_4,
1897 htlc_basepoint: pubkey_5,
1898 first_per_commitment_point: pubkey_6,
1899 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1901 let encoded_value = accept_channel.encode();
1902 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1904 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1906 assert_eq!(encoded_value, target_value);
1910 fn encoding_accept_channel() {
1911 do_encoding_accept_channel(false);
1912 do_encoding_accept_channel(true);
1916 fn encoding_funding_created() {
1917 let secp_ctx = Secp256k1::new();
1918 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1919 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1920 let funding_created = msgs::FundingCreated {
1921 temporary_channel_id: [2; 32],
1922 funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1923 funding_output_index: 255,
1926 let encoded_value = funding_created.encode();
1927 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1928 assert_eq!(encoded_value, target_value);
1932 fn encoding_funding_signed() {
1933 let secp_ctx = Secp256k1::new();
1934 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1935 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1936 let funding_signed = msgs::FundingSigned {
1937 channel_id: [2; 32],
1940 let encoded_value = funding_signed.encode();
1941 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1942 assert_eq!(encoded_value, target_value);
1946 fn encoding_funding_locked() {
1947 let secp_ctx = Secp256k1::new();
1948 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1949 let funding_locked = msgs::FundingLocked {
1950 channel_id: [2; 32],
1951 next_per_commitment_point: pubkey_1,
1953 let encoded_value = funding_locked.encode();
1954 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1955 assert_eq!(encoded_value, target_value);
1958 fn do_encoding_shutdown(script_type: u8) {
1959 let secp_ctx = Secp256k1::new();
1960 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1961 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1962 let shutdown = msgs::Shutdown {
1963 channel_id: [2; 32],
1964 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() },
1966 let encoded_value = shutdown.encode();
1967 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1968 if script_type == 1 {
1969 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1970 } else if script_type == 2 {
1971 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1972 } else if script_type == 3 {
1973 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1974 } else if script_type == 4 {
1975 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1977 assert_eq!(encoded_value, target_value);
1981 fn encoding_shutdown() {
1982 do_encoding_shutdown(1);
1983 do_encoding_shutdown(2);
1984 do_encoding_shutdown(3);
1985 do_encoding_shutdown(4);
1989 fn encoding_closing_signed() {
1990 let secp_ctx = Secp256k1::new();
1991 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1992 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1993 let closing_signed = msgs::ClosingSigned {
1994 channel_id: [2; 32],
1995 fee_satoshis: 2316138423780173,
1998 let encoded_value = closing_signed.encode();
1999 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2000 assert_eq!(encoded_value, target_value);
2004 fn encoding_update_add_htlc() {
2005 let secp_ctx = Secp256k1::new();
2006 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2007 let onion_routing_packet = msgs::OnionPacket {
2009 public_key: Ok(pubkey_1),
2010 hop_data: [1; 20*65],
2013 let update_add_htlc = msgs::UpdateAddHTLC {
2014 channel_id: [2; 32],
2015 htlc_id: 2316138423780173,
2016 amount_msat: 3608586615801332854,
2017 payment_hash: PaymentHash([1; 32]),
2018 cltv_expiry: 821716,
2019 onion_routing_packet
2021 let encoded_value = update_add_htlc.encode();
2022 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
2023 assert_eq!(encoded_value, target_value);
2027 fn encoding_update_fulfill_htlc() {
2028 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
2029 channel_id: [2; 32],
2030 htlc_id: 2316138423780173,
2031 payment_preimage: PaymentPreimage([1; 32]),
2033 let encoded_value = update_fulfill_htlc.encode();
2034 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
2035 assert_eq!(encoded_value, target_value);
2039 fn encoding_update_fail_htlc() {
2040 let reason = OnionErrorPacket {
2041 data: [1; 32].to_vec(),
2043 let update_fail_htlc = msgs::UpdateFailHTLC {
2044 channel_id: [2; 32],
2045 htlc_id: 2316138423780173,
2048 let encoded_value = update_fail_htlc.encode();
2049 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
2050 assert_eq!(encoded_value, target_value);
2054 fn encoding_update_fail_malformed_htlc() {
2055 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
2056 channel_id: [2; 32],
2057 htlc_id: 2316138423780173,
2058 sha256_of_onion: [1; 32],
2061 let encoded_value = update_fail_malformed_htlc.encode();
2062 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
2063 assert_eq!(encoded_value, target_value);
2066 fn do_encoding_commitment_signed(htlcs: bool) {
2067 let secp_ctx = Secp256k1::new();
2068 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2069 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2070 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2071 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2072 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2073 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2074 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2075 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2076 let commitment_signed = msgs::CommitmentSigned {
2077 channel_id: [2; 32],
2079 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
2081 let encoded_value = commitment_signed.encode();
2082 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2084 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2086 target_value.append(&mut hex::decode("0000").unwrap());
2088 assert_eq!(encoded_value, target_value);
2092 fn encoding_commitment_signed() {
2093 do_encoding_commitment_signed(true);
2094 do_encoding_commitment_signed(false);
2098 fn encoding_revoke_and_ack() {
2099 let secp_ctx = Secp256k1::new();
2100 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2101 let raa = msgs::RevokeAndACK {
2102 channel_id: [2; 32],
2103 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],
2104 next_per_commitment_point: pubkey_1,
2106 let encoded_value = raa.encode();
2107 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2108 assert_eq!(encoded_value, target_value);
2112 fn encoding_update_fee() {
2113 let update_fee = msgs::UpdateFee {
2114 channel_id: [2; 32],
2115 feerate_per_kw: 20190119,
2117 let encoded_value = update_fee.encode();
2118 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2119 assert_eq!(encoded_value, target_value);
2123 fn encoding_init() {
2124 assert_eq!(msgs::Init {
2125 features: InitFeatures {
2126 flags: vec![0xFF, 0xFF, 0xFF],
2129 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2130 assert_eq!(msgs::Init {
2131 features: InitFeatures {
2135 }.encode(), hex::decode("0001ff0001ff").unwrap());
2136 assert_eq!(msgs::Init {
2137 features: InitFeatures {
2141 }.encode(), hex::decode("00000000").unwrap());
2145 fn encoding_error() {
2146 let error = msgs::ErrorMessage {
2147 channel_id: [2; 32],
2148 data: String::from("rust-lightning"),
2150 let encoded_value = error.encode();
2151 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2152 assert_eq!(encoded_value, target_value);
2156 fn encoding_ping() {
2157 let ping = msgs::Ping {
2161 let encoded_value = ping.encode();
2162 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2163 assert_eq!(encoded_value, target_value);
2167 fn encoding_pong() {
2168 let pong = msgs::Pong {
2171 let encoded_value = pong.encode();
2172 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2173 assert_eq!(encoded_value, target_value);