1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Wire messages, traits representing wire message handlers, and a few error types live here.
12 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
13 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
14 //! server entirely) which handles only channel-related messages you may wish to implement
15 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
18 //! Note that if you go with such an architecture (instead of passing raw socket events to a
19 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
20 //! source node_id of the message, however this does allow you to significantly reduce bandwidth
21 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
22 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
23 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
24 //! raw socket events into your non-internet-facing system and then send routing events back to
25 //! track the network on the less-secure system.
27 use bitcoin::secp256k1::key::PublicKey;
28 use bitcoin::secp256k1::Signature;
29 use bitcoin::secp256k1;
30 use bitcoin::blockdata::script::Script;
31 use bitcoin::hash_types::{Txid, BlockHash};
33 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
39 use io_extras::read_to_end;
41 use util::events::MessageSendEventsProvider;
43 use util::ser::{Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt};
45 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
47 /// 21 million * 10^8 * 1000
48 pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
50 /// An error in decoding a message or struct.
51 #[derive(Clone, Debug, PartialEq)]
52 pub enum DecodeError {
53 /// A version byte specified something we don't know how to handle.
54 /// Includes unknown realm byte in an OnionHopData packet
56 /// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type)
57 UnknownRequiredFeature,
58 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
59 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was
60 /// syntactically incorrect, etc
64 /// A length descriptor in the packet didn't describe the later data correctly
66 /// Error from std::io
67 Io(/// (C-not exported) as ErrorKind doesn't have a reasonable mapping
69 /// The message included zlib-compressed values, which we don't support.
70 UnsupportedCompression,
73 /// An init message to be sent or received from a peer
74 #[derive(Clone, Debug, PartialEq)]
76 /// The relevant features which the sender supports
77 pub features: InitFeatures,
80 /// An error message to be sent or received from a peer
81 #[derive(Clone, Debug, PartialEq)]
82 pub struct ErrorMessage {
83 /// The channel ID involved in the error
84 pub channel_id: [u8; 32],
85 /// A possibly human-readable error description.
86 /// The string should be sanitized before it is used (e.g. emitted to logs
87 /// or printed to stdout). Otherwise, a well crafted error message may trigger a security
88 /// vulnerability in the terminal emulator or the logging subsystem.
92 /// A ping message to be sent or received from a peer
93 #[derive(Clone, Debug, PartialEq)]
95 /// The desired response length
97 /// The ping packet size.
98 /// This field is not sent on the wire. byteslen zeros are sent.
102 /// A pong message to be sent or received from a peer
103 #[derive(Clone, Debug, PartialEq)]
105 /// The pong packet size.
106 /// This field is not sent on the wire. byteslen zeros are sent.
110 /// An open_channel message to be sent or received from a peer
111 #[derive(Clone, Debug, PartialEq)]
112 pub struct OpenChannel {
113 /// The genesis hash of the blockchain where the channel is to be opened
114 pub chain_hash: BlockHash,
115 /// A temporary channel ID, until the funding outpoint is announced
116 pub temporary_channel_id: [u8; 32],
117 /// The channel value
118 pub funding_satoshis: u64,
119 /// The amount to push to the counterparty as part of the open, in milli-satoshi
121 /// The threshold below which outputs on transactions broadcast by sender will be omitted
122 pub dust_limit_satoshis: u64,
123 /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
124 pub max_htlc_value_in_flight_msat: u64,
125 /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
126 pub channel_reserve_satoshis: u64,
127 /// The minimum HTLC size incoming to sender, in milli-satoshi
128 pub htlc_minimum_msat: u64,
129 /// The feerate per 1000-weight of sender generated transactions, until updated by update_fee
130 pub feerate_per_kw: u32,
131 /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
132 pub to_self_delay: u16,
133 /// The maximum number of inbound HTLCs towards sender
134 pub max_accepted_htlcs: u16,
135 /// The sender's key controlling the funding transaction
136 pub funding_pubkey: PublicKey,
137 /// Used to derive a revocation key for transactions broadcast by counterparty
138 pub revocation_basepoint: PublicKey,
139 /// A payment key to sender for transactions broadcast by counterparty
140 pub payment_point: PublicKey,
141 /// Used to derive a payment key to sender for transactions broadcast by sender
142 pub delayed_payment_basepoint: PublicKey,
143 /// Used to derive an HTLC payment key to sender
144 pub htlc_basepoint: PublicKey,
145 /// The first to-be-broadcast-by-sender transaction's per commitment point
146 pub first_per_commitment_point: PublicKey,
148 pub channel_flags: u8,
149 /// Optionally, a request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
150 pub shutdown_scriptpubkey: OptionalField<Script>,
153 /// An accept_channel message to be sent or received from a peer
154 #[derive(Clone, Debug, PartialEq)]
155 pub struct AcceptChannel {
156 /// A temporary channel ID, until the funding outpoint is announced
157 pub temporary_channel_id: [u8; 32],
158 /// The threshold below which outputs on transactions broadcast by sender will be omitted
159 pub dust_limit_satoshis: u64,
160 /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
161 pub max_htlc_value_in_flight_msat: u64,
162 /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
163 pub channel_reserve_satoshis: u64,
164 /// The minimum HTLC size incoming to sender, in milli-satoshi
165 pub htlc_minimum_msat: u64,
166 /// Minimum depth of the funding transaction before the channel is considered open
167 pub minimum_depth: u32,
168 /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
169 pub to_self_delay: u16,
170 /// The maximum number of inbound HTLCs towards sender
171 pub max_accepted_htlcs: u16,
172 /// The sender's key controlling the funding transaction
173 pub funding_pubkey: PublicKey,
174 /// Used to derive a revocation key for transactions broadcast by counterparty
175 pub revocation_basepoint: PublicKey,
176 /// A payment key to sender for transactions broadcast by counterparty
177 pub payment_point: PublicKey,
178 /// Used to derive a payment key to sender for transactions broadcast by sender
179 pub delayed_payment_basepoint: PublicKey,
180 /// Used to derive an HTLC payment key to sender for transactions broadcast by counterparty
181 pub htlc_basepoint: PublicKey,
182 /// The first to-be-broadcast-by-sender transaction's per commitment point
183 pub first_per_commitment_point: PublicKey,
184 /// Optionally, a request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
185 pub shutdown_scriptpubkey: OptionalField<Script>,
188 /// A funding_created message to be sent or received from a peer
189 #[derive(Clone, Debug, PartialEq)]
190 pub struct FundingCreated {
191 /// A temporary channel ID, until the funding is established
192 pub temporary_channel_id: [u8; 32],
193 /// The funding transaction ID
194 pub funding_txid: Txid,
195 /// The specific output index funding this channel
196 pub funding_output_index: u16,
197 /// The signature of the channel initiator (funder) on the funding transaction
198 pub signature: Signature,
201 /// A funding_signed message to be sent or received from a peer
202 #[derive(Clone, Debug, PartialEq)]
203 pub struct FundingSigned {
205 pub channel_id: [u8; 32],
206 /// The signature of the channel acceptor (fundee) on the funding transaction
207 pub signature: Signature,
210 /// A funding_locked message to be sent or received from a peer
211 #[derive(Clone, Debug, PartialEq)]
212 pub struct FundingLocked {
214 pub channel_id: [u8; 32],
215 /// The per-commitment point of the second commitment transaction
216 pub next_per_commitment_point: PublicKey,
219 /// A shutdown message to be sent or received from a peer
220 #[derive(Clone, Debug, PartialEq)]
221 pub struct Shutdown {
223 pub channel_id: [u8; 32],
224 /// The destination of this peer's funds on closing.
225 /// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh.
226 pub scriptpubkey: Script,
229 /// A closing_signed message to be sent or received from a peer
230 #[derive(Clone, Debug, PartialEq)]
231 pub struct ClosingSigned {
233 pub channel_id: [u8; 32],
234 /// The proposed total fee for the closing transaction
235 pub fee_satoshis: u64,
236 /// A signature on the closing transaction
237 pub signature: Signature,
240 /// An update_add_htlc message to be sent or received from a peer
241 #[derive(Clone, Debug, PartialEq)]
242 pub struct UpdateAddHTLC {
244 pub channel_id: [u8; 32],
247 /// The HTLC value in milli-satoshi
248 pub amount_msat: u64,
249 /// The payment hash, the pre-image of which controls HTLC redemption
250 pub payment_hash: PaymentHash,
251 /// The expiry height of the HTLC
252 pub cltv_expiry: u32,
253 pub(crate) onion_routing_packet: OnionPacket,
256 /// An update_fulfill_htlc message to be sent or received from a peer
257 #[derive(Clone, Debug, PartialEq)]
258 pub struct UpdateFulfillHTLC {
260 pub channel_id: [u8; 32],
263 /// The pre-image of the payment hash, allowing HTLC redemption
264 pub payment_preimage: PaymentPreimage,
267 /// An update_fail_htlc message to be sent or received from a peer
268 #[derive(Clone, Debug, PartialEq)]
269 pub struct UpdateFailHTLC {
271 pub channel_id: [u8; 32],
274 pub(crate) reason: OnionErrorPacket,
277 /// An update_fail_malformed_htlc message to be sent or received from a peer
278 #[derive(Clone, Debug, PartialEq)]
279 pub struct UpdateFailMalformedHTLC {
281 pub channel_id: [u8; 32],
284 pub(crate) sha256_of_onion: [u8; 32],
286 pub failure_code: u16,
289 /// A commitment_signed message to be sent or received from a peer
290 #[derive(Clone, Debug, PartialEq)]
291 pub struct CommitmentSigned {
293 pub channel_id: [u8; 32],
294 /// A signature on the commitment transaction
295 pub signature: Signature,
296 /// Signatures on the HTLC transactions
297 pub htlc_signatures: Vec<Signature>,
300 /// A revoke_and_ack message to be sent or received from a peer
301 #[derive(Clone, Debug, PartialEq)]
302 pub struct RevokeAndACK {
304 pub channel_id: [u8; 32],
305 /// The secret corresponding to the per-commitment point
306 pub per_commitment_secret: [u8; 32],
307 /// The next sender-broadcast commitment transaction's per-commitment point
308 pub next_per_commitment_point: PublicKey,
311 /// An update_fee message to be sent or received from a peer
312 #[derive(Clone, Debug, PartialEq)]
313 pub struct UpdateFee {
315 pub channel_id: [u8; 32],
316 /// Fee rate per 1000-weight of the transaction
317 pub feerate_per_kw: u32,
320 #[derive(Clone, Debug, PartialEq)]
321 /// Proof that the sender knows the per-commitment secret of the previous commitment transaction.
322 /// This is used to convince the recipient that the channel is at a certain commitment
323 /// number even if they lost that data due to a local failure. Of course, the peer may lie
324 /// and even later commitments may have been revoked.
325 pub struct DataLossProtect {
326 /// Proof that the sender knows the per-commitment secret of a specific commitment transaction
327 /// belonging to the recipient
328 pub your_last_per_commitment_secret: [u8; 32],
329 /// The sender's per-commitment point for their current commitment transaction
330 pub my_current_per_commitment_point: PublicKey,
333 /// A channel_reestablish message to be sent or received from a peer
334 #[derive(Clone, Debug, PartialEq)]
335 pub struct ChannelReestablish {
337 pub channel_id: [u8; 32],
338 /// The next commitment number for the sender
339 pub next_local_commitment_number: u64,
340 /// The next commitment number for the recipient
341 pub next_remote_commitment_number: u64,
342 /// Optionally, a field proving that next_remote_commitment_number-1 has been revoked
343 pub data_loss_protect: OptionalField<DataLossProtect>,
346 /// An announcement_signatures message to be sent or received from a peer
347 #[derive(Clone, Debug, PartialEq)]
348 pub struct AnnouncementSignatures {
350 pub channel_id: [u8; 32],
351 /// The short channel ID
352 pub short_channel_id: u64,
353 /// A signature by the node key
354 pub node_signature: Signature,
355 /// A signature by the funding key
356 pub bitcoin_signature: Signature,
359 /// An address which can be used to connect to a remote peer
360 #[derive(Clone, Debug, PartialEq)]
361 pub enum NetAddress {
362 /// An IPv4 address/port on which the peer is listening.
364 /// The 4-byte IPv4 address
366 /// The port on which the node is listening
369 /// An IPv6 address/port on which the peer is listening.
371 /// The 16-byte IPv6 address
373 /// The port on which the node is listening
376 /// An old-style Tor onion address/port on which the peer is listening.
378 /// The bytes (usually encoded in base32 with ".onion" appended)
380 /// The port on which the node is listening
383 /// A new-style Tor onion address/port on which the peer is listening.
384 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
385 /// wrap as base32 and append ".onion".
387 /// The ed25519 long-term public key of the peer
388 ed25519_pubkey: [u8; 32],
389 /// The checksum of the pubkey and version, as included in the onion address
391 /// The version byte, as defined by the Tor Onion v3 spec.
393 /// The port on which the node is listening
398 /// Gets the ID of this address type. Addresses in node_announcement messages should be sorted
400 pub(crate) fn get_id(&self) -> u8 {
402 &NetAddress::IPv4 {..} => { 1 },
403 &NetAddress::IPv6 {..} => { 2 },
404 &NetAddress::OnionV2 {..} => { 3 },
405 &NetAddress::OnionV3 {..} => { 4 },
409 /// Strict byte-length of address descriptor, 1-byte type not recorded
410 fn len(&self) -> u16 {
412 &NetAddress::IPv4 { .. } => { 6 },
413 &NetAddress::IPv6 { .. } => { 18 },
414 &NetAddress::OnionV2 { .. } => { 12 },
415 &NetAddress::OnionV3 { .. } => { 37 },
419 /// The maximum length of any address descriptor, not including the 1-byte type
420 pub(crate) const MAX_LEN: u16 = 37;
423 impl Writeable for NetAddress {
424 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
426 &NetAddress::IPv4 { ref addr, ref port } => {
431 &NetAddress::IPv6 { ref addr, ref port } => {
436 &NetAddress::OnionV2 { ref addr, ref port } => {
441 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
443 ed25519_pubkey.write(writer)?;
444 checksum.write(writer)?;
445 version.write(writer)?;
453 impl Readable for Result<NetAddress, u8> {
454 fn read<R: Read>(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
455 let byte = <u8 as Readable>::read(reader)?;
458 Ok(Ok(NetAddress::IPv4 {
459 addr: Readable::read(reader)?,
460 port: Readable::read(reader)?,
464 Ok(Ok(NetAddress::IPv6 {
465 addr: Readable::read(reader)?,
466 port: Readable::read(reader)?,
470 Ok(Ok(NetAddress::OnionV2 {
471 addr: Readable::read(reader)?,
472 port: Readable::read(reader)?,
476 Ok(Ok(NetAddress::OnionV3 {
477 ed25519_pubkey: Readable::read(reader)?,
478 checksum: Readable::read(reader)?,
479 version: Readable::read(reader)?,
480 port: Readable::read(reader)?,
483 _ => return Ok(Err(byte)),
488 impl Readable for NetAddress {
489 fn read<R: Read>(reader: &mut R) -> Result<NetAddress, DecodeError> {
490 match Readable::read(reader) {
491 Ok(Ok(res)) => Ok(res),
492 Ok(Err(_)) => Err(DecodeError::UnknownVersion),
499 /// The unsigned part of a node_announcement
500 #[derive(Clone, Debug, PartialEq)]
501 pub struct UnsignedNodeAnnouncement {
502 /// The advertised features
503 pub features: NodeFeatures,
504 /// A strictly monotonic announcement counter, with gaps allowed
506 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
508 pub node_id: PublicKey,
509 /// An RGB color for UI purposes
511 /// An alias, for UI purposes. This should be sanitized before use. There is no guarantee
514 /// List of addresses on which this node is reachable
515 pub addresses: Vec<NetAddress>,
516 pub(crate) excess_address_data: Vec<u8>,
517 pub(crate) excess_data: Vec<u8>,
519 #[derive(Clone, Debug, PartialEq)]
520 /// A node_announcement message to be sent or received from a peer
521 pub struct NodeAnnouncement {
522 /// The signature by the node key
523 pub signature: Signature,
524 /// The actual content of the announcement
525 pub contents: UnsignedNodeAnnouncement,
528 /// The unsigned part of a channel_announcement
529 #[derive(Clone, Debug, PartialEq)]
530 pub struct UnsignedChannelAnnouncement {
531 /// The advertised channel features
532 pub features: ChannelFeatures,
533 /// The genesis hash of the blockchain where the channel is to be opened
534 pub chain_hash: BlockHash,
535 /// The short channel ID
536 pub short_channel_id: u64,
537 /// One of the two node_ids which are endpoints of this channel
538 pub node_id_1: PublicKey,
539 /// The other of the two node_ids which are endpoints of this channel
540 pub node_id_2: PublicKey,
541 /// The funding key for the first node
542 pub bitcoin_key_1: PublicKey,
543 /// The funding key for the second node
544 pub bitcoin_key_2: PublicKey,
545 pub(crate) excess_data: Vec<u8>,
547 /// A channel_announcement message to be sent or received from a peer
548 #[derive(Clone, Debug, PartialEq)]
549 pub struct ChannelAnnouncement {
550 /// Authentication of the announcement by the first public node
551 pub node_signature_1: Signature,
552 /// Authentication of the announcement by the second public node
553 pub node_signature_2: Signature,
554 /// Proof of funding UTXO ownership by the first public node
555 pub bitcoin_signature_1: Signature,
556 /// Proof of funding UTXO ownership by the second public node
557 pub bitcoin_signature_2: Signature,
558 /// The actual announcement
559 pub contents: UnsignedChannelAnnouncement,
562 /// The unsigned part of a channel_update
563 #[derive(Clone, Debug, PartialEq)]
564 pub struct UnsignedChannelUpdate {
565 /// The genesis hash of the blockchain where the channel is to be opened
566 pub chain_hash: BlockHash,
567 /// The short channel ID
568 pub short_channel_id: u64,
569 /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel
573 /// The number of blocks such that if:
574 /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta`
575 /// then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines
576 /// the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a
577 /// cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10,
578 /// then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before
579 /// forwarding. Note that the HTLC sender is the one who originally sets this value when
580 /// constructing the route.
581 pub cltv_expiry_delta: u16,
582 /// The minimum HTLC size incoming to sender, in milli-satoshi
583 pub htlc_minimum_msat: u64,
584 /// Optionally, the maximum HTLC value incoming to sender, in milli-satoshi
585 pub htlc_maximum_msat: OptionalField<u64>,
586 /// The base HTLC fee charged by sender, in milli-satoshi
587 pub fee_base_msat: u32,
588 /// The amount to fee multiplier, in micro-satoshi
589 pub fee_proportional_millionths: u32,
590 pub(crate) excess_data: Vec<u8>,
592 /// A channel_update message to be sent or received from a peer
593 #[derive(Clone, Debug, PartialEq)]
594 pub struct ChannelUpdate {
595 /// A signature of the channel update
596 pub signature: Signature,
597 /// The actual channel update
598 pub contents: UnsignedChannelUpdate,
601 /// A query_channel_range message is used to query a peer for channel
602 /// UTXOs in a range of blocks. The recipient of a query makes a best
603 /// effort to reply to the query using one or more reply_channel_range
605 #[derive(Clone, Debug, PartialEq)]
606 pub struct QueryChannelRange {
607 /// The genesis hash of the blockchain being queried
608 pub chain_hash: BlockHash,
609 /// The height of the first block for the channel UTXOs being queried
610 pub first_blocknum: u32,
611 /// The number of blocks to include in the query results
612 pub number_of_blocks: u32,
615 /// A reply_channel_range message is a reply to a query_channel_range
616 /// message. Multiple reply_channel_range messages can be sent in reply
617 /// to a single query_channel_range message. The query recipient makes a
618 /// best effort to respond based on their local network view which may
619 /// not be a perfect view of the network. The short_channel_ids in the
620 /// reply are encoded. We only support encoding_type=0 uncompressed
621 /// serialization and do not support encoding_type=1 zlib serialization.
622 #[derive(Clone, Debug, PartialEq)]
623 pub struct ReplyChannelRange {
624 /// The genesis hash of the blockchain being queried
625 pub chain_hash: BlockHash,
626 /// The height of the first block in the range of the reply
627 pub first_blocknum: u32,
628 /// The number of blocks included in the range of the reply
629 pub number_of_blocks: u32,
630 /// True when this is the final reply for a query
631 pub sync_complete: bool,
632 /// The short_channel_ids in the channel range
633 pub short_channel_ids: Vec<u64>,
636 /// A query_short_channel_ids message is used to query a peer for
637 /// routing gossip messages related to one or more short_channel_ids.
638 /// The query recipient will reply with the latest, if available,
639 /// channel_announcement, channel_update and node_announcement messages
640 /// it maintains for the requested short_channel_ids followed by a
641 /// reply_short_channel_ids_end message. The short_channel_ids sent in
642 /// this query are encoded. We only support encoding_type=0 uncompressed
643 /// serialization and do not support encoding_type=1 zlib serialization.
644 #[derive(Clone, Debug, PartialEq)]
645 pub struct QueryShortChannelIds {
646 /// The genesis hash of the blockchain being queried
647 pub chain_hash: BlockHash,
648 /// The short_channel_ids that are being queried
649 pub short_channel_ids: Vec<u64>,
652 /// A reply_short_channel_ids_end message is sent as a reply to a
653 /// query_short_channel_ids message. The query recipient makes a best
654 /// effort to respond based on their local network view which may not be
655 /// a perfect view of the network.
656 #[derive(Clone, Debug, PartialEq)]
657 pub struct ReplyShortChannelIdsEnd {
658 /// The genesis hash of the blockchain that was queried
659 pub chain_hash: BlockHash,
660 /// Indicates if the query recipient maintains up-to-date channel
661 /// information for the chain_hash
662 pub full_information: bool,
665 /// A gossip_timestamp_filter message is used by a node to request
666 /// gossip relay for messages in the requested time range when the
667 /// gossip_queries feature has been negotiated.
668 #[derive(Clone, Debug, PartialEq)]
669 pub struct GossipTimestampFilter {
670 /// The genesis hash of the blockchain for channel and node information
671 pub chain_hash: BlockHash,
672 /// The starting unix timestamp
673 pub first_timestamp: u32,
674 /// The range of information in seconds
675 pub timestamp_range: u32,
678 /// Encoding type for data compression of collections in gossip queries.
679 /// We do not support encoding_type=1 zlib serialization defined in BOLT #7.
684 /// Used to put an error message in a LightningError
685 #[derive(Clone, Debug)]
686 pub enum ErrorAction {
687 /// The peer took some action which made us think they were useless. Disconnect them.
689 /// An error message which we should make an effort to send before we disconnect.
690 msg: Option<ErrorMessage>
692 /// The peer did something harmless that we weren't able to process, just log and ignore
693 // New code should *not* use this. New code must use IgnoreAndLog, below!
695 /// The peer did something harmless that we weren't able to meaningfully process.
696 /// If the error is logged, log it at the given level.
697 IgnoreAndLog(logger::Level),
698 /// The peer did something incorrect. Tell them.
700 /// The message to send.
705 /// An Err type for failure to process messages.
706 #[derive(Clone, Debug)]
707 pub struct LightningError {
708 /// A human-readable message describing the error
710 /// The action which should be taken against the offending peer.
711 pub action: ErrorAction,
714 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
715 /// transaction updates if they were pending.
716 #[derive(Clone, Debug, PartialEq)]
717 pub struct CommitmentUpdate {
718 /// update_add_htlc messages which should be sent
719 pub update_add_htlcs: Vec<UpdateAddHTLC>,
720 /// update_fulfill_htlc messages which should be sent
721 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
722 /// update_fail_htlc messages which should be sent
723 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
724 /// update_fail_malformed_htlc messages which should be sent
725 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
726 /// An update_fee message which should be sent
727 pub update_fee: Option<UpdateFee>,
728 /// Finally, the commitment_signed message which should be sent
729 pub commitment_signed: CommitmentSigned,
732 /// The information we received from a peer along the route of a payment we originated. This is
733 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
734 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
735 #[derive(Clone, Debug, PartialEq)]
736 pub enum HTLCFailChannelUpdate {
737 /// We received an error which included a full ChannelUpdate message.
738 ChannelUpdateMessage {
739 /// The unwrapped message we received
742 /// We received an error which indicated only that a channel has been closed
744 /// The short_channel_id which has now closed.
745 short_channel_id: u64,
746 /// when this true, this channel should be permanently removed from the
747 /// consideration. Otherwise, this channel can be restored as new channel_update is received
750 /// We received an error which indicated only that a node has failed
752 /// The node_id that has failed.
754 /// when this true, node should be permanently removed from the
755 /// consideration. Otherwise, the channels connected to this node can be
756 /// restored as new channel_update is received
761 /// Messages could have optional fields to use with extended features
762 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
763 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
764 /// separate enum type for them.
765 /// (C-not exported) due to a free generic in T
766 #[derive(Clone, Debug, PartialEq)]
767 pub enum OptionalField<T> {
768 /// Optional field is included in message
770 /// Optional field is absent in message
774 /// A trait to describe an object which can receive channel messages.
776 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
777 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
778 pub trait ChannelMessageHandler : MessageSendEventsProvider {
780 /// Handle an incoming open_channel message from the given peer.
781 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
782 /// Handle an incoming accept_channel message from the given peer.
783 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
784 /// Handle an incoming funding_created message from the given peer.
785 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
786 /// Handle an incoming funding_signed message from the given peer.
787 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
788 /// Handle an incoming funding_locked message from the given peer.
789 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
792 /// Handle an incoming shutdown message from the given peer.
793 fn handle_shutdown(&self, their_node_id: &PublicKey, their_features: &InitFeatures, msg: &Shutdown);
794 /// Handle an incoming closing_signed message from the given peer.
795 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
798 /// Handle an incoming update_add_htlc message from the given peer.
799 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
800 /// Handle an incoming update_fulfill_htlc message from the given peer.
801 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
802 /// Handle an incoming update_fail_htlc message from the given peer.
803 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
804 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
805 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
806 /// Handle an incoming commitment_signed message from the given peer.
807 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
808 /// Handle an incoming revoke_and_ack message from the given peer.
809 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
811 /// Handle an incoming update_fee message from the given peer.
812 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
814 // Channel-to-announce:
815 /// Handle an incoming announcement_signatures message from the given peer.
816 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
818 // Connection loss/reestablish:
819 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
820 /// is believed to be possible in the future (eg they're sending us messages we don't
821 /// understand or indicate they require unknown feature bits), no_connection_possible is set
822 /// and any outstanding channels should be failed.
823 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
825 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
826 fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init);
827 /// Handle an incoming channel_reestablish message from the given peer.
828 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
830 /// Handle an incoming channel update from the given peer.
831 fn handle_channel_update(&self, their_node_id: &PublicKey, msg: &ChannelUpdate);
834 /// Handle an incoming error message from the given peer.
835 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
838 /// A trait to describe an object which can receive routing messages.
840 /// # Implementor DoS Warnings
842 /// For `gossip_queries` messages there are potential DoS vectors when handling
843 /// inbound queries. Implementors using an on-disk network graph should be aware of
844 /// repeated disk I/O for queries accessing different parts of the network graph.
845 pub trait RoutingMessageHandler : MessageSendEventsProvider {
846 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
847 /// false or returning an Err otherwise.
848 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
849 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
850 /// or returning an Err otherwise.
851 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
852 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
853 /// false or returning an Err otherwise.
854 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
855 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
856 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
857 /// Gets a subset of the channel announcements and updates required to dump our routing table
858 /// to a remote node, starting at the short_channel_id indicated by starting_point and
859 /// including the batch_amount entries immediately higher in numerical value than starting_point.
860 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
861 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
862 /// starting at the node *after* the provided publickey and including batch_amount entries
863 /// immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
864 /// If None is provided for starting_point, we start at the first node.
865 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
866 /// Called when a connection is established with a peer. This can be used to
867 /// perform routing table synchronization using a strategy defined by the
869 fn sync_routing_table(&self, their_node_id: &PublicKey, init: &Init);
870 /// Handles the reply of a query we initiated to learn about channels
871 /// for a given range of blocks. We can expect to receive one or more
872 /// replies to a single query.
873 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError>;
874 /// Handles the reply of a query we initiated asking for routing gossip
875 /// messages for a list of channels. We should receive this message when
876 /// a node has completed its best effort to send us the pertaining routing
878 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError>;
879 /// Handles when a peer asks us to send a list of short_channel_ids
880 /// for the requested range of blocks.
881 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError>;
882 /// Handles when a peer asks us to send routing gossip messages for a
883 /// list of short_channel_ids.
884 fn handle_query_short_channel_ids(&self, their_node_id: &PublicKey, msg: QueryShortChannelIds) -> Result<(), LightningError>;
887 mod fuzzy_internal_msgs {
889 use ln::{PaymentPreimage, PaymentSecret};
891 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
892 // them from untrusted input):
894 pub(crate) struct FinalOnionHopData {
895 pub(crate) payment_secret: PaymentSecret,
896 /// The total value, in msat, of the payment as received by the ultimate recipient.
897 /// Message serialization may panic if this value is more than 21 million Bitcoin.
898 pub(crate) total_msat: u64,
901 pub(crate) enum OnionHopDataFormat {
902 Legacy { // aka Realm-0
903 short_channel_id: u64,
906 short_channel_id: u64,
909 payment_data: Option<FinalOnionHopData>,
910 keysend_preimage: Option<PaymentPreimage>,
914 pub struct OnionHopData {
915 pub(crate) format: OnionHopDataFormat,
916 /// The value, in msat, of the payment after this hop's fee is deducted.
917 /// Message serialization may panic if this value is more than 21 million Bitcoin.
918 pub(crate) amt_to_forward: u64,
919 pub(crate) outgoing_cltv_value: u32,
920 // 12 bytes of 0-padding for Legacy format
923 pub struct DecodedOnionErrorPacket {
924 pub(crate) hmac: [u8; 32],
925 pub(crate) failuremsg: Vec<u8>,
926 pub(crate) pad: Vec<u8>,
929 #[cfg(feature = "fuzztarget")]
930 pub use self::fuzzy_internal_msgs::*;
931 #[cfg(not(feature = "fuzztarget"))]
932 pub(crate) use self::fuzzy_internal_msgs::*;
935 pub(crate) struct OnionPacket {
936 pub(crate) version: u8,
937 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
938 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
939 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
940 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
941 pub(crate) hop_data: [u8; 20*65],
942 pub(crate) hmac: [u8; 32],
945 impl PartialEq for OnionPacket {
946 fn eq(&self, other: &OnionPacket) -> bool {
947 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
948 if i != j { return false; }
950 self.version == other.version &&
951 self.public_key == other.public_key &&
952 self.hmac == other.hmac
956 impl fmt::Debug for OnionPacket {
957 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
958 f.write_fmt(format_args!("OnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
962 #[derive(Clone, Debug, PartialEq)]
963 pub(crate) struct OnionErrorPacket {
964 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
965 // (TODO) We limit it in decode to much lower...
966 pub(crate) data: Vec<u8>,
969 impl fmt::Display for DecodeError {
970 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
972 DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
973 DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
974 DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
975 DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
976 DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
977 DecodeError::Io(ref e) => e.fmt(f),
978 DecodeError::UnsupportedCompression => f.write_str("We don't support receiving messages with zlib-compressed fields"),
983 impl From<io::Error> for DecodeError {
984 fn from(e: io::Error) -> Self {
985 if e.kind() == io::ErrorKind::UnexpectedEof {
986 DecodeError::ShortRead
988 DecodeError::Io(e.kind())
993 impl Writeable for OptionalField<Script> {
994 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
996 OptionalField::Present(ref script) => {
997 // Note that Writeable for script includes the 16-bit length tag for us
1000 OptionalField::Absent => {}
1006 impl Readable for OptionalField<Script> {
1007 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1008 match <u16 as Readable>::read(r) {
1010 let mut buf = vec![0; len as usize];
1011 r.read_exact(&mut buf)?;
1012 Ok(OptionalField::Present(Script::from(buf)))
1014 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
1020 impl Writeable for OptionalField<u64> {
1021 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1023 OptionalField::Present(ref value) => {
1026 OptionalField::Absent => {}
1032 impl Readable for OptionalField<u64> {
1033 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1034 let value: u64 = Readable::read(r)?;
1035 Ok(OptionalField::Present(value))
1040 impl_writeable_len_match!(AcceptChannel, {
1041 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
1044 temporary_channel_id,
1045 dust_limit_satoshis,
1046 max_htlc_value_in_flight_msat,
1047 channel_reserve_satoshis,
1053 revocation_basepoint,
1055 delayed_payment_basepoint,
1057 first_per_commitment_point,
1058 shutdown_scriptpubkey
1061 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
1068 impl Writeable for ChannelReestablish {
1069 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1070 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
1071 self.channel_id.write(w)?;
1072 self.next_local_commitment_number.write(w)?;
1073 self.next_remote_commitment_number.write(w)?;
1074 match self.data_loss_protect {
1075 OptionalField::Present(ref data_loss_protect) => {
1076 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
1077 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
1079 OptionalField::Absent => {}
1085 impl Readable for ChannelReestablish{
1086 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1088 channel_id: Readable::read(r)?,
1089 next_local_commitment_number: Readable::read(r)?,
1090 next_remote_commitment_number: Readable::read(r)?,
1091 data_loss_protect: {
1092 match <[u8; 32] as Readable>::read(r) {
1093 Ok(your_last_per_commitment_secret) =>
1094 OptionalField::Present(DataLossProtect {
1095 your_last_per_commitment_secret,
1096 my_current_per_commitment_point: Readable::read(r)?,
1098 Err(DecodeError::ShortRead) => OptionalField::Absent,
1099 Err(e) => return Err(e)
1106 impl_writeable!(ClosingSigned, 32+8+64, {
1112 impl_writeable_len_match!(CommitmentSigned, {
1113 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
1120 impl_writeable_len_match!(DecodedOnionErrorPacket, {
1121 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
1128 impl_writeable!(FundingCreated, 32+32+2+64, {
1129 temporary_channel_id,
1131 funding_output_index,
1135 impl_writeable!(FundingSigned, 32+64, {
1140 impl_writeable!(FundingLocked, 32+33, {
1142 next_per_commitment_point
1145 impl Writeable for Init {
1146 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1147 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1148 // our relevant feature bits. This keeps us compatible with old nodes.
1149 self.features.write_up_to_13(w)?;
1150 self.features.write(w)
1154 impl Readable for Init {
1155 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1156 let global_features: InitFeatures = Readable::read(r)?;
1157 let features: InitFeatures = Readable::read(r)?;
1159 features: features.or(global_features),
1164 impl_writeable_len_match!(OpenChannel, {
1165 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
1169 temporary_channel_id,
1172 dust_limit_satoshis,
1173 max_htlc_value_in_flight_msat,
1174 channel_reserve_satoshis,
1180 revocation_basepoint,
1182 delayed_payment_basepoint,
1184 first_per_commitment_point,
1186 shutdown_scriptpubkey
1189 impl_writeable!(RevokeAndACK, 32+32+33, {
1191 per_commitment_secret,
1192 next_per_commitment_point
1195 impl_writeable_len_match!(Shutdown, {
1196 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
1202 impl_writeable_len_match!(UpdateFailHTLC, {
1203 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
1210 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
1217 impl_writeable!(UpdateFee, 32+4, {
1222 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1228 impl_writeable_len_match!(OnionErrorPacket, {
1229 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1234 impl Writeable for OnionPacket {
1235 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1236 w.size_hint(1 + 33 + 20*65 + 32);
1237 self.version.write(w)?;
1238 match self.public_key {
1239 Ok(pubkey) => pubkey.write(w)?,
1240 Err(_) => [0u8;33].write(w)?,
1242 w.write_all(&self.hop_data)?;
1243 self.hmac.write(w)?;
1248 impl Readable for OnionPacket {
1249 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1251 version: Readable::read(r)?,
1253 let mut buf = [0u8;33];
1254 r.read_exact(&mut buf)?;
1255 PublicKey::from_slice(&buf)
1257 hop_data: Readable::read(r)?,
1258 hmac: Readable::read(r)?,
1263 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1269 onion_routing_packet
1272 impl Writeable for FinalOnionHopData {
1273 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1274 w.size_hint(32 + 8 - (self.total_msat.leading_zeros()/8) as usize);
1275 self.payment_secret.0.write(w)?;
1276 HighZeroBytesDroppedVarInt(self.total_msat).write(w)
1280 impl Readable for FinalOnionHopData {
1281 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1282 let secret: [u8; 32] = Readable::read(r)?;
1283 let amt: HighZeroBytesDroppedVarInt<u64> = Readable::read(r)?;
1284 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
1288 impl Writeable for OnionHopData {
1289 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1291 // Note that this should never be reachable if Rust-Lightning generated the message, as we
1292 // check values are sane long before we get here, though its possible in the future
1293 // user-generated messages may hit this.
1294 if self.amt_to_forward > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1296 OnionHopDataFormat::Legacy { short_channel_id } => {
1298 short_channel_id.write(w)?;
1299 self.amt_to_forward.write(w)?;
1300 self.outgoing_cltv_value.write(w)?;
1301 w.write_all(&[0;12])?;
1303 OnionHopDataFormat::NonFinalNode { short_channel_id } => {
1304 encode_varint_length_prefixed_tlv!(w, {
1305 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward), required),
1306 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value), required),
1307 (6, short_channel_id, required)
1310 OnionHopDataFormat::FinalNode { ref payment_data, ref keysend_preimage } => {
1311 if let Some(final_data) = payment_data {
1312 if final_data.total_msat > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1314 encode_varint_length_prefixed_tlv!(w, {
1315 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward), required),
1316 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value), required),
1317 (8, payment_data, option),
1318 (5482373484, keysend_preimage, option)
1326 impl Readable for OnionHopData {
1327 fn read<R: Read>(mut r: &mut R) -> Result<Self, DecodeError> {
1328 use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1329 let v: VarInt = Decodable::consensus_decode(&mut r)
1330 .map_err(|e| match e {
1331 Error::Io(ioe) => DecodeError::from(ioe),
1332 _ => DecodeError::InvalidValue
1334 const LEGACY_ONION_HOP_FLAG: u64 = 0;
1335 let (format, amt, cltv_value) = if v.0 != LEGACY_ONION_HOP_FLAG {
1336 let mut rd = FixedLengthReader::new(r, v.0);
1337 let mut amt = HighZeroBytesDroppedVarInt(0u64);
1338 let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
1339 let mut short_id: Option<u64> = None;
1340 let mut payment_data: Option<FinalOnionHopData> = None;
1341 let mut keysend_preimage: Option<PaymentPreimage> = None;
1342 // The TLV type is chosen to be compatible with lnd and c-lightning.
1343 decode_tlv_stream!(&mut rd, {
1345 (4, cltv_value, required),
1346 (6, short_id, option),
1347 (8, payment_data, option),
1348 (5482373484, keysend_preimage, option)
1350 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1351 let format = if let Some(short_channel_id) = short_id {
1352 if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
1353 OnionHopDataFormat::NonFinalNode {
1357 if let &Some(ref data) = &payment_data {
1358 if data.total_msat > MAX_VALUE_MSAT {
1359 return Err(DecodeError::InvalidValue);
1362 OnionHopDataFormat::FinalNode {
1367 (format, amt.0, cltv_value.0)
1369 let format = OnionHopDataFormat::Legacy {
1370 short_channel_id: Readable::read(r)?,
1372 let amt: u64 = Readable::read(r)?;
1373 let cltv_value: u32 = Readable::read(r)?;
1374 r.read_exact(&mut [0; 12])?;
1375 (format, amt, cltv_value)
1378 if amt > MAX_VALUE_MSAT {
1379 return Err(DecodeError::InvalidValue);
1383 amt_to_forward: amt,
1384 outgoing_cltv_value: cltv_value,
1389 impl Writeable for Ping {
1390 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1391 w.size_hint(self.byteslen as usize + 4);
1392 self.ponglen.write(w)?;
1393 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1398 impl Readable for Ping {
1399 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1401 ponglen: Readable::read(r)?,
1403 let byteslen = Readable::read(r)?;
1404 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1411 impl Writeable for Pong {
1412 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1413 w.size_hint(self.byteslen as usize + 2);
1414 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1419 impl Readable for Pong {
1420 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1423 let byteslen = Readable::read(r)?;
1424 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1431 impl Writeable for UnsignedChannelAnnouncement {
1432 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1433 w.size_hint(2 + 32 + 8 + 4*33 + self.features.byte_count() + self.excess_data.len());
1434 self.features.write(w)?;
1435 self.chain_hash.write(w)?;
1436 self.short_channel_id.write(w)?;
1437 self.node_id_1.write(w)?;
1438 self.node_id_2.write(w)?;
1439 self.bitcoin_key_1.write(w)?;
1440 self.bitcoin_key_2.write(w)?;
1441 w.write_all(&self.excess_data[..])?;
1446 impl Readable for UnsignedChannelAnnouncement {
1447 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1449 features: Readable::read(r)?,
1450 chain_hash: Readable::read(r)?,
1451 short_channel_id: Readable::read(r)?,
1452 node_id_1: Readable::read(r)?,
1453 node_id_2: Readable::read(r)?,
1454 bitcoin_key_1: Readable::read(r)?,
1455 bitcoin_key_2: Readable::read(r)?,
1456 excess_data: read_to_end(r)?,
1461 impl_writeable_len_match!(ChannelAnnouncement, {
1462 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1463 2 + 32 + 8 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1467 bitcoin_signature_1,
1468 bitcoin_signature_2,
1472 impl Writeable for UnsignedChannelUpdate {
1473 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1474 let mut size = 64 + self.excess_data.len();
1475 let mut message_flags: u8 = 0;
1476 if let OptionalField::Present(_) = self.htlc_maximum_msat {
1481 self.chain_hash.write(w)?;
1482 self.short_channel_id.write(w)?;
1483 self.timestamp.write(w)?;
1484 let all_flags = self.flags as u16 | ((message_flags as u16) << 8);
1485 all_flags.write(w)?;
1486 self.cltv_expiry_delta.write(w)?;
1487 self.htlc_minimum_msat.write(w)?;
1488 self.fee_base_msat.write(w)?;
1489 self.fee_proportional_millionths.write(w)?;
1490 self.htlc_maximum_msat.write(w)?;
1491 w.write_all(&self.excess_data[..])?;
1496 impl Readable for UnsignedChannelUpdate {
1497 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1498 let has_htlc_maximum_msat;
1500 chain_hash: Readable::read(r)?,
1501 short_channel_id: Readable::read(r)?,
1502 timestamp: Readable::read(r)?,
1504 let flags: u16 = Readable::read(r)?;
1505 let message_flags = flags >> 8;
1506 has_htlc_maximum_msat = (message_flags as i32 & 1) == 1;
1509 cltv_expiry_delta: Readable::read(r)?,
1510 htlc_minimum_msat: Readable::read(r)?,
1511 fee_base_msat: Readable::read(r)?,
1512 fee_proportional_millionths: Readable::read(r)?,
1513 htlc_maximum_msat: if has_htlc_maximum_msat { Readable::read(r)? } else { OptionalField::Absent },
1514 excess_data: read_to_end(r)?,
1519 impl_writeable_len_match!(ChannelUpdate, {
1520 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ref htlc_maximum_msat, ..}, .. },
1521 64 + 64 + excess_data.len() + if let OptionalField::Present(_) = htlc_maximum_msat { 8 } else { 0 } }
1527 impl Writeable for ErrorMessage {
1528 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1529 w.size_hint(32 + 2 + self.data.len());
1530 self.channel_id.write(w)?;
1531 (self.data.len() as u16).write(w)?;
1532 w.write_all(self.data.as_bytes())?;
1537 impl Readable for ErrorMessage {
1538 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1540 channel_id: Readable::read(r)?,
1542 let mut sz: usize = <u16 as Readable>::read(r)? as usize;
1543 let data = read_to_end(r)?;
1544 sz = cmp::min(data.len(), sz);
1545 match String::from_utf8(data[..sz as usize].to_vec()) {
1547 Err(_) => return Err(DecodeError::InvalidValue),
1554 impl Writeable for UnsignedNodeAnnouncement {
1555 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1556 w.size_hint(76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1557 self.features.write(w)?;
1558 self.timestamp.write(w)?;
1559 self.node_id.write(w)?;
1560 w.write_all(&self.rgb)?;
1561 self.alias.write(w)?;
1563 let mut addr_len = 0;
1564 for addr in self.addresses.iter() {
1565 addr_len += 1 + addr.len();
1567 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1568 for addr in self.addresses.iter() {
1571 w.write_all(&self.excess_address_data[..])?;
1572 w.write_all(&self.excess_data[..])?;
1577 impl Readable for UnsignedNodeAnnouncement {
1578 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1579 let features: NodeFeatures = Readable::read(r)?;
1580 let timestamp: u32 = Readable::read(r)?;
1581 let node_id: PublicKey = Readable::read(r)?;
1582 let mut rgb = [0; 3];
1583 r.read_exact(&mut rgb)?;
1584 let alias: [u8; 32] = Readable::read(r)?;
1586 let addr_len: u16 = Readable::read(r)?;
1587 let mut addresses: Vec<NetAddress> = Vec::new();
1588 let mut addr_readpos = 0;
1589 let mut excess = false;
1590 let mut excess_byte = 0;
1592 if addr_len <= addr_readpos { break; }
1593 match Readable::read(r) {
1595 if addr_len < addr_readpos + 1 + addr.len() {
1596 return Err(DecodeError::BadLengthDescriptor);
1598 addr_readpos += (1 + addr.len()) as u16;
1599 addresses.push(addr);
1601 Ok(Err(unknown_descriptor)) => {
1603 excess_byte = unknown_descriptor;
1606 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1607 Err(e) => return Err(e),
1611 let mut excess_data = vec![];
1612 let excess_address_data = if addr_readpos < addr_len {
1613 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1614 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1616 excess_address_data[0] = excess_byte;
1621 excess_data.push(excess_byte);
1625 excess_data.extend(read_to_end(r)?.iter());
1626 Ok(UnsignedNodeAnnouncement {
1633 excess_address_data,
1639 impl_writeable_len_match!(NodeAnnouncement, <=, {
1640 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1641 64 + 76 + features.byte_count() + addresses.len()*(NetAddress::MAX_LEN as usize + 1) + excess_address_data.len() + excess_data.len() }
1647 impl Readable for QueryShortChannelIds {
1648 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1649 let chain_hash: BlockHash = Readable::read(r)?;
1651 let encoding_len: u16 = Readable::read(r)?;
1652 let encoding_type: u8 = Readable::read(r)?;
1654 // Must be encoding_type=0 uncompressed serialization. We do not
1655 // support encoding_type=1 zlib serialization.
1656 if encoding_type != EncodingType::Uncompressed as u8 {
1657 return Err(DecodeError::UnsupportedCompression);
1660 // We expect the encoding_len to always includes the 1-byte
1661 // encoding_type and that short_channel_ids are 8-bytes each
1662 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1663 return Err(DecodeError::InvalidValue);
1666 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1667 // less the 1-byte encoding_type
1668 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1669 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1670 for _ in 0..short_channel_id_count {
1671 short_channel_ids.push(Readable::read(r)?);
1674 Ok(QueryShortChannelIds {
1681 impl Writeable for QueryShortChannelIds {
1682 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1683 // Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
1684 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1686 w.size_hint(32 + 2 + encoding_len as usize);
1687 self.chain_hash.write(w)?;
1688 encoding_len.write(w)?;
1690 // We only support type=0 uncompressed serialization
1691 (EncodingType::Uncompressed as u8).write(w)?;
1693 for scid in self.short_channel_ids.iter() {
1701 impl Readable for ReplyShortChannelIdsEnd {
1702 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1703 let chain_hash: BlockHash = Readable::read(r)?;
1704 let full_information: bool = Readable::read(r)?;
1705 Ok(ReplyShortChannelIdsEnd {
1712 impl Writeable for ReplyShortChannelIdsEnd {
1713 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1714 w.size_hint(32 + 1);
1715 self.chain_hash.write(w)?;
1716 self.full_information.write(w)?;
1721 impl QueryChannelRange {
1723 * Calculates the overflow safe ending block height for the query.
1724 * Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`
1726 pub fn end_blocknum(&self) -> u32 {
1727 match self.first_blocknum.checked_add(self.number_of_blocks) {
1728 Some(block) => block,
1729 None => u32::max_value(),
1734 impl Readable for QueryChannelRange {
1735 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1736 let chain_hash: BlockHash = Readable::read(r)?;
1737 let first_blocknum: u32 = Readable::read(r)?;
1738 let number_of_blocks: u32 = Readable::read(r)?;
1739 Ok(QueryChannelRange {
1747 impl Writeable for QueryChannelRange {
1748 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1749 w.size_hint(32 + 4 + 4);
1750 self.chain_hash.write(w)?;
1751 self.first_blocknum.write(w)?;
1752 self.number_of_blocks.write(w)?;
1757 impl Readable for ReplyChannelRange {
1758 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1759 let chain_hash: BlockHash = Readable::read(r)?;
1760 let first_blocknum: u32 = Readable::read(r)?;
1761 let number_of_blocks: u32 = Readable::read(r)?;
1762 let sync_complete: bool = Readable::read(r)?;
1764 let encoding_len: u16 = Readable::read(r)?;
1765 let encoding_type: u8 = Readable::read(r)?;
1767 // Must be encoding_type=0 uncompressed serialization. We do not
1768 // support encoding_type=1 zlib serialization.
1769 if encoding_type != EncodingType::Uncompressed as u8 {
1770 return Err(DecodeError::UnsupportedCompression);
1773 // We expect the encoding_len to always includes the 1-byte
1774 // encoding_type and that short_channel_ids are 8-bytes each
1775 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1776 return Err(DecodeError::InvalidValue);
1779 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1780 // less the 1-byte encoding_type
1781 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1782 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1783 for _ in 0..short_channel_id_count {
1784 short_channel_ids.push(Readable::read(r)?);
1787 Ok(ReplyChannelRange {
1797 impl Writeable for ReplyChannelRange {
1798 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1799 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1800 w.size_hint(32 + 4 + 4 + 1 + 2 + encoding_len as usize);
1801 self.chain_hash.write(w)?;
1802 self.first_blocknum.write(w)?;
1803 self.number_of_blocks.write(w)?;
1804 self.sync_complete.write(w)?;
1806 encoding_len.write(w)?;
1807 (EncodingType::Uncompressed as u8).write(w)?;
1808 for scid in self.short_channel_ids.iter() {
1816 impl Readable for GossipTimestampFilter {
1817 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1818 let chain_hash: BlockHash = Readable::read(r)?;
1819 let first_timestamp: u32 = Readable::read(r)?;
1820 let timestamp_range: u32 = Readable::read(r)?;
1821 Ok(GossipTimestampFilter {
1829 impl Writeable for GossipTimestampFilter {
1830 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1831 w.size_hint(32 + 4 + 4);
1832 self.chain_hash.write(w)?;
1833 self.first_timestamp.write(w)?;
1834 self.timestamp_range.write(w)?;
1843 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
1845 use ln::msgs::{ChannelFeatures, FinalOnionHopData, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1846 use util::ser::{Writeable, Readable};
1848 use bitcoin::hashes::hex::FromHex;
1849 use bitcoin::util::address::Address;
1850 use bitcoin::network::constants::Network;
1851 use bitcoin::blockdata::script::Builder;
1852 use bitcoin::blockdata::opcodes;
1853 use bitcoin::hash_types::{Txid, BlockHash};
1855 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1856 use bitcoin::secp256k1::{Secp256k1, Message};
1862 fn encoding_channel_reestablish_no_secret() {
1863 let cr = msgs::ChannelReestablish {
1864 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],
1865 next_local_commitment_number: 3,
1866 next_remote_commitment_number: 4,
1867 data_loss_protect: OptionalField::Absent,
1870 let encoded_value = cr.encode();
1873 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]
1878 fn encoding_channel_reestablish_with_secret() {
1880 let secp_ctx = Secp256k1::new();
1881 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1884 let cr = msgs::ChannelReestablish {
1885 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],
1886 next_local_commitment_number: 3,
1887 next_remote_commitment_number: 4,
1888 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1891 let encoded_value = cr.encode();
1894 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]
1898 macro_rules! get_keys_from {
1899 ($slice: expr, $secp_ctx: expr) => {
1901 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1902 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1908 macro_rules! get_sig_on {
1909 ($privkey: expr, $ctx: expr, $string: expr) => {
1911 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1912 $ctx.sign(&sighash, &$privkey)
1918 fn encoding_announcement_signatures() {
1919 let secp_ctx = Secp256k1::new();
1920 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1921 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1922 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1923 let announcement_signatures = msgs::AnnouncementSignatures {
1924 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],
1925 short_channel_id: 2316138423780173,
1926 node_signature: sig_1,
1927 bitcoin_signature: sig_2,
1930 let encoded_value = announcement_signatures.encode();
1931 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1934 fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
1935 let secp_ctx = Secp256k1::new();
1936 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1937 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1938 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1939 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1940 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1941 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1942 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1943 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1944 let mut features = ChannelFeatures::known();
1945 if unknown_features_bits {
1946 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
1948 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1950 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
1951 short_channel_id: 2316138423780173,
1952 node_id_1: pubkey_1,
1953 node_id_2: pubkey_2,
1954 bitcoin_key_1: pubkey_3,
1955 bitcoin_key_2: pubkey_4,
1956 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1958 let channel_announcement = msgs::ChannelAnnouncement {
1959 node_signature_1: sig_1,
1960 node_signature_2: sig_2,
1961 bitcoin_signature_1: sig_3,
1962 bitcoin_signature_2: sig_4,
1963 contents: unsigned_channel_announcement,
1965 let encoded_value = channel_announcement.encode();
1966 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1967 if unknown_features_bits {
1968 target_value.append(&mut hex::decode("0002ffff").unwrap());
1970 target_value.append(&mut hex::decode("0000").unwrap());
1972 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1973 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1975 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1977 assert_eq!(encoded_value, target_value);
1981 fn encoding_channel_announcement() {
1982 do_encoding_channel_announcement(true, false);
1983 do_encoding_channel_announcement(false, true);
1984 do_encoding_channel_announcement(false, false);
1985 do_encoding_channel_announcement(true, true);
1988 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1989 let secp_ctx = Secp256k1::new();
1990 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1991 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1992 let features = if unknown_features_bits {
1993 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
1995 // Set to some features we may support
1996 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
1998 let mut addresses = Vec::new();
2000 addresses.push(msgs::NetAddress::IPv4 {
2001 addr: [255, 254, 253, 252],
2006 addresses.push(msgs::NetAddress::IPv6 {
2007 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
2012 addresses.push(msgs::NetAddress::OnionV2 {
2013 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
2018 addresses.push(msgs::NetAddress::OnionV3 {
2019 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],
2025 let mut addr_len = 0;
2026 for addr in &addresses {
2027 addr_len += addr.len() + 1;
2029 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
2031 timestamp: 20190119,
2036 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() },
2037 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() },
2039 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
2040 let node_announcement = msgs::NodeAnnouncement {
2042 contents: unsigned_node_announcement,
2044 let encoded_value = node_announcement.encode();
2045 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2046 if unknown_features_bits {
2047 target_value.append(&mut hex::decode("0002ffff").unwrap());
2049 target_value.append(&mut hex::decode("000122").unwrap());
2051 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
2052 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
2054 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
2057 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
2060 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
2063 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
2065 if excess_address_data {
2066 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
2069 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2071 assert_eq!(encoded_value, target_value);
2075 fn encoding_node_announcement() {
2076 do_encoding_node_announcement(true, true, true, true, true, true, true);
2077 do_encoding_node_announcement(false, false, false, false, false, false, false);
2078 do_encoding_node_announcement(false, true, false, false, false, false, false);
2079 do_encoding_node_announcement(false, false, true, false, false, false, false);
2080 do_encoding_node_announcement(false, false, false, true, false, false, false);
2081 do_encoding_node_announcement(false, false, false, false, true, false, false);
2082 do_encoding_node_announcement(false, false, false, false, false, true, false);
2083 do_encoding_node_announcement(false, true, false, true, false, true, false);
2084 do_encoding_node_announcement(false, false, true, false, true, false, false);
2087 fn do_encoding_channel_update(direction: bool, disable: bool, htlc_maximum_msat: bool, excess_data: bool) {
2088 let secp_ctx = Secp256k1::new();
2089 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2090 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2091 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
2092 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2093 short_channel_id: 2316138423780173,
2094 timestamp: 20190119,
2095 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
2096 cltv_expiry_delta: 144,
2097 htlc_minimum_msat: 1000000,
2098 htlc_maximum_msat: if htlc_maximum_msat { OptionalField::Present(131355275467161) } else { OptionalField::Absent },
2099 fee_base_msat: 10000,
2100 fee_proportional_millionths: 20,
2101 excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
2103 let channel_update = msgs::ChannelUpdate {
2105 contents: unsigned_channel_update
2107 let encoded_value = channel_update.encode();
2108 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2109 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2110 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
2111 if htlc_maximum_msat {
2112 target_value.append(&mut hex::decode("01").unwrap());
2114 target_value.append(&mut hex::decode("00").unwrap());
2116 target_value.append(&mut hex::decode("00").unwrap());
2118 let flag = target_value.last_mut().unwrap();
2122 let flag = target_value.last_mut().unwrap();
2123 *flag = *flag | 1 << 1;
2125 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
2126 if htlc_maximum_msat {
2127 target_value.append(&mut hex::decode("0000777788889999").unwrap());
2130 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
2132 assert_eq!(encoded_value, target_value);
2136 fn encoding_channel_update() {
2137 do_encoding_channel_update(false, false, false, false);
2138 do_encoding_channel_update(false, false, false, true);
2139 do_encoding_channel_update(true, false, false, false);
2140 do_encoding_channel_update(true, false, false, true);
2141 do_encoding_channel_update(false, true, false, false);
2142 do_encoding_channel_update(false, true, false, true);
2143 do_encoding_channel_update(false, false, true, false);
2144 do_encoding_channel_update(false, false, true, true);
2145 do_encoding_channel_update(true, true, true, false);
2146 do_encoding_channel_update(true, true, true, true);
2149 fn do_encoding_open_channel(random_bit: bool, shutdown: bool) {
2150 let secp_ctx = Secp256k1::new();
2151 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2152 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2153 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2154 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2155 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2156 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2157 let open_channel = msgs::OpenChannel {
2158 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2159 temporary_channel_id: [2; 32],
2160 funding_satoshis: 1311768467284833366,
2161 push_msat: 2536655962884945560,
2162 dust_limit_satoshis: 3608586615801332854,
2163 max_htlc_value_in_flight_msat: 8517154655701053848,
2164 channel_reserve_satoshis: 8665828695742877976,
2165 htlc_minimum_msat: 2316138423780173,
2166 feerate_per_kw: 821716,
2167 to_self_delay: 49340,
2168 max_accepted_htlcs: 49340,
2169 funding_pubkey: pubkey_1,
2170 revocation_basepoint: pubkey_2,
2171 payment_point: pubkey_3,
2172 delayed_payment_basepoint: pubkey_4,
2173 htlc_basepoint: pubkey_5,
2174 first_per_commitment_point: pubkey_6,
2175 channel_flags: if random_bit { 1 << 5 } else { 0 },
2176 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
2178 let encoded_value = open_channel.encode();
2179 let mut target_value = Vec::new();
2180 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2181 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
2183 target_value.append(&mut hex::decode("20").unwrap());
2185 target_value.append(&mut hex::decode("00").unwrap());
2188 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2190 assert_eq!(encoded_value, target_value);
2194 fn encoding_open_channel() {
2195 do_encoding_open_channel(false, false);
2196 do_encoding_open_channel(true, false);
2197 do_encoding_open_channel(false, true);
2198 do_encoding_open_channel(true, true);
2201 fn do_encoding_accept_channel(shutdown: bool) {
2202 let secp_ctx = Secp256k1::new();
2203 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2204 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2205 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2206 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2207 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2208 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2209 let accept_channel = msgs::AcceptChannel {
2210 temporary_channel_id: [2; 32],
2211 dust_limit_satoshis: 1311768467284833366,
2212 max_htlc_value_in_flight_msat: 2536655962884945560,
2213 channel_reserve_satoshis: 3608586615801332854,
2214 htlc_minimum_msat: 2316138423780173,
2215 minimum_depth: 821716,
2216 to_self_delay: 49340,
2217 max_accepted_htlcs: 49340,
2218 funding_pubkey: pubkey_1,
2219 revocation_basepoint: pubkey_2,
2220 payment_point: pubkey_3,
2221 delayed_payment_basepoint: pubkey_4,
2222 htlc_basepoint: pubkey_5,
2223 first_per_commitment_point: pubkey_6,
2224 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
2226 let encoded_value = accept_channel.encode();
2227 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
2229 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2231 assert_eq!(encoded_value, target_value);
2235 fn encoding_accept_channel() {
2236 do_encoding_accept_channel(false);
2237 do_encoding_accept_channel(true);
2241 fn encoding_funding_created() {
2242 let secp_ctx = Secp256k1::new();
2243 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2244 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2245 let funding_created = msgs::FundingCreated {
2246 temporary_channel_id: [2; 32],
2247 funding_txid: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
2248 funding_output_index: 255,
2251 let encoded_value = funding_created.encode();
2252 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2253 assert_eq!(encoded_value, target_value);
2257 fn encoding_funding_signed() {
2258 let secp_ctx = Secp256k1::new();
2259 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2260 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2261 let funding_signed = msgs::FundingSigned {
2262 channel_id: [2; 32],
2265 let encoded_value = funding_signed.encode();
2266 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2267 assert_eq!(encoded_value, target_value);
2271 fn encoding_funding_locked() {
2272 let secp_ctx = Secp256k1::new();
2273 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2274 let funding_locked = msgs::FundingLocked {
2275 channel_id: [2; 32],
2276 next_per_commitment_point: pubkey_1,
2278 let encoded_value = funding_locked.encode();
2279 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2280 assert_eq!(encoded_value, target_value);
2283 fn do_encoding_shutdown(script_type: u8) {
2284 let secp_ctx = Secp256k1::new();
2285 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2286 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
2287 let shutdown = msgs::Shutdown {
2288 channel_id: [2; 32],
2290 if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() }
2291 else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() }
2292 else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).unwrap().script_pubkey() }
2293 else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
2295 let encoded_value = shutdown.encode();
2296 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
2297 if script_type == 1 {
2298 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2299 } else if script_type == 2 {
2300 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
2301 } else if script_type == 3 {
2302 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
2303 } else if script_type == 4 {
2304 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
2306 assert_eq!(encoded_value, target_value);
2310 fn encoding_shutdown() {
2311 do_encoding_shutdown(1);
2312 do_encoding_shutdown(2);
2313 do_encoding_shutdown(3);
2314 do_encoding_shutdown(4);
2318 fn encoding_closing_signed() {
2319 let secp_ctx = Secp256k1::new();
2320 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2321 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2322 let closing_signed = msgs::ClosingSigned {
2323 channel_id: [2; 32],
2324 fee_satoshis: 2316138423780173,
2327 let encoded_value = closing_signed.encode();
2328 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2329 assert_eq!(encoded_value, target_value);
2333 fn encoding_update_add_htlc() {
2334 let secp_ctx = Secp256k1::new();
2335 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2336 let onion_routing_packet = msgs::OnionPacket {
2338 public_key: Ok(pubkey_1),
2339 hop_data: [1; 20*65],
2342 let update_add_htlc = msgs::UpdateAddHTLC {
2343 channel_id: [2; 32],
2344 htlc_id: 2316138423780173,
2345 amount_msat: 3608586615801332854,
2346 payment_hash: PaymentHash([1; 32]),
2347 cltv_expiry: 821716,
2348 onion_routing_packet
2350 let encoded_value = update_add_htlc.encode();
2351 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
2352 assert_eq!(encoded_value, target_value);
2356 fn encoding_update_fulfill_htlc() {
2357 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
2358 channel_id: [2; 32],
2359 htlc_id: 2316138423780173,
2360 payment_preimage: PaymentPreimage([1; 32]),
2362 let encoded_value = update_fulfill_htlc.encode();
2363 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
2364 assert_eq!(encoded_value, target_value);
2368 fn encoding_update_fail_htlc() {
2369 let reason = OnionErrorPacket {
2370 data: [1; 32].to_vec(),
2372 let update_fail_htlc = msgs::UpdateFailHTLC {
2373 channel_id: [2; 32],
2374 htlc_id: 2316138423780173,
2377 let encoded_value = update_fail_htlc.encode();
2378 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
2379 assert_eq!(encoded_value, target_value);
2383 fn encoding_update_fail_malformed_htlc() {
2384 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
2385 channel_id: [2; 32],
2386 htlc_id: 2316138423780173,
2387 sha256_of_onion: [1; 32],
2390 let encoded_value = update_fail_malformed_htlc.encode();
2391 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
2392 assert_eq!(encoded_value, target_value);
2395 fn do_encoding_commitment_signed(htlcs: bool) {
2396 let secp_ctx = Secp256k1::new();
2397 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2398 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2399 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2400 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2401 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2402 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2403 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2404 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2405 let commitment_signed = msgs::CommitmentSigned {
2406 channel_id: [2; 32],
2408 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
2410 let encoded_value = commitment_signed.encode();
2411 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2413 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2415 target_value.append(&mut hex::decode("0000").unwrap());
2417 assert_eq!(encoded_value, target_value);
2421 fn encoding_commitment_signed() {
2422 do_encoding_commitment_signed(true);
2423 do_encoding_commitment_signed(false);
2427 fn encoding_revoke_and_ack() {
2428 let secp_ctx = Secp256k1::new();
2429 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2430 let raa = msgs::RevokeAndACK {
2431 channel_id: [2; 32],
2432 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],
2433 next_per_commitment_point: pubkey_1,
2435 let encoded_value = raa.encode();
2436 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2437 assert_eq!(encoded_value, target_value);
2441 fn encoding_update_fee() {
2442 let update_fee = msgs::UpdateFee {
2443 channel_id: [2; 32],
2444 feerate_per_kw: 20190119,
2446 let encoded_value = update_fee.encode();
2447 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2448 assert_eq!(encoded_value, target_value);
2452 fn encoding_init() {
2453 assert_eq!(msgs::Init {
2454 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
2455 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2456 assert_eq!(msgs::Init {
2457 features: InitFeatures::from_le_bytes(vec![0xFF]),
2458 }.encode(), hex::decode("0001ff0001ff").unwrap());
2459 assert_eq!(msgs::Init {
2460 features: InitFeatures::from_le_bytes(vec![]),
2461 }.encode(), hex::decode("00000000").unwrap());
2465 fn encoding_error() {
2466 let error = msgs::ErrorMessage {
2467 channel_id: [2; 32],
2468 data: String::from("rust-lightning"),
2470 let encoded_value = error.encode();
2471 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2472 assert_eq!(encoded_value, target_value);
2476 fn encoding_ping() {
2477 let ping = msgs::Ping {
2481 let encoded_value = ping.encode();
2482 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2483 assert_eq!(encoded_value, target_value);
2487 fn encoding_pong() {
2488 let pong = msgs::Pong {
2491 let encoded_value = pong.encode();
2492 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2493 assert_eq!(encoded_value, target_value);
2497 fn encoding_legacy_onion_hop_data() {
2498 let msg = msgs::OnionHopData {
2499 format: OnionHopDataFormat::Legacy {
2500 short_channel_id: 0xdeadbeef1bad1dea,
2502 amt_to_forward: 0x0badf00d01020304,
2503 outgoing_cltv_value: 0xffffffff,
2505 let encoded_value = msg.encode();
2506 let target_value = hex::decode("00deadbeef1bad1dea0badf00d01020304ffffffff000000000000000000000000").unwrap();
2507 assert_eq!(encoded_value, target_value);
2511 fn encoding_nonfinal_onion_hop_data() {
2512 let mut msg = msgs::OnionHopData {
2513 format: OnionHopDataFormat::NonFinalNode {
2514 short_channel_id: 0xdeadbeef1bad1dea,
2516 amt_to_forward: 0x0badf00d01020304,
2517 outgoing_cltv_value: 0xffffffff,
2519 let encoded_value = msg.encode();
2520 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2521 assert_eq!(encoded_value, target_value);
2522 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2523 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2524 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2525 } else { panic!(); }
2526 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2527 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2531 fn encoding_final_onion_hop_data() {
2532 let mut msg = msgs::OnionHopData {
2533 format: OnionHopDataFormat::FinalNode {
2535 keysend_preimage: None,
2537 amt_to_forward: 0x0badf00d01020304,
2538 outgoing_cltv_value: 0xffffffff,
2540 let encoded_value = msg.encode();
2541 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2542 assert_eq!(encoded_value, target_value);
2543 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2544 if let OnionHopDataFormat::FinalNode { payment_data: None, .. } = msg.format { } else { panic!(); }
2545 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2546 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2550 fn encoding_final_onion_hop_data_with_secret() {
2551 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
2552 let mut msg = msgs::OnionHopData {
2553 format: OnionHopDataFormat::FinalNode {
2554 payment_data: Some(FinalOnionHopData {
2555 payment_secret: expected_payment_secret,
2556 total_msat: 0x1badca1f
2558 keysend_preimage: None,
2560 amt_to_forward: 0x0badf00d01020304,
2561 outgoing_cltv_value: 0xffffffff,
2563 let encoded_value = msg.encode();
2564 let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
2565 assert_eq!(encoded_value, target_value);
2566 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2567 if let OnionHopDataFormat::FinalNode {
2568 payment_data: Some(FinalOnionHopData {
2570 total_msat: 0x1badca1f
2572 keysend_preimage: None,
2574 assert_eq!(payment_secret, expected_payment_secret);
2575 } else { panic!(); }
2576 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2577 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2581 fn query_channel_range_end_blocknum() {
2582 let tests: Vec<(u32, u32, u32)> = vec![
2583 (10000, 1500, 11500),
2584 (0, 0xffffffff, 0xffffffff),
2585 (1, 0xffffffff, 0xffffffff),
2588 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
2589 let sut = msgs::QueryChannelRange {
2590 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2594 assert_eq!(sut.end_blocknum(), expected);
2599 fn encoding_query_channel_range() {
2600 let mut query_channel_range = msgs::QueryChannelRange {
2601 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2602 first_blocknum: 100000,
2603 number_of_blocks: 1500,
2605 let encoded_value = query_channel_range.encode();
2606 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000186a0000005dc").unwrap();
2607 assert_eq!(encoded_value, target_value);
2609 query_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2610 assert_eq!(query_channel_range.first_blocknum, 100000);
2611 assert_eq!(query_channel_range.number_of_blocks, 1500);
2615 fn encoding_reply_channel_range() {
2616 do_encoding_reply_channel_range(0);
2617 do_encoding_reply_channel_range(1);
2620 fn do_encoding_reply_channel_range(encoding_type: u8) {
2621 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000b8a06000005dc01").unwrap();
2622 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2623 let mut reply_channel_range = msgs::ReplyChannelRange {
2624 chain_hash: expected_chain_hash,
2625 first_blocknum: 756230,
2626 number_of_blocks: 1500,
2627 sync_complete: true,
2628 short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2631 if encoding_type == 0 {
2632 target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2633 let encoded_value = reply_channel_range.encode();
2634 assert_eq!(encoded_value, target_value);
2636 reply_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2637 assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
2638 assert_eq!(reply_channel_range.first_blocknum, 756230);
2639 assert_eq!(reply_channel_range.number_of_blocks, 1500);
2640 assert_eq!(reply_channel_range.sync_complete, true);
2641 assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
2642 assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
2643 assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
2645 target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2646 let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2647 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2652 fn encoding_query_short_channel_ids() {
2653 do_encoding_query_short_channel_ids(0);
2654 do_encoding_query_short_channel_ids(1);
2657 fn do_encoding_query_short_channel_ids(encoding_type: u8) {
2658 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206").unwrap();
2659 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2660 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
2661 chain_hash: expected_chain_hash,
2662 short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2665 if encoding_type == 0 {
2666 target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2667 let encoded_value = query_short_channel_ids.encode();
2668 assert_eq!(encoded_value, target_value);
2670 query_short_channel_ids = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2671 assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
2672 assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
2673 assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
2674 assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
2676 target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2677 let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2678 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2683 fn encoding_reply_short_channel_ids_end() {
2684 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2685 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
2686 chain_hash: expected_chain_hash,
2687 full_information: true,
2689 let encoded_value = reply_short_channel_ids_end.encode();
2690 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e220601").unwrap();
2691 assert_eq!(encoded_value, target_value);
2693 reply_short_channel_ids_end = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2694 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
2695 assert_eq!(reply_short_channel_ids_end.full_information, true);
2699 fn encoding_gossip_timestamp_filter(){
2700 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2701 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
2702 chain_hash: expected_chain_hash,
2703 first_timestamp: 1590000000,
2704 timestamp_range: 0xffff_ffff,
2706 let encoded_value = gossip_timestamp_filter.encode();
2707 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e22065ec57980ffffffff").unwrap();
2708 assert_eq!(encoded_value, target_value);
2710 gossip_timestamp_filter = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2711 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
2712 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
2713 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);