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 util::events::MessageSendEventsProvider;
40 use util::ser::{Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt};
42 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
44 /// 21 million * 10^8 * 1000
45 pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
47 /// An error in decoding a message or struct.
48 #[derive(Clone, Debug)]
49 pub enum DecodeError {
50 /// A version byte specified something we don't know how to handle.
51 /// Includes unknown realm byte in an OnionHopData packet
53 /// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type)
54 UnknownRequiredFeature,
55 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
56 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was
57 /// syntactically incorrect, etc
61 /// A length descriptor in the packet didn't describe the later data correctly
63 /// Error from std::io
64 Io(/// (C-not exported) as ErrorKind doesn't have a reasonable mapping
65 ::std::io::ErrorKind),
66 /// The message included zlib-compressed values, which we don't support.
67 UnsupportedCompression,
70 /// An init message to be sent or received from a peer
71 #[derive(Clone, Debug, PartialEq)]
73 /// The relevant features which the sender supports
74 pub features: InitFeatures,
77 /// An error message to be sent or received from a peer
78 #[derive(Clone, Debug, PartialEq)]
79 pub struct ErrorMessage {
80 /// The channel ID involved in the error
81 pub channel_id: [u8; 32],
82 /// A possibly human-readable error description.
83 /// The string should be sanitized before it is used (e.g. emitted to logs
84 /// or printed to stdout). Otherwise, a well crafted error message may trigger a security
85 /// vulnerability in the terminal emulator or the logging subsystem.
89 /// A ping message to be sent or received from a peer
90 #[derive(Clone, Debug, PartialEq)]
92 /// The desired response length
94 /// The ping packet size.
95 /// This field is not sent on the wire. byteslen zeros are sent.
99 /// A pong message to be sent or received from a peer
100 #[derive(Clone, Debug, PartialEq)]
102 /// The pong packet size.
103 /// This field is not sent on the wire. byteslen zeros are sent.
107 /// An open_channel message to be sent or received from a peer
108 #[derive(Clone, Debug, PartialEq)]
109 pub struct OpenChannel {
110 /// The genesis hash of the blockchain where the channel is to be opened
111 pub chain_hash: BlockHash,
112 /// A temporary channel ID, until the funding outpoint is announced
113 pub temporary_channel_id: [u8; 32],
114 /// The channel value
115 pub funding_satoshis: u64,
116 /// The amount to push to the counterparty as part of the open, in milli-satoshi
118 /// The threshold below which outputs on transactions broadcast by sender will be omitted
119 pub dust_limit_satoshis: u64,
120 /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
121 pub max_htlc_value_in_flight_msat: u64,
122 /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
123 pub channel_reserve_satoshis: u64,
124 /// The minimum HTLC size incoming to sender, in milli-satoshi
125 pub htlc_minimum_msat: u64,
126 /// The feerate per 1000-weight of sender generated transactions, until updated by update_fee
127 pub feerate_per_kw: u32,
128 /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
129 pub to_self_delay: u16,
130 /// The maximum number of inbound HTLCs towards sender
131 pub max_accepted_htlcs: u16,
132 /// The sender's key controlling the funding transaction
133 pub funding_pubkey: PublicKey,
134 /// Used to derive a revocation key for transactions broadcast by counterparty
135 pub revocation_basepoint: PublicKey,
136 /// A payment key to sender for transactions broadcast by counterparty
137 pub payment_point: PublicKey,
138 /// Used to derive a payment key to sender for transactions broadcast by sender
139 pub delayed_payment_basepoint: PublicKey,
140 /// Used to derive an HTLC payment key to sender
141 pub htlc_basepoint: PublicKey,
142 /// The first to-be-broadcast-by-sender transaction's per commitment point
143 pub first_per_commitment_point: PublicKey,
145 pub channel_flags: u8,
146 /// Optionally, a request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
147 pub shutdown_scriptpubkey: OptionalField<Script>,
150 /// An accept_channel message to be sent or received from a peer
151 #[derive(Clone, Debug, PartialEq)]
152 pub struct AcceptChannel {
153 /// A temporary channel ID, until the funding outpoint is announced
154 pub temporary_channel_id: [u8; 32],
155 /// The threshold below which outputs on transactions broadcast by sender will be omitted
156 pub dust_limit_satoshis: u64,
157 /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi
158 pub max_htlc_value_in_flight_msat: u64,
159 /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel
160 pub channel_reserve_satoshis: u64,
161 /// The minimum HTLC size incoming to sender, in milli-satoshi
162 pub htlc_minimum_msat: u64,
163 /// Minimum depth of the funding transaction before the channel is considered open
164 pub minimum_depth: u32,
165 /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction
166 pub to_self_delay: u16,
167 /// The maximum number of inbound HTLCs towards sender
168 pub max_accepted_htlcs: u16,
169 /// The sender's key controlling the funding transaction
170 pub funding_pubkey: PublicKey,
171 /// Used to derive a revocation key for transactions broadcast by counterparty
172 pub revocation_basepoint: PublicKey,
173 /// A payment key to sender for transactions broadcast by counterparty
174 pub payment_point: PublicKey,
175 /// Used to derive a payment key to sender for transactions broadcast by sender
176 pub delayed_payment_basepoint: PublicKey,
177 /// Used to derive an HTLC payment key to sender for transactions broadcast by counterparty
178 pub htlc_basepoint: PublicKey,
179 /// The first to-be-broadcast-by-sender transaction's per commitment point
180 pub first_per_commitment_point: PublicKey,
181 /// Optionally, a request to pre-set the to-sender output's scriptPubkey for when we collaboratively close
182 pub shutdown_scriptpubkey: OptionalField<Script>,
185 /// A funding_created message to be sent or received from a peer
186 #[derive(Clone, Debug, PartialEq)]
187 pub struct FundingCreated {
188 /// A temporary channel ID, until the funding is established
189 pub temporary_channel_id: [u8; 32],
190 /// The funding transaction ID
191 pub funding_txid: Txid,
192 /// The specific output index funding this channel
193 pub funding_output_index: u16,
194 /// The signature of the channel initiator (funder) on the funding transaction
195 pub signature: Signature,
198 /// A funding_signed message to be sent or received from a peer
199 #[derive(Clone, Debug, PartialEq)]
200 pub struct FundingSigned {
202 pub channel_id: [u8; 32],
203 /// The signature of the channel acceptor (fundee) on the funding transaction
204 pub signature: Signature,
207 /// A funding_locked message to be sent or received from a peer
208 #[derive(Clone, Debug, PartialEq)]
209 pub struct FundingLocked {
211 pub channel_id: [u8; 32],
212 /// The per-commitment point of the second commitment transaction
213 pub next_per_commitment_point: PublicKey,
216 /// A shutdown message to be sent or received from a peer
217 #[derive(Clone, Debug, PartialEq)]
218 pub struct Shutdown {
220 pub channel_id: [u8; 32],
221 /// The destination of this peer's funds on closing.
222 /// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh.
223 pub scriptpubkey: Script,
226 /// A closing_signed message to be sent or received from a peer
227 #[derive(Clone, Debug, PartialEq)]
228 pub struct ClosingSigned {
230 pub channel_id: [u8; 32],
231 /// The proposed total fee for the closing transaction
232 pub fee_satoshis: u64,
233 /// A signature on the closing transaction
234 pub signature: Signature,
237 /// An update_add_htlc message to be sent or received from a peer
238 #[derive(Clone, Debug, PartialEq)]
239 pub struct UpdateAddHTLC {
241 pub channel_id: [u8; 32],
244 /// The HTLC value in milli-satoshi
245 pub amount_msat: u64,
246 /// The payment hash, the pre-image of which controls HTLC redemption
247 pub payment_hash: PaymentHash,
248 /// The expiry height of the HTLC
249 pub cltv_expiry: u32,
250 pub(crate) onion_routing_packet: OnionPacket,
253 /// An update_fulfill_htlc message to be sent or received from a peer
254 #[derive(Clone, Debug, PartialEq)]
255 pub struct UpdateFulfillHTLC {
257 pub channel_id: [u8; 32],
260 /// The pre-image of the payment hash, allowing HTLC redemption
261 pub payment_preimage: PaymentPreimage,
264 /// An update_fail_htlc message to be sent or received from a peer
265 #[derive(Clone, Debug, PartialEq)]
266 pub struct UpdateFailHTLC {
268 pub channel_id: [u8; 32],
271 pub(crate) reason: OnionErrorPacket,
274 /// An update_fail_malformed_htlc message to be sent or received from a peer
275 #[derive(Clone, Debug, PartialEq)]
276 pub struct UpdateFailMalformedHTLC {
278 pub channel_id: [u8; 32],
281 pub(crate) sha256_of_onion: [u8; 32],
283 pub failure_code: u16,
286 /// A commitment_signed message to be sent or received from a peer
287 #[derive(Clone, Debug, PartialEq)]
288 pub struct CommitmentSigned {
290 pub channel_id: [u8; 32],
291 /// A signature on the commitment transaction
292 pub signature: Signature,
293 /// Signatures on the HTLC transactions
294 pub htlc_signatures: Vec<Signature>,
297 /// A revoke_and_ack message to be sent or received from a peer
298 #[derive(Clone, Debug, PartialEq)]
299 pub struct RevokeAndACK {
301 pub channel_id: [u8; 32],
302 /// The secret corresponding to the per-commitment point
303 pub per_commitment_secret: [u8; 32],
304 /// The next sender-broadcast commitment transaction's per-commitment point
305 pub next_per_commitment_point: PublicKey,
308 /// An update_fee message to be sent or received from a peer
309 #[derive(Clone, Debug, PartialEq)]
310 pub struct UpdateFee {
312 pub channel_id: [u8; 32],
313 /// Fee rate per 1000-weight of the transaction
314 pub feerate_per_kw: u32,
317 #[derive(Clone, Debug, PartialEq)]
318 /// Proof that the sender knows the per-commitment secret of the previous commitment transaction.
319 /// This is used to convince the recipient that the channel is at a certain commitment
320 /// number even if they lost that data due to a local failure. Of course, the peer may lie
321 /// and even later commitments may have been revoked.
322 pub struct DataLossProtect {
323 /// Proof that the sender knows the per-commitment secret of a specific commitment transaction
324 /// belonging to the recipient
325 pub your_last_per_commitment_secret: [u8; 32],
326 /// The sender's per-commitment point for their current commitment transaction
327 pub my_current_per_commitment_point: PublicKey,
330 /// A channel_reestablish message to be sent or received from a peer
331 #[derive(Clone, Debug, PartialEq)]
332 pub struct ChannelReestablish {
334 pub channel_id: [u8; 32],
335 /// The next commitment number for the sender
336 pub next_local_commitment_number: u64,
337 /// The next commitment number for the recipient
338 pub next_remote_commitment_number: u64,
339 /// Optionally, a field proving that next_remote_commitment_number-1 has been revoked
340 pub data_loss_protect: OptionalField<DataLossProtect>,
343 /// An announcement_signatures message to be sent or received from a peer
344 #[derive(Clone, Debug, PartialEq)]
345 pub struct AnnouncementSignatures {
347 pub channel_id: [u8; 32],
348 /// The short channel ID
349 pub short_channel_id: u64,
350 /// A signature by the node key
351 pub node_signature: Signature,
352 /// A signature by the funding key
353 pub bitcoin_signature: Signature,
356 /// An address which can be used to connect to a remote peer
357 #[derive(Clone, Debug, PartialEq)]
358 pub enum NetAddress {
359 /// An IPv4 address/port on which the peer is listening.
361 /// The 4-byte IPv4 address
363 /// The port on which the node is listening
366 /// An IPv6 address/port on which the peer is listening.
368 /// The 16-byte IPv6 address
370 /// The port on which the node is listening
373 /// An old-style Tor onion address/port on which the peer is listening.
375 /// The bytes (usually encoded in base32 with ".onion" appended)
377 /// The port on which the node is listening
380 /// A new-style Tor onion address/port on which the peer is listening.
381 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
382 /// wrap as base32 and append ".onion".
384 /// The ed25519 long-term public key of the peer
385 ed25519_pubkey: [u8; 32],
386 /// The checksum of the pubkey and version, as included in the onion address
388 /// The version byte, as defined by the Tor Onion v3 spec.
390 /// The port on which the node is listening
395 /// Gets the ID of this address type. Addresses in node_announcement messages should be sorted
397 pub(crate) fn get_id(&self) -> u8 {
399 &NetAddress::IPv4 {..} => { 1 },
400 &NetAddress::IPv6 {..} => { 2 },
401 &NetAddress::OnionV2 {..} => { 3 },
402 &NetAddress::OnionV3 {..} => { 4 },
406 /// Strict byte-length of address descriptor, 1-byte type not recorded
407 fn len(&self) -> u16 {
409 &NetAddress::IPv4 { .. } => { 6 },
410 &NetAddress::IPv6 { .. } => { 18 },
411 &NetAddress::OnionV2 { .. } => { 12 },
412 &NetAddress::OnionV3 { .. } => { 37 },
416 /// The maximum length of any address descriptor, not including the 1-byte type
417 pub(crate) const MAX_LEN: u16 = 37;
420 impl Writeable for NetAddress {
421 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
423 &NetAddress::IPv4 { ref addr, ref port } => {
428 &NetAddress::IPv6 { ref addr, ref port } => {
433 &NetAddress::OnionV2 { ref addr, ref port } => {
438 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
440 ed25519_pubkey.write(writer)?;
441 checksum.write(writer)?;
442 version.write(writer)?;
450 impl Readable for Result<NetAddress, u8> {
451 fn read<R: Read>(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
452 let byte = <u8 as Readable>::read(reader)?;
455 Ok(Ok(NetAddress::IPv4 {
456 addr: Readable::read(reader)?,
457 port: Readable::read(reader)?,
461 Ok(Ok(NetAddress::IPv6 {
462 addr: Readable::read(reader)?,
463 port: Readable::read(reader)?,
467 Ok(Ok(NetAddress::OnionV2 {
468 addr: Readable::read(reader)?,
469 port: Readable::read(reader)?,
473 Ok(Ok(NetAddress::OnionV3 {
474 ed25519_pubkey: Readable::read(reader)?,
475 checksum: Readable::read(reader)?,
476 version: Readable::read(reader)?,
477 port: Readable::read(reader)?,
480 _ => return Ok(Err(byte)),
485 impl Readable for NetAddress {
486 fn read<R: Read>(reader: &mut R) -> Result<NetAddress, DecodeError> {
487 match Readable::read(reader) {
488 Ok(Ok(res)) => Ok(res),
489 Ok(Err(_)) => Err(DecodeError::UnknownVersion),
496 /// The unsigned part of a node_announcement
497 #[derive(Clone, Debug, PartialEq)]
498 pub struct UnsignedNodeAnnouncement {
499 /// The advertised features
500 pub features: NodeFeatures,
501 /// A strictly monotonic announcement counter, with gaps allowed
503 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
505 pub node_id: PublicKey,
506 /// An RGB color for UI purposes
508 /// An alias, for UI purposes. This should be sanitized before use. There is no guarantee
511 /// List of addresses on which this node is reachable
512 pub addresses: Vec<NetAddress>,
513 pub(crate) excess_address_data: Vec<u8>,
514 pub(crate) excess_data: Vec<u8>,
516 #[derive(Clone, Debug, PartialEq)]
517 /// A node_announcement message to be sent or received from a peer
518 pub struct NodeAnnouncement {
519 /// The signature by the node key
520 pub signature: Signature,
521 /// The actual content of the announcement
522 pub contents: UnsignedNodeAnnouncement,
525 /// The unsigned part of a channel_announcement
526 #[derive(Clone, Debug, PartialEq)]
527 pub struct UnsignedChannelAnnouncement {
528 /// The advertised channel features
529 pub features: ChannelFeatures,
530 /// The genesis hash of the blockchain where the channel is to be opened
531 pub chain_hash: BlockHash,
532 /// The short channel ID
533 pub short_channel_id: u64,
534 /// One of the two node_ids which are endpoints of this channel
535 pub node_id_1: PublicKey,
536 /// The other of the two node_ids which are endpoints of this channel
537 pub node_id_2: PublicKey,
538 /// The funding key for the first node
539 pub bitcoin_key_1: PublicKey,
540 /// The funding key for the second node
541 pub bitcoin_key_2: PublicKey,
542 pub(crate) excess_data: Vec<u8>,
544 /// A channel_announcement message to be sent or received from a peer
545 #[derive(Clone, Debug, PartialEq)]
546 pub struct ChannelAnnouncement {
547 /// Authentication of the announcement by the first public node
548 pub node_signature_1: Signature,
549 /// Authentication of the announcement by the second public node
550 pub node_signature_2: Signature,
551 /// Proof of funding UTXO ownership by the first public node
552 pub bitcoin_signature_1: Signature,
553 /// Proof of funding UTXO ownership by the second public node
554 pub bitcoin_signature_2: Signature,
555 /// The actual announcement
556 pub contents: UnsignedChannelAnnouncement,
559 /// The unsigned part of a channel_update
560 #[derive(Clone, Debug, PartialEq)]
561 pub struct UnsignedChannelUpdate {
562 /// The genesis hash of the blockchain where the channel is to be opened
563 pub chain_hash: BlockHash,
564 /// The short channel ID
565 pub short_channel_id: u64,
566 /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel
570 /// The number of blocks such that if:
571 /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta`
572 /// then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines
573 /// the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a
574 /// cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10,
575 /// then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before
576 /// forwarding. Note that the HTLC sender is the one who originally sets this value when
577 /// constructing the route.
578 pub cltv_expiry_delta: u16,
579 /// The minimum HTLC size incoming to sender, in milli-satoshi
580 pub htlc_minimum_msat: u64,
581 /// Optionally, the maximum HTLC value incoming to sender, in milli-satoshi
582 pub htlc_maximum_msat: OptionalField<u64>,
583 /// The base HTLC fee charged by sender, in milli-satoshi
584 pub fee_base_msat: u32,
585 /// The amount to fee multiplier, in micro-satoshi
586 pub fee_proportional_millionths: u32,
587 pub(crate) excess_data: Vec<u8>,
589 /// A channel_update message to be sent or received from a peer
590 #[derive(Clone, Debug, PartialEq)]
591 pub struct ChannelUpdate {
592 /// A signature of the channel update
593 pub signature: Signature,
594 /// The actual channel update
595 pub contents: UnsignedChannelUpdate,
598 /// A query_channel_range message is used to query a peer for channel
599 /// UTXOs in a range of blocks. The recipient of a query makes a best
600 /// effort to reply to the query using one or more reply_channel_range
602 #[derive(Clone, Debug, PartialEq)]
603 pub struct QueryChannelRange {
604 /// The genesis hash of the blockchain being queried
605 pub chain_hash: BlockHash,
606 /// The height of the first block for the channel UTXOs being queried
607 pub first_blocknum: u32,
608 /// The number of blocks to include in the query results
609 pub number_of_blocks: u32,
612 /// A reply_channel_range message is a reply to a query_channel_range
613 /// message. Multiple reply_channel_range messages can be sent in reply
614 /// to a single query_channel_range message. The query recipient makes a
615 /// best effort to respond based on their local network view which may
616 /// not be a perfect view of the network. The short_channel_ids in the
617 /// reply are encoded. We only support encoding_type=0 uncompressed
618 /// serialization and do not support encoding_type=1 zlib serialization.
619 #[derive(Clone, Debug, PartialEq)]
620 pub struct ReplyChannelRange {
621 /// The genesis hash of the blockchain being queried
622 pub chain_hash: BlockHash,
623 /// The height of the first block in the range of the reply
624 pub first_blocknum: u32,
625 /// The number of blocks included in the range of the reply
626 pub number_of_blocks: u32,
627 /// True when this is the final reply for a query
628 pub sync_complete: bool,
629 /// The short_channel_ids in the channel range
630 pub short_channel_ids: Vec<u64>,
633 /// A query_short_channel_ids message is used to query a peer for
634 /// routing gossip messages related to one or more short_channel_ids.
635 /// The query recipient will reply with the latest, if available,
636 /// channel_announcement, channel_update and node_announcement messages
637 /// it maintains for the requested short_channel_ids followed by a
638 /// reply_short_channel_ids_end message. The short_channel_ids sent in
639 /// this query are encoded. We only support encoding_type=0 uncompressed
640 /// serialization and do not support encoding_type=1 zlib serialization.
641 #[derive(Clone, Debug, PartialEq)]
642 pub struct QueryShortChannelIds {
643 /// The genesis hash of the blockchain being queried
644 pub chain_hash: BlockHash,
645 /// The short_channel_ids that are being queried
646 pub short_channel_ids: Vec<u64>,
649 /// A reply_short_channel_ids_end message is sent as a reply to a
650 /// query_short_channel_ids message. The query recipient makes a best
651 /// effort to respond based on their local network view which may not be
652 /// a perfect view of the network.
653 #[derive(Clone, Debug, PartialEq)]
654 pub struct ReplyShortChannelIdsEnd {
655 /// The genesis hash of the blockchain that was queried
656 pub chain_hash: BlockHash,
657 /// Indicates if the query recipient maintains up-to-date channel
658 /// information for the chain_hash
659 pub full_information: bool,
662 /// A gossip_timestamp_filter message is used by a node to request
663 /// gossip relay for messages in the requested time range when the
664 /// gossip_queries feature has been negotiated.
665 #[derive(Clone, Debug, PartialEq)]
666 pub struct GossipTimestampFilter {
667 /// The genesis hash of the blockchain for channel and node information
668 pub chain_hash: BlockHash,
669 /// The starting unix timestamp
670 pub first_timestamp: u32,
671 /// The range of information in seconds
672 pub timestamp_range: u32,
675 /// Encoding type for data compression of collections in gossip queries.
676 /// We do not support encoding_type=1 zlib serialization defined in BOLT #7.
681 /// Used to put an error message in a LightningError
682 #[derive(Clone, Debug)]
683 pub enum ErrorAction {
684 /// The peer took some action which made us think they were useless. Disconnect them.
686 /// An error message which we should make an effort to send before we disconnect.
687 msg: Option<ErrorMessage>
689 /// The peer did something harmless that we weren't able to process, just log and ignore
691 /// The peer did something incorrect. Tell them.
693 /// The message to send.
698 /// An Err type for failure to process messages.
699 #[derive(Clone, Debug)]
700 pub struct LightningError {
701 /// A human-readable message describing the error
703 /// The action which should be taken against the offending peer.
704 pub action: ErrorAction,
707 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
708 /// transaction updates if they were pending.
709 #[derive(Clone, Debug, PartialEq)]
710 pub struct CommitmentUpdate {
711 /// update_add_htlc messages which should be sent
712 pub update_add_htlcs: Vec<UpdateAddHTLC>,
713 /// update_fulfill_htlc messages which should be sent
714 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
715 /// update_fail_htlc messages which should be sent
716 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
717 /// update_fail_malformed_htlc messages which should be sent
718 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
719 /// An update_fee message which should be sent
720 pub update_fee: Option<UpdateFee>,
721 /// Finally, the commitment_signed message which should be sent
722 pub commitment_signed: CommitmentSigned,
725 /// The information we received from a peer along the route of a payment we originated. This is
726 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
727 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
728 #[derive(Clone, Debug, PartialEq)]
729 pub enum HTLCFailChannelUpdate {
730 /// We received an error which included a full ChannelUpdate message.
731 ChannelUpdateMessage {
732 /// The unwrapped message we received
735 /// We received an error which indicated only that a channel has been closed
737 /// The short_channel_id which has now closed.
738 short_channel_id: u64,
739 /// when this true, this channel should be permanently removed from the
740 /// consideration. Otherwise, this channel can be restored as new channel_update is received
743 /// We received an error which indicated only that a node has failed
745 /// The node_id that has failed.
747 /// when this true, node should be permanently removed from the
748 /// consideration. Otherwise, the channels connected to this node can be
749 /// restored as new channel_update is received
754 /// Messages could have optional fields to use with extended features
755 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
756 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
757 /// separate enum type for them.
758 /// (C-not exported) due to a free generic in T
759 #[derive(Clone, Debug, PartialEq)]
760 pub enum OptionalField<T> {
761 /// Optional field is included in message
763 /// Optional field is absent in message
767 /// A trait to describe an object which can receive channel messages.
769 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
770 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
771 pub trait ChannelMessageHandler : MessageSendEventsProvider {
773 /// Handle an incoming open_channel message from the given peer.
774 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
775 /// Handle an incoming accept_channel message from the given peer.
776 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
777 /// Handle an incoming funding_created message from the given peer.
778 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
779 /// Handle an incoming funding_signed message from the given peer.
780 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
781 /// Handle an incoming funding_locked message from the given peer.
782 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
785 /// Handle an incoming shutdown message from the given peer.
786 fn handle_shutdown(&self, their_node_id: &PublicKey, their_features: &InitFeatures, msg: &Shutdown);
787 /// Handle an incoming closing_signed message from the given peer.
788 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
791 /// Handle an incoming update_add_htlc message from the given peer.
792 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
793 /// Handle an incoming update_fulfill_htlc message from the given peer.
794 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
795 /// Handle an incoming update_fail_htlc message from the given peer.
796 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
797 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
798 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
799 /// Handle an incoming commitment_signed message from the given peer.
800 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
801 /// Handle an incoming revoke_and_ack message from the given peer.
802 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
804 /// Handle an incoming update_fee message from the given peer.
805 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
807 // Channel-to-announce:
808 /// Handle an incoming announcement_signatures message from the given peer.
809 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
811 // Connection loss/reestablish:
812 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
813 /// is believed to be possible in the future (eg they're sending us messages we don't
814 /// understand or indicate they require unknown feature bits), no_connection_possible is set
815 /// and any outstanding channels should be failed.
816 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
818 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
819 fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init);
820 /// Handle an incoming channel_reestablish message from the given peer.
821 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
823 /// Handle an incoming channel update from the given peer.
824 fn handle_channel_update(&self, their_node_id: &PublicKey, msg: &ChannelUpdate);
827 /// Handle an incoming error message from the given peer.
828 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
831 /// A trait to describe an object which can receive routing messages.
833 /// # Implementor DoS Warnings
835 /// For `gossip_queries` messages there are potential DoS vectors when handling
836 /// inbound queries. Implementors using an on-disk network graph should be aware of
837 /// repeated disk I/O for queries accessing different parts of the network graph.
838 pub trait RoutingMessageHandler : MessageSendEventsProvider {
839 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
840 /// false or returning an Err otherwise.
841 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
842 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
843 /// or returning an Err otherwise.
844 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
845 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
846 /// false or returning an Err otherwise.
847 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
848 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
849 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
850 /// Gets a subset of the channel announcements and updates required to dump our routing table
851 /// to a remote node, starting at the short_channel_id indicated by starting_point and
852 /// including the batch_amount entries immediately higher in numerical value than starting_point.
853 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
854 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
855 /// starting at the node *after* the provided publickey and including batch_amount entries
856 /// immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
857 /// If None is provided for starting_point, we start at the first node.
858 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
859 /// Called when a connection is established with a peer. This can be used to
860 /// perform routing table synchronization using a strategy defined by the
862 fn sync_routing_table(&self, their_node_id: &PublicKey, init: &Init);
863 /// Handles the reply of a query we initiated to learn about channels
864 /// for a given range of blocks. We can expect to receive one or more
865 /// replies to a single query.
866 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError>;
867 /// Handles the reply of a query we initiated asking for routing gossip
868 /// messages for a list of channels. We should receive this message when
869 /// a node has completed its best effort to send us the pertaining routing
871 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError>;
872 /// Handles when a peer asks us to send a list of short_channel_ids
873 /// for the requested range of blocks.
874 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError>;
875 /// Handles when a peer asks us to send routing gossip messages for a
876 /// list of short_channel_ids.
877 fn handle_query_short_channel_ids(&self, their_node_id: &PublicKey, msg: QueryShortChannelIds) -> Result<(), LightningError>;
880 mod fuzzy_internal_msgs {
881 use ln::PaymentSecret;
883 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
884 // them from untrusted input):
886 pub(crate) struct FinalOnionHopData {
887 pub(crate) payment_secret: PaymentSecret,
888 /// The total value, in msat, of the payment as received by the ultimate recipient.
889 /// Message serialization may panic if this value is more than 21 million Bitcoin.
890 pub(crate) total_msat: u64,
893 pub(crate) enum OnionHopDataFormat {
894 Legacy { // aka Realm-0
895 short_channel_id: u64,
898 short_channel_id: u64,
901 payment_data: Option<FinalOnionHopData>,
905 pub struct OnionHopData {
906 pub(crate) format: OnionHopDataFormat,
907 /// The value, in msat, of the payment after this hop's fee is deducted.
908 /// Message serialization may panic if this value is more than 21 million Bitcoin.
909 pub(crate) amt_to_forward: u64,
910 pub(crate) outgoing_cltv_value: u32,
911 // 12 bytes of 0-padding for Legacy format
914 pub struct DecodedOnionErrorPacket {
915 pub(crate) hmac: [u8; 32],
916 pub(crate) failuremsg: Vec<u8>,
917 pub(crate) pad: Vec<u8>,
920 #[cfg(feature = "fuzztarget")]
921 pub use self::fuzzy_internal_msgs::*;
922 #[cfg(not(feature = "fuzztarget"))]
923 pub(crate) use self::fuzzy_internal_msgs::*;
926 pub(crate) struct OnionPacket {
927 pub(crate) version: u8,
928 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
929 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
930 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
931 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
932 pub(crate) hop_data: [u8; 20*65],
933 pub(crate) hmac: [u8; 32],
936 impl PartialEq for OnionPacket {
937 fn eq(&self, other: &OnionPacket) -> bool {
938 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
939 if i != j { return false; }
941 self.version == other.version &&
942 self.public_key == other.public_key &&
943 self.hmac == other.hmac
947 impl fmt::Debug for OnionPacket {
948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
949 f.write_fmt(format_args!("OnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
953 #[derive(Clone, Debug, PartialEq)]
954 pub(crate) struct OnionErrorPacket {
955 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
956 // (TODO) We limit it in decode to much lower...
957 pub(crate) data: Vec<u8>,
960 impl fmt::Display for DecodeError {
961 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
963 DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
964 DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
965 DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
966 DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
967 DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
968 DecodeError::Io(ref e) => e.fmt(f),
969 DecodeError::UnsupportedCompression => f.write_str("We don't support receiving messages with zlib-compressed fields"),
974 impl From<::std::io::Error> for DecodeError {
975 fn from(e: ::std::io::Error) -> Self {
976 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
977 DecodeError::ShortRead
979 DecodeError::Io(e.kind())
984 impl Writeable for OptionalField<Script> {
985 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
987 OptionalField::Present(ref script) => {
988 // Note that Writeable for script includes the 16-bit length tag for us
991 OptionalField::Absent => {}
997 impl Readable for OptionalField<Script> {
998 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
999 match <u16 as Readable>::read(r) {
1001 let mut buf = vec![0; len as usize];
1002 r.read_exact(&mut buf)?;
1003 Ok(OptionalField::Present(Script::from(buf)))
1005 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
1011 impl Writeable for OptionalField<u64> {
1012 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1014 OptionalField::Present(ref value) => {
1017 OptionalField::Absent => {}
1023 impl Readable for OptionalField<u64> {
1024 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1025 let value: u64 = Readable::read(r)?;
1026 Ok(OptionalField::Present(value))
1031 impl_writeable_len_match!(AcceptChannel, {
1032 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
1035 temporary_channel_id,
1036 dust_limit_satoshis,
1037 max_htlc_value_in_flight_msat,
1038 channel_reserve_satoshis,
1044 revocation_basepoint,
1046 delayed_payment_basepoint,
1048 first_per_commitment_point,
1049 shutdown_scriptpubkey
1052 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
1059 impl Writeable for ChannelReestablish {
1060 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1061 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
1062 self.channel_id.write(w)?;
1063 self.next_local_commitment_number.write(w)?;
1064 self.next_remote_commitment_number.write(w)?;
1065 match self.data_loss_protect {
1066 OptionalField::Present(ref data_loss_protect) => {
1067 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
1068 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
1070 OptionalField::Absent => {}
1076 impl Readable for ChannelReestablish{
1077 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1079 channel_id: Readable::read(r)?,
1080 next_local_commitment_number: Readable::read(r)?,
1081 next_remote_commitment_number: Readable::read(r)?,
1082 data_loss_protect: {
1083 match <[u8; 32] as Readable>::read(r) {
1084 Ok(your_last_per_commitment_secret) =>
1085 OptionalField::Present(DataLossProtect {
1086 your_last_per_commitment_secret,
1087 my_current_per_commitment_point: Readable::read(r)?,
1089 Err(DecodeError::ShortRead) => OptionalField::Absent,
1090 Err(e) => return Err(e)
1097 impl_writeable!(ClosingSigned, 32+8+64, {
1103 impl_writeable_len_match!(CommitmentSigned, {
1104 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
1111 impl_writeable_len_match!(DecodedOnionErrorPacket, {
1112 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
1119 impl_writeable!(FundingCreated, 32+32+2+64, {
1120 temporary_channel_id,
1122 funding_output_index,
1126 impl_writeable!(FundingSigned, 32+64, {
1131 impl_writeable!(FundingLocked, 32+33, {
1133 next_per_commitment_point
1136 impl Writeable for Init {
1137 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1138 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1139 // our relevant feature bits. This keeps us compatible with old nodes.
1140 self.features.write_up_to_13(w)?;
1141 self.features.write(w)
1145 impl Readable for Init {
1146 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1147 let global_features: InitFeatures = Readable::read(r)?;
1148 let features: InitFeatures = Readable::read(r)?;
1150 features: features.or(global_features),
1155 impl_writeable_len_match!(OpenChannel, {
1156 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
1160 temporary_channel_id,
1163 dust_limit_satoshis,
1164 max_htlc_value_in_flight_msat,
1165 channel_reserve_satoshis,
1171 revocation_basepoint,
1173 delayed_payment_basepoint,
1175 first_per_commitment_point,
1177 shutdown_scriptpubkey
1180 impl_writeable!(RevokeAndACK, 32+32+33, {
1182 per_commitment_secret,
1183 next_per_commitment_point
1186 impl_writeable_len_match!(Shutdown, {
1187 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
1193 impl_writeable_len_match!(UpdateFailHTLC, {
1194 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
1201 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
1208 impl_writeable!(UpdateFee, 32+4, {
1213 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1219 impl_writeable_len_match!(OnionErrorPacket, {
1220 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1225 impl Writeable for OnionPacket {
1226 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1227 w.size_hint(1 + 33 + 20*65 + 32);
1228 self.version.write(w)?;
1229 match self.public_key {
1230 Ok(pubkey) => pubkey.write(w)?,
1231 Err(_) => [0u8;33].write(w)?,
1233 w.write_all(&self.hop_data)?;
1234 self.hmac.write(w)?;
1239 impl Readable for OnionPacket {
1240 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1242 version: Readable::read(r)?,
1244 let mut buf = [0u8;33];
1245 r.read_exact(&mut buf)?;
1246 PublicKey::from_slice(&buf)
1248 hop_data: Readable::read(r)?,
1249 hmac: Readable::read(r)?,
1254 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1260 onion_routing_packet
1263 impl Writeable for FinalOnionHopData {
1264 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1265 w.size_hint(32 + 8 - (self.total_msat.leading_zeros()/8) as usize);
1266 self.payment_secret.0.write(w)?;
1267 HighZeroBytesDroppedVarInt(self.total_msat).write(w)
1271 impl Readable for FinalOnionHopData {
1272 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1273 let secret: [u8; 32] = Readable::read(r)?;
1274 let amt: HighZeroBytesDroppedVarInt<u64> = Readable::read(r)?;
1275 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
1279 impl Writeable for OnionHopData {
1280 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1282 // Note that this should never be reachable if Rust-Lightning generated the message, as we
1283 // check values are sane long before we get here, though its possible in the future
1284 // user-generated messages may hit this.
1285 if self.amt_to_forward > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1287 OnionHopDataFormat::Legacy { short_channel_id } => {
1289 short_channel_id.write(w)?;
1290 self.amt_to_forward.write(w)?;
1291 self.outgoing_cltv_value.write(w)?;
1292 w.write_all(&[0;12])?;
1294 OnionHopDataFormat::NonFinalNode { short_channel_id } => {
1295 encode_varint_length_prefixed_tlv!(w, {
1296 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1297 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1298 (6, short_channel_id)
1301 OnionHopDataFormat::FinalNode { ref payment_data } => {
1302 if let Some(final_data) = payment_data {
1303 if final_data.total_msat > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1305 encode_varint_length_prefixed_tlv!(w, {
1306 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1307 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
1317 impl Readable for OnionHopData {
1318 fn read<R: Read>(mut r: &mut R) -> Result<Self, DecodeError> {
1319 use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1320 let v: VarInt = Decodable::consensus_decode(&mut r)
1321 .map_err(|e| match e {
1322 Error::Io(ioe) => DecodeError::from(ioe),
1323 _ => DecodeError::InvalidValue
1325 const LEGACY_ONION_HOP_FLAG: u64 = 0;
1326 let (format, amt, cltv_value) = if v.0 != LEGACY_ONION_HOP_FLAG {
1327 let mut rd = FixedLengthReader::new(r, v.0);
1328 let mut amt = HighZeroBytesDroppedVarInt(0u64);
1329 let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
1330 let mut short_id: Option<u64> = None;
1331 let mut payment_data: Option<FinalOnionHopData> = None;
1332 decode_tlv!(&mut rd, {
1339 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1340 let format = if let Some(short_channel_id) = short_id {
1341 if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
1342 OnionHopDataFormat::NonFinalNode {
1346 if let &Some(ref data) = &payment_data {
1347 if data.total_msat > MAX_VALUE_MSAT {
1348 return Err(DecodeError::InvalidValue);
1351 OnionHopDataFormat::FinalNode {
1355 (format, amt.0, cltv_value.0)
1357 let format = OnionHopDataFormat::Legacy {
1358 short_channel_id: Readable::read(r)?,
1360 let amt: u64 = Readable::read(r)?;
1361 let cltv_value: u32 = Readable::read(r)?;
1362 r.read_exact(&mut [0; 12])?;
1363 (format, amt, cltv_value)
1366 if amt > MAX_VALUE_MSAT {
1367 return Err(DecodeError::InvalidValue);
1371 amt_to_forward: amt,
1372 outgoing_cltv_value: cltv_value,
1377 impl Writeable for Ping {
1378 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1379 w.size_hint(self.byteslen as usize + 4);
1380 self.ponglen.write(w)?;
1381 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1386 impl Readable for Ping {
1387 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1389 ponglen: Readable::read(r)?,
1391 let byteslen = Readable::read(r)?;
1392 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1399 impl Writeable for Pong {
1400 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1401 w.size_hint(self.byteslen as usize + 2);
1402 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1407 impl Readable for Pong {
1408 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1411 let byteslen = Readable::read(r)?;
1412 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1419 impl Writeable for UnsignedChannelAnnouncement {
1420 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1421 w.size_hint(2 + 32 + 8 + 4*33 + self.features.byte_count() + self.excess_data.len());
1422 self.features.write(w)?;
1423 self.chain_hash.write(w)?;
1424 self.short_channel_id.write(w)?;
1425 self.node_id_1.write(w)?;
1426 self.node_id_2.write(w)?;
1427 self.bitcoin_key_1.write(w)?;
1428 self.bitcoin_key_2.write(w)?;
1429 w.write_all(&self.excess_data[..])?;
1434 impl Readable for UnsignedChannelAnnouncement {
1435 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1437 features: Readable::read(r)?,
1438 chain_hash: Readable::read(r)?,
1439 short_channel_id: Readable::read(r)?,
1440 node_id_1: Readable::read(r)?,
1441 node_id_2: Readable::read(r)?,
1442 bitcoin_key_1: Readable::read(r)?,
1443 bitcoin_key_2: Readable::read(r)?,
1445 let mut excess_data = vec![];
1446 r.read_to_end(&mut excess_data)?;
1453 impl_writeable_len_match!(ChannelAnnouncement, {
1454 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1455 2 + 32 + 8 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1459 bitcoin_signature_1,
1460 bitcoin_signature_2,
1464 impl Writeable for UnsignedChannelUpdate {
1465 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1466 let mut size = 64 + self.excess_data.len();
1467 let mut message_flags: u8 = 0;
1468 if let OptionalField::Present(_) = self.htlc_maximum_msat {
1473 self.chain_hash.write(w)?;
1474 self.short_channel_id.write(w)?;
1475 self.timestamp.write(w)?;
1476 let all_flags = self.flags as u16 | ((message_flags as u16) << 8);
1477 all_flags.write(w)?;
1478 self.cltv_expiry_delta.write(w)?;
1479 self.htlc_minimum_msat.write(w)?;
1480 self.fee_base_msat.write(w)?;
1481 self.fee_proportional_millionths.write(w)?;
1482 self.htlc_maximum_msat.write(w)?;
1483 w.write_all(&self.excess_data[..])?;
1488 impl Readable for UnsignedChannelUpdate {
1489 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1490 let has_htlc_maximum_msat;
1492 chain_hash: Readable::read(r)?,
1493 short_channel_id: Readable::read(r)?,
1494 timestamp: Readable::read(r)?,
1496 let flags: u16 = Readable::read(r)?;
1497 let message_flags = flags >> 8;
1498 has_htlc_maximum_msat = (message_flags as i32 & 1) == 1;
1501 cltv_expiry_delta: Readable::read(r)?,
1502 htlc_minimum_msat: Readable::read(r)?,
1503 fee_base_msat: Readable::read(r)?,
1504 fee_proportional_millionths: Readable::read(r)?,
1505 htlc_maximum_msat: if has_htlc_maximum_msat { Readable::read(r)? } else { OptionalField::Absent },
1507 let mut excess_data = vec![];
1508 r.read_to_end(&mut excess_data)?;
1515 impl_writeable_len_match!(ChannelUpdate, {
1516 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ref htlc_maximum_msat, ..}, .. },
1517 64 + 64 + excess_data.len() + if let OptionalField::Present(_) = htlc_maximum_msat { 8 } else { 0 } }
1523 impl Writeable for ErrorMessage {
1524 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1525 w.size_hint(32 + 2 + self.data.len());
1526 self.channel_id.write(w)?;
1527 (self.data.len() as u16).write(w)?;
1528 w.write_all(self.data.as_bytes())?;
1533 impl Readable for ErrorMessage {
1534 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1536 channel_id: Readable::read(r)?,
1538 let mut sz: usize = <u16 as Readable>::read(r)? as usize;
1539 let mut data = vec![];
1540 let data_len = r.read_to_end(&mut data)?;
1541 sz = cmp::min(data_len, sz);
1542 match String::from_utf8(data[..sz as usize].to_vec()) {
1544 Err(_) => return Err(DecodeError::InvalidValue),
1551 impl Writeable for UnsignedNodeAnnouncement {
1552 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1553 w.size_hint(76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1554 self.features.write(w)?;
1555 self.timestamp.write(w)?;
1556 self.node_id.write(w)?;
1557 w.write_all(&self.rgb)?;
1558 self.alias.write(w)?;
1560 let mut addr_len = 0;
1561 for addr in self.addresses.iter() {
1562 addr_len += 1 + addr.len();
1564 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1565 for addr in self.addresses.iter() {
1568 w.write_all(&self.excess_address_data[..])?;
1569 w.write_all(&self.excess_data[..])?;
1574 impl Readable for UnsignedNodeAnnouncement {
1575 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1576 let features: NodeFeatures = Readable::read(r)?;
1577 let timestamp: u32 = Readable::read(r)?;
1578 let node_id: PublicKey = Readable::read(r)?;
1579 let mut rgb = [0; 3];
1580 r.read_exact(&mut rgb)?;
1581 let alias: [u8; 32] = Readable::read(r)?;
1583 let addr_len: u16 = Readable::read(r)?;
1584 let mut addresses: Vec<NetAddress> = Vec::new();
1585 let mut addr_readpos = 0;
1586 let mut excess = false;
1587 let mut excess_byte = 0;
1589 if addr_len <= addr_readpos { break; }
1590 match Readable::read(r) {
1592 if addr_len < addr_readpos + 1 + addr.len() {
1593 return Err(DecodeError::BadLengthDescriptor);
1595 addr_readpos += (1 + addr.len()) as u16;
1596 addresses.push(addr);
1598 Ok(Err(unknown_descriptor)) => {
1600 excess_byte = unknown_descriptor;
1603 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1604 Err(e) => return Err(e),
1608 let mut excess_data = vec![];
1609 let excess_address_data = if addr_readpos < addr_len {
1610 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1611 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1613 excess_address_data[0] = excess_byte;
1618 excess_data.push(excess_byte);
1622 r.read_to_end(&mut excess_data)?;
1623 Ok(UnsignedNodeAnnouncement {
1630 excess_address_data,
1636 impl_writeable_len_match!(NodeAnnouncement, <=, {
1637 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1638 64 + 76 + features.byte_count() + addresses.len()*(NetAddress::MAX_LEN as usize + 1) + excess_address_data.len() + excess_data.len() }
1644 impl Readable for QueryShortChannelIds {
1645 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1646 let chain_hash: BlockHash = Readable::read(r)?;
1648 let encoding_len: u16 = Readable::read(r)?;
1649 let encoding_type: u8 = Readable::read(r)?;
1651 // Must be encoding_type=0 uncompressed serialization. We do not
1652 // support encoding_type=1 zlib serialization.
1653 if encoding_type != EncodingType::Uncompressed as u8 {
1654 return Err(DecodeError::UnsupportedCompression);
1657 // We expect the encoding_len to always includes the 1-byte
1658 // encoding_type and that short_channel_ids are 8-bytes each
1659 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1660 return Err(DecodeError::InvalidValue);
1663 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1664 // less the 1-byte encoding_type
1665 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1666 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1667 for _ in 0..short_channel_id_count {
1668 short_channel_ids.push(Readable::read(r)?);
1671 Ok(QueryShortChannelIds {
1678 impl Writeable for QueryShortChannelIds {
1679 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1680 // Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
1681 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1683 w.size_hint(32 + 2 + encoding_len as usize);
1684 self.chain_hash.write(w)?;
1685 encoding_len.write(w)?;
1687 // We only support type=0 uncompressed serialization
1688 (EncodingType::Uncompressed as u8).write(w)?;
1690 for scid in self.short_channel_ids.iter() {
1698 impl Readable for ReplyShortChannelIdsEnd {
1699 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1700 let chain_hash: BlockHash = Readable::read(r)?;
1701 let full_information: bool = Readable::read(r)?;
1702 Ok(ReplyShortChannelIdsEnd {
1709 impl Writeable for ReplyShortChannelIdsEnd {
1710 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1711 w.size_hint(32 + 1);
1712 self.chain_hash.write(w)?;
1713 self.full_information.write(w)?;
1718 impl QueryChannelRange {
1720 * Calculates the overflow safe ending block height for the query.
1721 * Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`
1723 pub fn end_blocknum(&self) -> u32 {
1724 match self.first_blocknum.checked_add(self.number_of_blocks) {
1725 Some(block) => block,
1726 None => u32::max_value(),
1731 impl Readable for QueryChannelRange {
1732 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1733 let chain_hash: BlockHash = Readable::read(r)?;
1734 let first_blocknum: u32 = Readable::read(r)?;
1735 let number_of_blocks: u32 = Readable::read(r)?;
1736 Ok(QueryChannelRange {
1744 impl Writeable for QueryChannelRange {
1745 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1746 w.size_hint(32 + 4 + 4);
1747 self.chain_hash.write(w)?;
1748 self.first_blocknum.write(w)?;
1749 self.number_of_blocks.write(w)?;
1754 impl Readable for ReplyChannelRange {
1755 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1756 let chain_hash: BlockHash = Readable::read(r)?;
1757 let first_blocknum: u32 = Readable::read(r)?;
1758 let number_of_blocks: u32 = Readable::read(r)?;
1759 let sync_complete: bool = Readable::read(r)?;
1761 let encoding_len: u16 = Readable::read(r)?;
1762 let encoding_type: u8 = Readable::read(r)?;
1764 // Must be encoding_type=0 uncompressed serialization. We do not
1765 // support encoding_type=1 zlib serialization.
1766 if encoding_type != EncodingType::Uncompressed as u8 {
1767 return Err(DecodeError::UnsupportedCompression);
1770 // We expect the encoding_len to always includes the 1-byte
1771 // encoding_type and that short_channel_ids are 8-bytes each
1772 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1773 return Err(DecodeError::InvalidValue);
1776 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1777 // less the 1-byte encoding_type
1778 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1779 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1780 for _ in 0..short_channel_id_count {
1781 short_channel_ids.push(Readable::read(r)?);
1784 Ok(ReplyChannelRange {
1794 impl Writeable for ReplyChannelRange {
1795 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1796 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1797 w.size_hint(32 + 4 + 4 + 1 + 2 + encoding_len as usize);
1798 self.chain_hash.write(w)?;
1799 self.first_blocknum.write(w)?;
1800 self.number_of_blocks.write(w)?;
1801 self.sync_complete.write(w)?;
1803 encoding_len.write(w)?;
1804 (EncodingType::Uncompressed as u8).write(w)?;
1805 for scid in self.short_channel_ids.iter() {
1813 impl Readable for GossipTimestampFilter {
1814 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1815 let chain_hash: BlockHash = Readable::read(r)?;
1816 let first_timestamp: u32 = Readable::read(r)?;
1817 let timestamp_range: u32 = Readable::read(r)?;
1818 Ok(GossipTimestampFilter {
1826 impl Writeable for GossipTimestampFilter {
1827 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1828 w.size_hint(32 + 4 + 4);
1829 self.chain_hash.write(w)?;
1830 self.first_timestamp.write(w)?;
1831 self.timestamp_range.write(w)?;
1840 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
1842 use ln::msgs::{ChannelFeatures, FinalOnionHopData, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1843 use util::ser::{Writeable, Readable};
1845 use bitcoin::hashes::hex::FromHex;
1846 use bitcoin::util::address::Address;
1847 use bitcoin::network::constants::Network;
1848 use bitcoin::blockdata::script::Builder;
1849 use bitcoin::blockdata::opcodes;
1850 use bitcoin::hash_types::{Txid, BlockHash};
1852 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1853 use bitcoin::secp256k1::{Secp256k1, Message};
1855 use std::io::Cursor;
1858 fn encoding_channel_reestablish_no_secret() {
1859 let cr = msgs::ChannelReestablish {
1860 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],
1861 next_local_commitment_number: 3,
1862 next_remote_commitment_number: 4,
1863 data_loss_protect: OptionalField::Absent,
1866 let encoded_value = cr.encode();
1869 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]
1874 fn encoding_channel_reestablish_with_secret() {
1876 let secp_ctx = Secp256k1::new();
1877 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1880 let cr = msgs::ChannelReestablish {
1881 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],
1882 next_local_commitment_number: 3,
1883 next_remote_commitment_number: 4,
1884 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1887 let encoded_value = cr.encode();
1890 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]
1894 macro_rules! get_keys_from {
1895 ($slice: expr, $secp_ctx: expr) => {
1897 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1898 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1904 macro_rules! get_sig_on {
1905 ($privkey: expr, $ctx: expr, $string: expr) => {
1907 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1908 $ctx.sign(&sighash, &$privkey)
1914 fn encoding_announcement_signatures() {
1915 let secp_ctx = Secp256k1::new();
1916 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1917 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1918 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1919 let announcement_signatures = msgs::AnnouncementSignatures {
1920 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],
1921 short_channel_id: 2316138423780173,
1922 node_signature: sig_1,
1923 bitcoin_signature: sig_2,
1926 let encoded_value = announcement_signatures.encode();
1927 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1930 fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
1931 let secp_ctx = Secp256k1::new();
1932 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1933 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1934 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1935 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1936 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1937 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1938 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1939 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1940 let mut features = ChannelFeatures::known();
1941 if unknown_features_bits {
1942 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
1944 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1946 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
1947 short_channel_id: 2316138423780173,
1948 node_id_1: pubkey_1,
1949 node_id_2: pubkey_2,
1950 bitcoin_key_1: pubkey_3,
1951 bitcoin_key_2: pubkey_4,
1952 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1954 let channel_announcement = msgs::ChannelAnnouncement {
1955 node_signature_1: sig_1,
1956 node_signature_2: sig_2,
1957 bitcoin_signature_1: sig_3,
1958 bitcoin_signature_2: sig_4,
1959 contents: unsigned_channel_announcement,
1961 let encoded_value = channel_announcement.encode();
1962 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1963 if unknown_features_bits {
1964 target_value.append(&mut hex::decode("0002ffff").unwrap());
1966 target_value.append(&mut hex::decode("0000").unwrap());
1968 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1969 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1971 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1973 assert_eq!(encoded_value, target_value);
1977 fn encoding_channel_announcement() {
1978 do_encoding_channel_announcement(true, false);
1979 do_encoding_channel_announcement(false, true);
1980 do_encoding_channel_announcement(false, false);
1981 do_encoding_channel_announcement(true, true);
1984 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1985 let secp_ctx = Secp256k1::new();
1986 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1987 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1988 let features = if unknown_features_bits {
1989 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
1991 // Set to some features we may support
1992 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
1994 let mut addresses = Vec::new();
1996 addresses.push(msgs::NetAddress::IPv4 {
1997 addr: [255, 254, 253, 252],
2002 addresses.push(msgs::NetAddress::IPv6 {
2003 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
2008 addresses.push(msgs::NetAddress::OnionV2 {
2009 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
2014 addresses.push(msgs::NetAddress::OnionV3 {
2015 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],
2021 let mut addr_len = 0;
2022 for addr in &addresses {
2023 addr_len += addr.len() + 1;
2025 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
2027 timestamp: 20190119,
2032 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() },
2033 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() },
2035 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
2036 let node_announcement = msgs::NodeAnnouncement {
2038 contents: unsigned_node_announcement,
2040 let encoded_value = node_announcement.encode();
2041 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2042 if unknown_features_bits {
2043 target_value.append(&mut hex::decode("0002ffff").unwrap());
2045 target_value.append(&mut hex::decode("000122").unwrap());
2047 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
2048 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
2050 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
2053 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
2056 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
2059 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
2061 if excess_address_data {
2062 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
2065 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2067 assert_eq!(encoded_value, target_value);
2071 fn encoding_node_announcement() {
2072 do_encoding_node_announcement(true, true, true, true, true, true, true);
2073 do_encoding_node_announcement(false, false, false, false, false, false, false);
2074 do_encoding_node_announcement(false, true, false, false, false, false, false);
2075 do_encoding_node_announcement(false, false, true, false, false, false, false);
2076 do_encoding_node_announcement(false, false, false, true, false, false, false);
2077 do_encoding_node_announcement(false, false, false, false, true, false, false);
2078 do_encoding_node_announcement(false, false, false, false, false, true, false);
2079 do_encoding_node_announcement(false, true, false, true, false, true, false);
2080 do_encoding_node_announcement(false, false, true, false, true, false, false);
2083 fn do_encoding_channel_update(direction: bool, disable: bool, htlc_maximum_msat: bool, excess_data: bool) {
2084 let secp_ctx = Secp256k1::new();
2085 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2086 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2087 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
2088 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2089 short_channel_id: 2316138423780173,
2090 timestamp: 20190119,
2091 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
2092 cltv_expiry_delta: 144,
2093 htlc_minimum_msat: 1000000,
2094 htlc_maximum_msat: if htlc_maximum_msat { OptionalField::Present(131355275467161) } else { OptionalField::Absent },
2095 fee_base_msat: 10000,
2096 fee_proportional_millionths: 20,
2097 excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
2099 let channel_update = msgs::ChannelUpdate {
2101 contents: unsigned_channel_update
2103 let encoded_value = channel_update.encode();
2104 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2105 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2106 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
2107 if htlc_maximum_msat {
2108 target_value.append(&mut hex::decode("01").unwrap());
2110 target_value.append(&mut hex::decode("00").unwrap());
2112 target_value.append(&mut hex::decode("00").unwrap());
2114 let flag = target_value.last_mut().unwrap();
2118 let flag = target_value.last_mut().unwrap();
2119 *flag = *flag | 1 << 1;
2121 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
2122 if htlc_maximum_msat {
2123 target_value.append(&mut hex::decode("0000777788889999").unwrap());
2126 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
2128 assert_eq!(encoded_value, target_value);
2132 fn encoding_channel_update() {
2133 do_encoding_channel_update(false, false, false, false);
2134 do_encoding_channel_update(false, false, false, true);
2135 do_encoding_channel_update(true, false, false, false);
2136 do_encoding_channel_update(true, false, false, true);
2137 do_encoding_channel_update(false, true, false, false);
2138 do_encoding_channel_update(false, true, false, true);
2139 do_encoding_channel_update(false, false, true, false);
2140 do_encoding_channel_update(false, false, true, true);
2141 do_encoding_channel_update(true, true, true, false);
2142 do_encoding_channel_update(true, true, true, true);
2145 fn do_encoding_open_channel(random_bit: bool, shutdown: bool) {
2146 let secp_ctx = Secp256k1::new();
2147 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2148 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2149 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2150 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2151 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2152 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2153 let open_channel = msgs::OpenChannel {
2154 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2155 temporary_channel_id: [2; 32],
2156 funding_satoshis: 1311768467284833366,
2157 push_msat: 2536655962884945560,
2158 dust_limit_satoshis: 3608586615801332854,
2159 max_htlc_value_in_flight_msat: 8517154655701053848,
2160 channel_reserve_satoshis: 8665828695742877976,
2161 htlc_minimum_msat: 2316138423780173,
2162 feerate_per_kw: 821716,
2163 to_self_delay: 49340,
2164 max_accepted_htlcs: 49340,
2165 funding_pubkey: pubkey_1,
2166 revocation_basepoint: pubkey_2,
2167 payment_point: pubkey_3,
2168 delayed_payment_basepoint: pubkey_4,
2169 htlc_basepoint: pubkey_5,
2170 first_per_commitment_point: pubkey_6,
2171 channel_flags: if random_bit { 1 << 5 } else { 0 },
2172 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
2174 let encoded_value = open_channel.encode();
2175 let mut target_value = Vec::new();
2176 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2177 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
2179 target_value.append(&mut hex::decode("20").unwrap());
2181 target_value.append(&mut hex::decode("00").unwrap());
2184 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2186 assert_eq!(encoded_value, target_value);
2190 fn encoding_open_channel() {
2191 do_encoding_open_channel(false, false);
2192 do_encoding_open_channel(true, false);
2193 do_encoding_open_channel(false, true);
2194 do_encoding_open_channel(true, true);
2197 fn do_encoding_accept_channel(shutdown: bool) {
2198 let secp_ctx = Secp256k1::new();
2199 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2200 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2201 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2202 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2203 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2204 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2205 let accept_channel = msgs::AcceptChannel {
2206 temporary_channel_id: [2; 32],
2207 dust_limit_satoshis: 1311768467284833366,
2208 max_htlc_value_in_flight_msat: 2536655962884945560,
2209 channel_reserve_satoshis: 3608586615801332854,
2210 htlc_minimum_msat: 2316138423780173,
2211 minimum_depth: 821716,
2212 to_self_delay: 49340,
2213 max_accepted_htlcs: 49340,
2214 funding_pubkey: pubkey_1,
2215 revocation_basepoint: pubkey_2,
2216 payment_point: pubkey_3,
2217 delayed_payment_basepoint: pubkey_4,
2218 htlc_basepoint: pubkey_5,
2219 first_per_commitment_point: pubkey_6,
2220 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
2222 let encoded_value = accept_channel.encode();
2223 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
2225 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2227 assert_eq!(encoded_value, target_value);
2231 fn encoding_accept_channel() {
2232 do_encoding_accept_channel(false);
2233 do_encoding_accept_channel(true);
2237 fn encoding_funding_created() {
2238 let secp_ctx = Secp256k1::new();
2239 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2240 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2241 let funding_created = msgs::FundingCreated {
2242 temporary_channel_id: [2; 32],
2243 funding_txid: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
2244 funding_output_index: 255,
2247 let encoded_value = funding_created.encode();
2248 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2249 assert_eq!(encoded_value, target_value);
2253 fn encoding_funding_signed() {
2254 let secp_ctx = Secp256k1::new();
2255 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2256 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2257 let funding_signed = msgs::FundingSigned {
2258 channel_id: [2; 32],
2261 let encoded_value = funding_signed.encode();
2262 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2263 assert_eq!(encoded_value, target_value);
2267 fn encoding_funding_locked() {
2268 let secp_ctx = Secp256k1::new();
2269 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2270 let funding_locked = msgs::FundingLocked {
2271 channel_id: [2; 32],
2272 next_per_commitment_point: pubkey_1,
2274 let encoded_value = funding_locked.encode();
2275 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2276 assert_eq!(encoded_value, target_value);
2279 fn do_encoding_shutdown(script_type: u8) {
2280 let secp_ctx = Secp256k1::new();
2281 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2282 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
2283 let shutdown = msgs::Shutdown {
2284 channel_id: [2; 32],
2286 if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() }
2287 else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() }
2288 else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).unwrap().script_pubkey() }
2289 else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
2291 let encoded_value = shutdown.encode();
2292 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
2293 if script_type == 1 {
2294 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2295 } else if script_type == 2 {
2296 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
2297 } else if script_type == 3 {
2298 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
2299 } else if script_type == 4 {
2300 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
2302 assert_eq!(encoded_value, target_value);
2306 fn encoding_shutdown() {
2307 do_encoding_shutdown(1);
2308 do_encoding_shutdown(2);
2309 do_encoding_shutdown(3);
2310 do_encoding_shutdown(4);
2314 fn encoding_closing_signed() {
2315 let secp_ctx = Secp256k1::new();
2316 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2317 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2318 let closing_signed = msgs::ClosingSigned {
2319 channel_id: [2; 32],
2320 fee_satoshis: 2316138423780173,
2323 let encoded_value = closing_signed.encode();
2324 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2325 assert_eq!(encoded_value, target_value);
2329 fn encoding_update_add_htlc() {
2330 let secp_ctx = Secp256k1::new();
2331 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2332 let onion_routing_packet = msgs::OnionPacket {
2334 public_key: Ok(pubkey_1),
2335 hop_data: [1; 20*65],
2338 let update_add_htlc = msgs::UpdateAddHTLC {
2339 channel_id: [2; 32],
2340 htlc_id: 2316138423780173,
2341 amount_msat: 3608586615801332854,
2342 payment_hash: PaymentHash([1; 32]),
2343 cltv_expiry: 821716,
2344 onion_routing_packet
2346 let encoded_value = update_add_htlc.encode();
2347 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
2348 assert_eq!(encoded_value, target_value);
2352 fn encoding_update_fulfill_htlc() {
2353 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
2354 channel_id: [2; 32],
2355 htlc_id: 2316138423780173,
2356 payment_preimage: PaymentPreimage([1; 32]),
2358 let encoded_value = update_fulfill_htlc.encode();
2359 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
2360 assert_eq!(encoded_value, target_value);
2364 fn encoding_update_fail_htlc() {
2365 let reason = OnionErrorPacket {
2366 data: [1; 32].to_vec(),
2368 let update_fail_htlc = msgs::UpdateFailHTLC {
2369 channel_id: [2; 32],
2370 htlc_id: 2316138423780173,
2373 let encoded_value = update_fail_htlc.encode();
2374 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
2375 assert_eq!(encoded_value, target_value);
2379 fn encoding_update_fail_malformed_htlc() {
2380 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
2381 channel_id: [2; 32],
2382 htlc_id: 2316138423780173,
2383 sha256_of_onion: [1; 32],
2386 let encoded_value = update_fail_malformed_htlc.encode();
2387 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
2388 assert_eq!(encoded_value, target_value);
2391 fn do_encoding_commitment_signed(htlcs: bool) {
2392 let secp_ctx = Secp256k1::new();
2393 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2394 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2395 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2396 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2397 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2398 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2399 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2400 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2401 let commitment_signed = msgs::CommitmentSigned {
2402 channel_id: [2; 32],
2404 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
2406 let encoded_value = commitment_signed.encode();
2407 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2409 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2411 target_value.append(&mut hex::decode("0000").unwrap());
2413 assert_eq!(encoded_value, target_value);
2417 fn encoding_commitment_signed() {
2418 do_encoding_commitment_signed(true);
2419 do_encoding_commitment_signed(false);
2423 fn encoding_revoke_and_ack() {
2424 let secp_ctx = Secp256k1::new();
2425 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2426 let raa = msgs::RevokeAndACK {
2427 channel_id: [2; 32],
2428 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],
2429 next_per_commitment_point: pubkey_1,
2431 let encoded_value = raa.encode();
2432 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2433 assert_eq!(encoded_value, target_value);
2437 fn encoding_update_fee() {
2438 let update_fee = msgs::UpdateFee {
2439 channel_id: [2; 32],
2440 feerate_per_kw: 20190119,
2442 let encoded_value = update_fee.encode();
2443 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2444 assert_eq!(encoded_value, target_value);
2448 fn encoding_init() {
2449 assert_eq!(msgs::Init {
2450 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
2451 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2452 assert_eq!(msgs::Init {
2453 features: InitFeatures::from_le_bytes(vec![0xFF]),
2454 }.encode(), hex::decode("0001ff0001ff").unwrap());
2455 assert_eq!(msgs::Init {
2456 features: InitFeatures::from_le_bytes(vec![]),
2457 }.encode(), hex::decode("00000000").unwrap());
2461 fn encoding_error() {
2462 let error = msgs::ErrorMessage {
2463 channel_id: [2; 32],
2464 data: String::from("rust-lightning"),
2466 let encoded_value = error.encode();
2467 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2468 assert_eq!(encoded_value, target_value);
2472 fn encoding_ping() {
2473 let ping = msgs::Ping {
2477 let encoded_value = ping.encode();
2478 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2479 assert_eq!(encoded_value, target_value);
2483 fn encoding_pong() {
2484 let pong = msgs::Pong {
2487 let encoded_value = pong.encode();
2488 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2489 assert_eq!(encoded_value, target_value);
2493 fn encoding_legacy_onion_hop_data() {
2494 let msg = msgs::OnionHopData {
2495 format: OnionHopDataFormat::Legacy {
2496 short_channel_id: 0xdeadbeef1bad1dea,
2498 amt_to_forward: 0x0badf00d01020304,
2499 outgoing_cltv_value: 0xffffffff,
2501 let encoded_value = msg.encode();
2502 let target_value = hex::decode("00deadbeef1bad1dea0badf00d01020304ffffffff000000000000000000000000").unwrap();
2503 assert_eq!(encoded_value, target_value);
2507 fn encoding_nonfinal_onion_hop_data() {
2508 let mut msg = msgs::OnionHopData {
2509 format: OnionHopDataFormat::NonFinalNode {
2510 short_channel_id: 0xdeadbeef1bad1dea,
2512 amt_to_forward: 0x0badf00d01020304,
2513 outgoing_cltv_value: 0xffffffff,
2515 let encoded_value = msg.encode();
2516 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2517 assert_eq!(encoded_value, target_value);
2518 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2519 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2520 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2521 } else { panic!(); }
2522 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2523 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2527 fn encoding_final_onion_hop_data() {
2528 let mut msg = msgs::OnionHopData {
2529 format: OnionHopDataFormat::FinalNode {
2532 amt_to_forward: 0x0badf00d01020304,
2533 outgoing_cltv_value: 0xffffffff,
2535 let encoded_value = msg.encode();
2536 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2537 assert_eq!(encoded_value, target_value);
2538 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2539 if let OnionHopDataFormat::FinalNode { payment_data: None } = msg.format { } else { panic!(); }
2540 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2541 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2545 fn encoding_final_onion_hop_data_with_secret() {
2546 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
2547 let mut msg = msgs::OnionHopData {
2548 format: OnionHopDataFormat::FinalNode {
2549 payment_data: Some(FinalOnionHopData {
2550 payment_secret: expected_payment_secret,
2551 total_msat: 0x1badca1f
2554 amt_to_forward: 0x0badf00d01020304,
2555 outgoing_cltv_value: 0xffffffff,
2557 let encoded_value = msg.encode();
2558 let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
2559 assert_eq!(encoded_value, target_value);
2560 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2561 if let OnionHopDataFormat::FinalNode {
2562 payment_data: Some(FinalOnionHopData {
2564 total_msat: 0x1badca1f
2567 assert_eq!(payment_secret, expected_payment_secret);
2568 } else { panic!(); }
2569 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2570 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2574 fn query_channel_range_end_blocknum() {
2575 let tests: Vec<(u32, u32, u32)> = vec![
2576 (10000, 1500, 11500),
2577 (0, 0xffffffff, 0xffffffff),
2578 (1, 0xffffffff, 0xffffffff),
2581 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
2582 let sut = msgs::QueryChannelRange {
2583 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2587 assert_eq!(sut.end_blocknum(), expected);
2592 fn encoding_query_channel_range() {
2593 let mut query_channel_range = msgs::QueryChannelRange {
2594 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2595 first_blocknum: 100000,
2596 number_of_blocks: 1500,
2598 let encoded_value = query_channel_range.encode();
2599 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000186a0000005dc").unwrap();
2600 assert_eq!(encoded_value, target_value);
2602 query_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2603 assert_eq!(query_channel_range.first_blocknum, 100000);
2604 assert_eq!(query_channel_range.number_of_blocks, 1500);
2608 fn encoding_reply_channel_range() {
2609 do_encoding_reply_channel_range(0);
2610 do_encoding_reply_channel_range(1);
2613 fn do_encoding_reply_channel_range(encoding_type: u8) {
2614 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000b8a06000005dc01").unwrap();
2615 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2616 let mut reply_channel_range = msgs::ReplyChannelRange {
2617 chain_hash: expected_chain_hash,
2618 first_blocknum: 756230,
2619 number_of_blocks: 1500,
2620 sync_complete: true,
2621 short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2624 if encoding_type == 0 {
2625 target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2626 let encoded_value = reply_channel_range.encode();
2627 assert_eq!(encoded_value, target_value);
2629 reply_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2630 assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
2631 assert_eq!(reply_channel_range.first_blocknum, 756230);
2632 assert_eq!(reply_channel_range.number_of_blocks, 1500);
2633 assert_eq!(reply_channel_range.sync_complete, true);
2634 assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
2635 assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
2636 assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
2638 target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2639 let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2640 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2645 fn encoding_query_short_channel_ids() {
2646 do_encoding_query_short_channel_ids(0);
2647 do_encoding_query_short_channel_ids(1);
2650 fn do_encoding_query_short_channel_ids(encoding_type: u8) {
2651 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206").unwrap();
2652 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2653 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
2654 chain_hash: expected_chain_hash,
2655 short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2658 if encoding_type == 0 {
2659 target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2660 let encoded_value = query_short_channel_ids.encode();
2661 assert_eq!(encoded_value, target_value);
2663 query_short_channel_ids = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2664 assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
2665 assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
2666 assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
2667 assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
2669 target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2670 let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2671 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2676 fn encoding_reply_short_channel_ids_end() {
2677 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2678 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
2679 chain_hash: expected_chain_hash,
2680 full_information: true,
2682 let encoded_value = reply_short_channel_ids_end.encode();
2683 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e220601").unwrap();
2684 assert_eq!(encoded_value, target_value);
2686 reply_short_channel_ids_end = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2687 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
2688 assert_eq!(reply_short_channel_ids_end.full_information, true);
2692 fn encoding_gossip_timestamp_filter(){
2693 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2694 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
2695 chain_hash: expected_chain_hash,
2696 first_timestamp: 1590000000,
2697 timestamp_range: 0xffff_ffff,
2699 let encoded_value = gossip_timestamp_filter.encode();
2700 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e22065ec57980ffffffff").unwrap();
2701 assert_eq!(encoded_value, target_value);
2703 gossip_timestamp_filter = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2704 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
2705 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
2706 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);