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::channelmanager::{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),
68 /// An init message to be sent or received from a peer
71 #[cfg(not(feature = "fuzztarget"))]
72 pub(crate) features: InitFeatures,
73 #[cfg(feature = "fuzztarget")]
74 pub features: InitFeatures,
77 /// An error message to be sent or received from a peer
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
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
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
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
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
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
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, 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, 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, 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, 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, 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, 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, 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, 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, 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(PartialEq, Clone)]
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(PartialEq, Clone)]
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(PartialEq, Clone)]
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(PartialEq, Clone, Debug)]
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, PartialEq, Debug)]
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 /// Strict byte-length of address descriptor, 1-byte type not recorded
396 fn len(&self) -> u16 {
398 &NetAddress::IPv4 { .. } => { 6 },
399 &NetAddress::IPv6 { .. } => { 18 },
400 &NetAddress::OnionV2 { .. } => { 12 },
401 &NetAddress::OnionV3 { .. } => { 37 },
405 /// The maximum length of any address descriptor, not including the 1-byte type
406 pub(crate) const MAX_LEN: u16 = 37;
409 impl Writeable for NetAddress {
410 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
412 &NetAddress::IPv4 { ref addr, ref port } => {
417 &NetAddress::IPv6 { ref addr, ref port } => {
422 &NetAddress::OnionV2 { ref addr, ref port } => {
427 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
429 ed25519_pubkey.write(writer)?;
430 checksum.write(writer)?;
431 version.write(writer)?;
439 impl Readable for Result<NetAddress, u8> {
440 fn read<R: Read>(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
441 let byte = <u8 as Readable>::read(reader)?;
444 Ok(Ok(NetAddress::IPv4 {
445 addr: Readable::read(reader)?,
446 port: Readable::read(reader)?,
450 Ok(Ok(NetAddress::IPv6 {
451 addr: Readable::read(reader)?,
452 port: Readable::read(reader)?,
456 Ok(Ok(NetAddress::OnionV2 {
457 addr: Readable::read(reader)?,
458 port: Readable::read(reader)?,
462 Ok(Ok(NetAddress::OnionV3 {
463 ed25519_pubkey: Readable::read(reader)?,
464 checksum: Readable::read(reader)?,
465 version: Readable::read(reader)?,
466 port: Readable::read(reader)?,
469 _ => return Ok(Err(byte)),
474 /// The unsigned part of a node_announcement
475 #[derive(PartialEq, Clone, Debug)]
476 pub struct UnsignedNodeAnnouncement {
477 /// The advertised features
478 pub features: NodeFeatures,
479 /// A strictly monotonic announcement counter, with gaps allowed
481 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
483 pub node_id: PublicKey,
484 /// An RGB color for UI purposes
486 /// An alias, for UI purposes. This should be sanitized before use. There is no guarantee
489 /// List of addresses on which this node is reachable
490 pub addresses: Vec<NetAddress>,
491 pub(crate) excess_address_data: Vec<u8>,
492 pub(crate) excess_data: Vec<u8>,
494 #[derive(PartialEq, Clone, Debug)]
495 /// A node_announcement message to be sent or received from a peer
496 pub struct NodeAnnouncement {
497 /// The signature by the node key
498 pub signature: Signature,
499 /// The actual content of the announcement
500 pub contents: UnsignedNodeAnnouncement,
503 /// The unsigned part of a channel_announcement
504 #[derive(PartialEq, Clone, Debug)]
505 pub struct UnsignedChannelAnnouncement {
506 /// The advertised channel features
507 pub features: ChannelFeatures,
508 /// The genesis hash of the blockchain where the channel is to be opened
509 pub chain_hash: BlockHash,
510 /// The short channel ID
511 pub short_channel_id: u64,
512 /// One of the two node_ids which are endpoints of this channel
513 pub node_id_1: PublicKey,
514 /// The other of the two node_ids which are endpoints of this channel
515 pub node_id_2: PublicKey,
516 /// The funding key for the first node
517 pub bitcoin_key_1: PublicKey,
518 /// The funding key for the second node
519 pub bitcoin_key_2: PublicKey,
520 pub(crate) excess_data: Vec<u8>,
522 /// A channel_announcement message to be sent or received from a peer
523 #[derive(PartialEq, Clone, Debug)]
524 pub struct ChannelAnnouncement {
525 /// Authentication of the announcement by the first public node
526 pub node_signature_1: Signature,
527 /// Authentication of the announcement by the second public node
528 pub node_signature_2: Signature,
529 /// Proof of funding UTXO ownership by the first public node
530 pub bitcoin_signature_1: Signature,
531 /// Proof of funding UTXO ownership by the second public node
532 pub bitcoin_signature_2: Signature,
533 /// The actual announcement
534 pub contents: UnsignedChannelAnnouncement,
537 /// The unsigned part of a channel_update
538 #[derive(PartialEq, Clone, Debug)]
539 pub struct UnsignedChannelUpdate {
540 /// The genesis hash of the blockchain where the channel is to be opened
541 pub chain_hash: BlockHash,
542 /// The short channel ID
543 pub short_channel_id: u64,
544 /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel
548 /// The number of blocks to subtract from incoming HTLC cltv_expiry values
549 pub cltv_expiry_delta: u16,
550 /// The minimum HTLC size incoming to sender, in milli-satoshi
551 pub htlc_minimum_msat: u64,
552 /// Optionally, the maximum HTLC value incoming to sender, in milli-satoshi
553 pub htlc_maximum_msat: OptionalField<u64>,
554 /// The base HTLC fee charged by sender, in milli-satoshi
555 pub fee_base_msat: u32,
556 /// The amount to fee multiplier, in micro-satoshi
557 pub fee_proportional_millionths: u32,
558 pub(crate) excess_data: Vec<u8>,
560 /// A channel_update message to be sent or received from a peer
561 #[derive(PartialEq, Clone, Debug)]
562 pub struct ChannelUpdate {
563 /// A signature of the channel update
564 pub signature: Signature,
565 /// The actual channel update
566 pub contents: UnsignedChannelUpdate,
569 /// A query_channel_range message is used to query a peer for channel
570 /// UTXOs in a range of blocks. The recipient of a query makes a best
571 /// effort to reply to the query using one or more reply_channel_range
573 #[derive(Clone, Debug)]
574 pub struct QueryChannelRange {
575 /// The genesis hash of the blockchain being queried
576 pub chain_hash: BlockHash,
577 /// The height of the first block for the channel UTXOs being queried
578 pub first_blocknum: u32,
579 /// The number of blocks to include in the query results
580 pub number_of_blocks: u32,
583 /// A reply_channel_range message is a reply to a query_channel_range
584 /// message. Multiple reply_channel_range messages can be sent in reply
585 /// to a single query_channel_range message. The query recipient makes a
586 /// best effort to respond based on their local network view which may
587 /// not be a perfect view of the network. The short_channel_ids in the
588 /// reply are encoded. We only support encoding_type=0 uncompressed
589 /// serialization and do not support encoding_type=1 zlib serialization.
590 #[derive(Clone, Debug)]
591 pub struct ReplyChannelRange {
592 /// The genesis hash of the blockchain being queried
593 pub chain_hash: BlockHash,
594 /// The height of the first block in the range of the reply
595 pub first_blocknum: u32,
596 /// The number of blocks included in the range of the reply
597 pub number_of_blocks: u32,
598 /// True when this is the final reply for a query
599 pub sync_complete: bool,
600 /// The short_channel_ids in the channel range
601 pub short_channel_ids: Vec<u64>,
604 /// A query_short_channel_ids message is used to query a peer for
605 /// routing gossip messages related to one or more short_channel_ids.
606 /// The query recipient will reply with the latest, if available,
607 /// channel_announcement, channel_update and node_announcement messages
608 /// it maintains for the requested short_channel_ids followed by a
609 /// reply_short_channel_ids_end message. The short_channel_ids sent in
610 /// this query are encoded. We only support encoding_type=0 uncompressed
611 /// serialization and do not support encoding_type=1 zlib serialization.
612 #[derive(Clone, Debug)]
613 pub struct QueryShortChannelIds {
614 /// The genesis hash of the blockchain being queried
615 pub chain_hash: BlockHash,
616 /// The short_channel_ids that are being queried
617 pub short_channel_ids: Vec<u64>,
620 /// A reply_short_channel_ids_end message is sent as a reply to a
621 /// query_short_channel_ids message. The query recipient makes a best
622 /// effort to respond based on their local network view which may not be
623 /// a perfect view of the network.
624 #[derive(Clone, Debug)]
625 pub struct ReplyShortChannelIdsEnd {
626 /// The genesis hash of the blockchain that was queried
627 pub chain_hash: BlockHash,
628 /// Indicates if the query recipient maintains up-to-date channel
629 /// information for the chain_hash
630 pub full_information: bool,
633 /// A gossip_timestamp_filter message is used by a node to request
634 /// gossip relay for messages in the requested time range when the
635 /// gossip_queries feature has been negotiated.
636 #[derive(Clone, Debug)]
637 pub struct GossipTimestampFilter {
638 /// The genesis hash of the blockchain for channel and node information
639 pub chain_hash: BlockHash,
640 /// The starting unix timestamp
641 pub first_timestamp: u32,
642 /// The range of information in seconds
643 pub timestamp_range: u32,
646 /// Encoding type for data compression of collections in gossip queries.
647 /// We do not support encoding_type=1 zlib serialization defined in BOLT #7.
652 /// Used to put an error message in a LightningError
654 pub enum ErrorAction {
655 /// The peer took some action which made us think they were useless. Disconnect them.
657 /// An error message which we should make an effort to send before we disconnect.
658 msg: Option<ErrorMessage>
660 /// The peer did something harmless that we weren't able to process, just log and ignore
662 /// The peer did something incorrect. Tell them.
664 /// The message to send.
669 /// An Err type for failure to process messages.
671 pub struct LightningError {
672 /// A human-readable message describing the error
674 /// The action which should be taken against the offending peer.
675 pub action: ErrorAction,
678 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
679 /// transaction updates if they were pending.
680 #[derive(PartialEq, Clone)]
681 pub struct CommitmentUpdate {
682 /// update_add_htlc messages which should be sent
683 pub update_add_htlcs: Vec<UpdateAddHTLC>,
684 /// update_fulfill_htlc messages which should be sent
685 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
686 /// update_fail_htlc messages which should be sent
687 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
688 /// update_fail_malformed_htlc messages which should be sent
689 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
690 /// An update_fee message which should be sent
691 pub update_fee: Option<UpdateFee>,
692 /// Finally, the commitment_signed message which should be sent
693 pub commitment_signed: CommitmentSigned,
696 /// The information we received from a peer along the route of a payment we originated. This is
697 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
698 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
700 pub enum HTLCFailChannelUpdate {
701 /// We received an error which included a full ChannelUpdate message.
702 ChannelUpdateMessage {
703 /// The unwrapped message we received
706 /// We received an error which indicated only that a channel has been closed
708 /// The short_channel_id which has now closed.
709 short_channel_id: u64,
710 /// when this true, this channel should be permanently removed from the
711 /// consideration. Otherwise, this channel can be restored as new channel_update is received
714 /// We received an error which indicated only that a node has failed
716 /// The node_id that has failed.
718 /// when this true, node should be permanently removed from the
719 /// consideration. Otherwise, the channels connected to this node can be
720 /// restored as new channel_update is received
725 /// Messages could have optional fields to use with extended features
726 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
727 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
728 /// separate enum type for them.
729 /// (C-not exported) due to a free generic in T
730 #[derive(Clone, PartialEq, Debug)]
731 pub enum OptionalField<T> {
732 /// Optional field is included in message
734 /// Optional field is absent in message
738 /// A trait to describe an object which can receive channel messages.
740 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
741 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
742 pub trait ChannelMessageHandler : MessageSendEventsProvider + Send + Sync {
744 /// Handle an incoming open_channel message from the given peer.
745 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
746 /// Handle an incoming accept_channel message from the given peer.
747 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
748 /// Handle an incoming funding_created message from the given peer.
749 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
750 /// Handle an incoming funding_signed message from the given peer.
751 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
752 /// Handle an incoming funding_locked message from the given peer.
753 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
756 /// Handle an incoming shutdown message from the given peer.
757 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
758 /// Handle an incoming closing_signed message from the given peer.
759 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
762 /// Handle an incoming update_add_htlc message from the given peer.
763 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
764 /// Handle an incoming update_fulfill_htlc message from the given peer.
765 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
766 /// Handle an incoming update_fail_htlc message from the given peer.
767 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
768 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
769 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
770 /// Handle an incoming commitment_signed message from the given peer.
771 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
772 /// Handle an incoming revoke_and_ack message from the given peer.
773 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
775 /// Handle an incoming update_fee message from the given peer.
776 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
778 // Channel-to-announce:
779 /// Handle an incoming announcement_signatures message from the given peer.
780 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
782 // Connection loss/reestablish:
783 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
784 /// is believed to be possible in the future (eg they're sending us messages we don't
785 /// understand or indicate they require unknown feature bits), no_connection_possible is set
786 /// and any outstanding channels should be failed.
787 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
789 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
790 fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init);
791 /// Handle an incoming channel_reestablish message from the given peer.
792 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
795 /// Handle an incoming error message from the given peer.
796 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
799 /// A trait to describe an object which can receive routing messages.
801 /// # Implementor DoS Warnings
803 /// For `gossip_queries` messages there are potential DoS vectors when handling
804 /// inbound queries. Implementors using an on-disk network graph should be aware of
805 /// repeated disk I/O for queries accessing different parts of the network graph.
806 pub trait RoutingMessageHandler : Send + Sync + MessageSendEventsProvider {
807 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
808 /// false or returning an Err otherwise.
809 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
810 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
811 /// or returning an Err otherwise.
812 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
813 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
814 /// false or returning an Err otherwise.
815 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
816 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
817 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
818 /// Gets a subset of the channel announcements and updates required to dump our routing table
819 /// to a remote node, starting at the short_channel_id indicated by starting_point and
820 /// including the batch_amount entries immediately higher in numerical value than starting_point.
821 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
822 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
823 /// starting at the node *after* the provided publickey and including batch_amount entries
824 /// immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
825 /// If None is provided for starting_point, we start at the first node.
826 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
827 /// Called when a connection is established with a peer. This can be used to
828 /// perform routing table synchronization using a strategy defined by the
830 fn sync_routing_table(&self, their_node_id: &PublicKey, init: &Init);
831 /// Handles the reply of a query we initiated to learn about channels
832 /// for a given range of blocks. We can expect to receive one or more
833 /// replies to a single query.
834 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError>;
835 /// Handles the reply of a query we initiated asking for routing gossip
836 /// messages for a list of channels. We should receive this message when
837 /// a node has completed its best effort to send us the pertaining routing
839 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError>;
840 /// Handles when a peer asks us to send a list of short_channel_ids
841 /// for the requested range of blocks.
842 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError>;
843 /// Handles when a peer asks us to send routing gossip messages for a
844 /// list of short_channel_ids.
845 fn handle_query_short_channel_ids(&self, their_node_id: &PublicKey, msg: QueryShortChannelIds) -> Result<(), LightningError>;
848 mod fuzzy_internal_msgs {
849 use ln::channelmanager::PaymentSecret;
851 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
852 // them from untrusted input):
854 pub(crate) struct FinalOnionHopData {
855 pub(crate) payment_secret: PaymentSecret,
856 /// The total value, in msat, of the payment as received by the ultimate recipient.
857 /// Message serialization may panic if this value is more than 21 million Bitcoin.
858 pub(crate) total_msat: u64,
861 pub(crate) enum OnionHopDataFormat {
862 Legacy { // aka Realm-0
863 short_channel_id: u64,
866 short_channel_id: u64,
869 payment_data: Option<FinalOnionHopData>,
873 pub struct OnionHopData {
874 pub(crate) format: OnionHopDataFormat,
875 /// The value, in msat, of the payment after this hop's fee is deducted.
876 /// Message serialization may panic if this value is more than 21 million Bitcoin.
877 pub(crate) amt_to_forward: u64,
878 pub(crate) outgoing_cltv_value: u32,
879 // 12 bytes of 0-padding for Legacy format
882 pub struct DecodedOnionErrorPacket {
883 pub(crate) hmac: [u8; 32],
884 pub(crate) failuremsg: Vec<u8>,
885 pub(crate) pad: Vec<u8>,
888 #[cfg(feature = "fuzztarget")]
889 pub use self::fuzzy_internal_msgs::*;
890 #[cfg(not(feature = "fuzztarget"))]
891 pub(crate) use self::fuzzy_internal_msgs::*;
894 pub(crate) struct OnionPacket {
895 pub(crate) version: u8,
896 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
897 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
898 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
899 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
900 pub(crate) hop_data: [u8; 20*65],
901 pub(crate) hmac: [u8; 32],
904 impl PartialEq for OnionPacket {
905 fn eq(&self, other: &OnionPacket) -> bool {
906 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
907 if i != j { return false; }
909 self.version == other.version &&
910 self.public_key == other.public_key &&
911 self.hmac == other.hmac
915 #[derive(Clone, PartialEq)]
916 pub(crate) struct OnionErrorPacket {
917 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
918 // (TODO) We limit it in decode to much lower...
919 pub(crate) data: Vec<u8>,
922 impl fmt::Display for DecodeError {
923 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
925 DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
926 DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
927 DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
928 DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
929 DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
930 DecodeError::Io(ref e) => e.fmt(f),
935 impl fmt::Debug for LightningError {
936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
937 f.write_str(self.err.as_str())
941 impl From<::std::io::Error> for DecodeError {
942 fn from(e: ::std::io::Error) -> Self {
943 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
944 DecodeError::ShortRead
946 DecodeError::Io(e.kind())
951 impl Writeable for OptionalField<Script> {
952 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
954 OptionalField::Present(ref script) => {
955 // Note that Writeable for script includes the 16-bit length tag for us
958 OptionalField::Absent => {}
964 impl Readable for OptionalField<Script> {
965 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
966 match <u16 as Readable>::read(r) {
968 let mut buf = vec![0; len as usize];
969 r.read_exact(&mut buf)?;
970 Ok(OptionalField::Present(Script::from(buf)))
972 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
978 impl Writeable for OptionalField<u64> {
979 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
981 OptionalField::Present(ref value) => {
984 OptionalField::Absent => {}
990 impl Readable for OptionalField<u64> {
991 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
992 let value: u64 = Readable::read(r)?;
993 Ok(OptionalField::Present(value))
998 impl_writeable_len_match!(AcceptChannel, {
999 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
1002 temporary_channel_id,
1003 dust_limit_satoshis,
1004 max_htlc_value_in_flight_msat,
1005 channel_reserve_satoshis,
1011 revocation_basepoint,
1013 delayed_payment_basepoint,
1015 first_per_commitment_point,
1016 shutdown_scriptpubkey
1019 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
1026 impl Writeable for ChannelReestablish {
1027 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1028 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
1029 self.channel_id.write(w)?;
1030 self.next_local_commitment_number.write(w)?;
1031 self.next_remote_commitment_number.write(w)?;
1032 match self.data_loss_protect {
1033 OptionalField::Present(ref data_loss_protect) => {
1034 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
1035 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
1037 OptionalField::Absent => {}
1043 impl Readable for ChannelReestablish{
1044 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1046 channel_id: Readable::read(r)?,
1047 next_local_commitment_number: Readable::read(r)?,
1048 next_remote_commitment_number: Readable::read(r)?,
1049 data_loss_protect: {
1050 match <[u8; 32] as Readable>::read(r) {
1051 Ok(your_last_per_commitment_secret) =>
1052 OptionalField::Present(DataLossProtect {
1053 your_last_per_commitment_secret,
1054 my_current_per_commitment_point: Readable::read(r)?,
1056 Err(DecodeError::ShortRead) => OptionalField::Absent,
1057 Err(e) => return Err(e)
1064 impl_writeable!(ClosingSigned, 32+8+64, {
1070 impl_writeable_len_match!(CommitmentSigned, {
1071 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
1078 impl_writeable_len_match!(DecodedOnionErrorPacket, {
1079 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
1086 impl_writeable!(FundingCreated, 32+32+2+64, {
1087 temporary_channel_id,
1089 funding_output_index,
1093 impl_writeable!(FundingSigned, 32+64, {
1098 impl_writeable!(FundingLocked, 32+33, {
1100 next_per_commitment_point
1103 impl Writeable for Init {
1104 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1105 // global_features gets the bottom 13 bits of our features, and local_features gets all of
1106 // our relevant feature bits. This keeps us compatible with old nodes.
1107 self.features.write_up_to_13(w)?;
1108 self.features.write(w)
1112 impl Readable for Init {
1113 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1114 let global_features: InitFeatures = Readable::read(r)?;
1115 let features: InitFeatures = Readable::read(r)?;
1117 features: features.or(global_features),
1122 impl_writeable_len_match!(OpenChannel, {
1123 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
1127 temporary_channel_id,
1130 dust_limit_satoshis,
1131 max_htlc_value_in_flight_msat,
1132 channel_reserve_satoshis,
1138 revocation_basepoint,
1140 delayed_payment_basepoint,
1142 first_per_commitment_point,
1144 shutdown_scriptpubkey
1147 impl_writeable!(RevokeAndACK, 32+32+33, {
1149 per_commitment_secret,
1150 next_per_commitment_point
1153 impl_writeable_len_match!(Shutdown, {
1154 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
1160 impl_writeable_len_match!(UpdateFailHTLC, {
1161 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
1168 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
1175 impl_writeable!(UpdateFee, 32+4, {
1180 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1186 impl_writeable_len_match!(OnionErrorPacket, {
1187 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1192 impl Writeable for OnionPacket {
1193 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1194 w.size_hint(1 + 33 + 20*65 + 32);
1195 self.version.write(w)?;
1196 match self.public_key {
1197 Ok(pubkey) => pubkey.write(w)?,
1198 Err(_) => [0u8;33].write(w)?,
1200 w.write_all(&self.hop_data)?;
1201 self.hmac.write(w)?;
1206 impl Readable for OnionPacket {
1207 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1209 version: Readable::read(r)?,
1211 let mut buf = [0u8;33];
1212 r.read_exact(&mut buf)?;
1213 PublicKey::from_slice(&buf)
1215 hop_data: Readable::read(r)?,
1216 hmac: Readable::read(r)?,
1221 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1227 onion_routing_packet
1230 impl Writeable for FinalOnionHopData {
1231 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1232 w.size_hint(32 + 8 - (self.total_msat.leading_zeros()/8) as usize);
1233 self.payment_secret.0.write(w)?;
1234 HighZeroBytesDroppedVarInt(self.total_msat).write(w)
1238 impl Readable for FinalOnionHopData {
1239 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1240 let secret: [u8; 32] = Readable::read(r)?;
1241 let amt: HighZeroBytesDroppedVarInt<u64> = Readable::read(r)?;
1242 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
1246 impl Writeable for OnionHopData {
1247 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1249 // Note that this should never be reachable if Rust-Lightning generated the message, as we
1250 // check values are sane long before we get here, though its possible in the future
1251 // user-generated messages may hit this.
1252 if self.amt_to_forward > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1254 OnionHopDataFormat::Legacy { short_channel_id } => {
1256 short_channel_id.write(w)?;
1257 self.amt_to_forward.write(w)?;
1258 self.outgoing_cltv_value.write(w)?;
1259 w.write_all(&[0;12])?;
1261 OnionHopDataFormat::NonFinalNode { short_channel_id } => {
1262 encode_varint_length_prefixed_tlv!(w, {
1263 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1264 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1265 (6, short_channel_id)
1268 OnionHopDataFormat::FinalNode { payment_data: Some(ref final_data) } => {
1269 if final_data.total_msat > MAX_VALUE_MSAT { panic!("We should never be sending infinite/overflow onion payments"); }
1270 encode_varint_length_prefixed_tlv!(w, {
1271 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1272 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1276 OnionHopDataFormat::FinalNode { payment_data: None } => {
1277 encode_varint_length_prefixed_tlv!(w, {
1278 (2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1279 (4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
1287 impl Readable for OnionHopData {
1288 fn read<R: Read>(mut r: &mut R) -> Result<Self, DecodeError> {
1289 use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1290 let v: VarInt = Decodable::consensus_decode(&mut r)
1291 .map_err(|e| match e {
1292 Error::Io(ioe) => DecodeError::from(ioe),
1293 _ => DecodeError::InvalidValue
1295 const LEGACY_ONION_HOP_FLAG: u64 = 0;
1296 let (format, amt, cltv_value) = if v.0 != LEGACY_ONION_HOP_FLAG {
1297 let mut rd = FixedLengthReader::new(r, v.0);
1298 let mut amt = HighZeroBytesDroppedVarInt(0u64);
1299 let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
1300 let mut short_id: Option<u64> = None;
1301 let mut payment_data: Option<FinalOnionHopData> = None;
1302 decode_tlv!(&mut rd, {
1309 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1310 let format = if let Some(short_channel_id) = short_id {
1311 if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
1312 OnionHopDataFormat::NonFinalNode {
1316 if let &Some(ref data) = &payment_data {
1317 if data.total_msat > MAX_VALUE_MSAT {
1318 return Err(DecodeError::InvalidValue);
1321 OnionHopDataFormat::FinalNode {
1325 (format, amt.0, cltv_value.0)
1327 let format = OnionHopDataFormat::Legacy {
1328 short_channel_id: Readable::read(r)?,
1330 let amt: u64 = Readable::read(r)?;
1331 let cltv_value: u32 = Readable::read(r)?;
1332 r.read_exact(&mut [0; 12])?;
1333 (format, amt, cltv_value)
1336 if amt > MAX_VALUE_MSAT {
1337 return Err(DecodeError::InvalidValue);
1341 amt_to_forward: amt,
1342 outgoing_cltv_value: cltv_value,
1347 impl Writeable for Ping {
1348 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1349 w.size_hint(self.byteslen as usize + 4);
1350 self.ponglen.write(w)?;
1351 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1356 impl Readable for Ping {
1357 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1359 ponglen: Readable::read(r)?,
1361 let byteslen = Readable::read(r)?;
1362 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1369 impl Writeable for Pong {
1370 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1371 w.size_hint(self.byteslen as usize + 2);
1372 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1377 impl Readable for Pong {
1378 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1381 let byteslen = Readable::read(r)?;
1382 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1389 impl Writeable for UnsignedChannelAnnouncement {
1390 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1391 w.size_hint(2 + 2*32 + 4*33 + self.features.byte_count() + self.excess_data.len());
1392 self.features.write(w)?;
1393 self.chain_hash.write(w)?;
1394 self.short_channel_id.write(w)?;
1395 self.node_id_1.write(w)?;
1396 self.node_id_2.write(w)?;
1397 self.bitcoin_key_1.write(w)?;
1398 self.bitcoin_key_2.write(w)?;
1399 w.write_all(&self.excess_data[..])?;
1404 impl Readable for UnsignedChannelAnnouncement {
1405 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1407 features: Readable::read(r)?,
1408 chain_hash: Readable::read(r)?,
1409 short_channel_id: Readable::read(r)?,
1410 node_id_1: Readable::read(r)?,
1411 node_id_2: Readable::read(r)?,
1412 bitcoin_key_1: Readable::read(r)?,
1413 bitcoin_key_2: Readable::read(r)?,
1415 let mut excess_data = vec![];
1416 r.read_to_end(&mut excess_data)?;
1423 impl_writeable_len_match!(ChannelAnnouncement, {
1424 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1425 2 + 2*32 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1429 bitcoin_signature_1,
1430 bitcoin_signature_2,
1434 impl Writeable for UnsignedChannelUpdate {
1435 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1436 let mut size = 64 + self.excess_data.len();
1437 let mut message_flags: u8 = 0;
1438 if let OptionalField::Present(_) = self.htlc_maximum_msat {
1443 self.chain_hash.write(w)?;
1444 self.short_channel_id.write(w)?;
1445 self.timestamp.write(w)?;
1446 let all_flags = self.flags as u16 | ((message_flags as u16) << 8);
1447 all_flags.write(w)?;
1448 self.cltv_expiry_delta.write(w)?;
1449 self.htlc_minimum_msat.write(w)?;
1450 self.fee_base_msat.write(w)?;
1451 self.fee_proportional_millionths.write(w)?;
1452 self.htlc_maximum_msat.write(w)?;
1453 w.write_all(&self.excess_data[..])?;
1458 impl Readable for UnsignedChannelUpdate {
1459 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1460 let has_htlc_maximum_msat;
1462 chain_hash: Readable::read(r)?,
1463 short_channel_id: Readable::read(r)?,
1464 timestamp: Readable::read(r)?,
1466 let flags: u16 = Readable::read(r)?;
1467 let message_flags = flags >> 8;
1468 has_htlc_maximum_msat = (message_flags as i32 & 1) == 1;
1471 cltv_expiry_delta: Readable::read(r)?,
1472 htlc_minimum_msat: Readable::read(r)?,
1473 fee_base_msat: Readable::read(r)?,
1474 fee_proportional_millionths: Readable::read(r)?,
1475 htlc_maximum_msat: if has_htlc_maximum_msat { Readable::read(r)? } else { OptionalField::Absent },
1477 let mut excess_data = vec![];
1478 r.read_to_end(&mut excess_data)?;
1485 impl_writeable_len_match!(ChannelUpdate, {
1486 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1487 64 + excess_data.len() + 64 }
1493 impl Writeable for ErrorMessage {
1494 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1495 w.size_hint(32 + 2 + self.data.len());
1496 self.channel_id.write(w)?;
1497 (self.data.len() as u16).write(w)?;
1498 w.write_all(self.data.as_bytes())?;
1503 impl Readable for ErrorMessage {
1504 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1506 channel_id: Readable::read(r)?,
1508 let mut sz: usize = <u16 as Readable>::read(r)? as usize;
1509 let mut data = vec![];
1510 let data_len = r.read_to_end(&mut data)?;
1511 sz = cmp::min(data_len, sz);
1512 match String::from_utf8(data[..sz as usize].to_vec()) {
1514 Err(_) => return Err(DecodeError::InvalidValue),
1521 impl Writeable for UnsignedNodeAnnouncement {
1522 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1523 w.size_hint(64 + 76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1524 self.features.write(w)?;
1525 self.timestamp.write(w)?;
1526 self.node_id.write(w)?;
1527 w.write_all(&self.rgb)?;
1528 self.alias.write(w)?;
1530 let mut addr_len = 0;
1531 for addr in self.addresses.iter() {
1532 addr_len += 1 + addr.len();
1534 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1535 for addr in self.addresses.iter() {
1538 w.write_all(&self.excess_address_data[..])?;
1539 w.write_all(&self.excess_data[..])?;
1544 impl Readable for UnsignedNodeAnnouncement {
1545 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1546 let features: NodeFeatures = Readable::read(r)?;
1547 let timestamp: u32 = Readable::read(r)?;
1548 let node_id: PublicKey = Readable::read(r)?;
1549 let mut rgb = [0; 3];
1550 r.read_exact(&mut rgb)?;
1551 let alias: [u8; 32] = Readable::read(r)?;
1553 let addr_len: u16 = Readable::read(r)?;
1554 let mut addresses: Vec<NetAddress> = Vec::new();
1555 let mut addr_readpos = 0;
1556 let mut excess = false;
1557 let mut excess_byte = 0;
1559 if addr_len <= addr_readpos { break; }
1560 match Readable::read(r) {
1562 if addr_len < addr_readpos + 1 + addr.len() {
1563 return Err(DecodeError::BadLengthDescriptor);
1565 addr_readpos += (1 + addr.len()) as u16;
1566 addresses.push(addr);
1568 Ok(Err(unknown_descriptor)) => {
1570 excess_byte = unknown_descriptor;
1573 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1574 Err(e) => return Err(e),
1578 let mut excess_data = vec![];
1579 let excess_address_data = if addr_readpos < addr_len {
1580 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1581 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1583 excess_address_data[0] = excess_byte;
1588 excess_data.push(excess_byte);
1592 r.read_to_end(&mut excess_data)?;
1593 Ok(UnsignedNodeAnnouncement {
1600 excess_address_data,
1606 impl_writeable_len_match!(NodeAnnouncement, {
1607 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1608 64 + 76 + features.byte_count() + addresses.len()*(NetAddress::MAX_LEN as usize + 1) + excess_address_data.len() + excess_data.len() }
1614 impl Readable for QueryShortChannelIds {
1615 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1616 let chain_hash: BlockHash = Readable::read(r)?;
1618 // We expect the encoding_len to always includes the 1-byte
1619 // encoding_type and that short_channel_ids are 8-bytes each
1620 let encoding_len: u16 = Readable::read(r)?;
1621 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1622 return Err(DecodeError::InvalidValue);
1625 // Must be encoding_type=0 uncompressed serialization. We do not
1626 // support encoding_type=1 zlib serialization.
1627 let encoding_type: u8 = Readable::read(r)?;
1628 if encoding_type != EncodingType::Uncompressed as u8 {
1629 return Err(DecodeError::InvalidValue);
1632 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1633 // less the 1-byte encoding_type
1634 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1635 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1636 for _ in 0..short_channel_id_count {
1637 short_channel_ids.push(Readable::read(r)?);
1640 Ok(QueryShortChannelIds {
1647 impl Writeable for QueryShortChannelIds {
1648 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1649 // Calculated from 1-byte encoding_type plus 8-bytes per short_channel_id
1650 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1652 w.size_hint(32 + 2 + encoding_len as usize);
1653 self.chain_hash.write(w)?;
1654 encoding_len.write(w)?;
1656 // We only support type=0 uncompressed serialization
1657 (EncodingType::Uncompressed as u8).write(w)?;
1659 for scid in self.short_channel_ids.iter() {
1667 impl Readable for ReplyShortChannelIdsEnd {
1668 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1669 let chain_hash: BlockHash = Readable::read(r)?;
1670 let full_information: bool = Readable::read(r)?;
1671 Ok(ReplyShortChannelIdsEnd {
1678 impl Writeable for ReplyShortChannelIdsEnd {
1679 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1680 w.size_hint(32 + 1);
1681 self.chain_hash.write(w)?;
1682 self.full_information.write(w)?;
1687 impl Readable for QueryChannelRange {
1688 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1689 let chain_hash: BlockHash = Readable::read(r)?;
1690 let first_blocknum: u32 = Readable::read(r)?;
1691 let number_of_blocks: u32 = Readable::read(r)?;
1692 Ok(QueryChannelRange {
1700 impl Writeable for QueryChannelRange {
1701 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1702 w.size_hint(32 + 4 + 4);
1703 self.chain_hash.write(w)?;
1704 self.first_blocknum.write(w)?;
1705 self.number_of_blocks.write(w)?;
1710 impl Readable for ReplyChannelRange {
1711 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1712 let chain_hash: BlockHash = Readable::read(r)?;
1713 let first_blocknum: u32 = Readable::read(r)?;
1714 let number_of_blocks: u32 = Readable::read(r)?;
1715 let sync_complete: bool = Readable::read(r)?;
1717 // We expect the encoding_len to always includes the 1-byte
1718 // encoding_type and that short_channel_ids are 8-bytes each
1719 let encoding_len: u16 = Readable::read(r)?;
1720 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
1721 return Err(DecodeError::InvalidValue);
1724 // Must be encoding_type=0 uncompressed serialization. We do not
1725 // support encoding_type=1 zlib serialization.
1726 let encoding_type: u8 = Readable::read(r)?;
1727 if encoding_type != EncodingType::Uncompressed as u8 {
1728 return Err(DecodeError::InvalidValue);
1731 // Read short_channel_ids (8-bytes each), for the u16 encoding_len
1732 // less the 1-byte encoding_type
1733 let short_channel_id_count: u16 = (encoding_len - 1)/8;
1734 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
1735 for _ in 0..short_channel_id_count {
1736 short_channel_ids.push(Readable::read(r)?);
1739 Ok(ReplyChannelRange {
1749 impl Writeable for ReplyChannelRange {
1750 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1751 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
1752 w.size_hint(32 + 4 + 4 + 1 + 2 + encoding_len as usize);
1753 self.chain_hash.write(w)?;
1754 self.first_blocknum.write(w)?;
1755 self.number_of_blocks.write(w)?;
1756 self.sync_complete.write(w)?;
1758 encoding_len.write(w)?;
1759 (EncodingType::Uncompressed as u8).write(w)?;
1760 for scid in self.short_channel_ids.iter() {
1768 impl Readable for GossipTimestampFilter {
1769 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1770 let chain_hash: BlockHash = Readable::read(r)?;
1771 let first_timestamp: u32 = Readable::read(r)?;
1772 let timestamp_range: u32 = Readable::read(r)?;
1773 Ok(GossipTimestampFilter {
1781 impl Writeable for GossipTimestampFilter {
1782 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1783 w.size_hint(32 + 4 + 4);
1784 self.chain_hash.write(w)?;
1785 self.first_timestamp.write(w)?;
1786 self.timestamp_range.write(w)?;
1796 use ln::msgs::{ChannelFeatures, FinalOnionHopData, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1797 use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
1798 use util::ser::{Writeable, Readable};
1800 use bitcoin::hashes::hex::FromHex;
1801 use bitcoin::util::address::Address;
1802 use bitcoin::network::constants::Network;
1803 use bitcoin::blockdata::script::Builder;
1804 use bitcoin::blockdata::opcodes;
1805 use bitcoin::hash_types::{Txid, BlockHash};
1807 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1808 use bitcoin::secp256k1::{Secp256k1, Message};
1810 use std::io::Cursor;
1813 fn encoding_channel_reestablish_no_secret() {
1814 let cr = msgs::ChannelReestablish {
1815 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],
1816 next_local_commitment_number: 3,
1817 next_remote_commitment_number: 4,
1818 data_loss_protect: OptionalField::Absent,
1821 let encoded_value = cr.encode();
1824 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]
1829 fn encoding_channel_reestablish_with_secret() {
1831 let secp_ctx = Secp256k1::new();
1832 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1835 let cr = msgs::ChannelReestablish {
1836 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],
1837 next_local_commitment_number: 3,
1838 next_remote_commitment_number: 4,
1839 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1842 let encoded_value = cr.encode();
1845 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]
1849 macro_rules! get_keys_from {
1850 ($slice: expr, $secp_ctx: expr) => {
1852 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1853 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1859 macro_rules! get_sig_on {
1860 ($privkey: expr, $ctx: expr, $string: expr) => {
1862 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1863 $ctx.sign(&sighash, &$privkey)
1869 fn encoding_announcement_signatures() {
1870 let secp_ctx = Secp256k1::new();
1871 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1872 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1873 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1874 let announcement_signatures = msgs::AnnouncementSignatures {
1875 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],
1876 short_channel_id: 2316138423780173,
1877 node_signature: sig_1,
1878 bitcoin_signature: sig_2,
1881 let encoded_value = announcement_signatures.encode();
1882 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1885 fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
1886 let secp_ctx = Secp256k1::new();
1887 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1888 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1889 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1890 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1891 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1892 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1893 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1894 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1895 let mut features = ChannelFeatures::known();
1896 if unknown_features_bits {
1897 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
1899 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1901 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
1902 short_channel_id: 2316138423780173,
1903 node_id_1: pubkey_1,
1904 node_id_2: pubkey_2,
1905 bitcoin_key_1: pubkey_3,
1906 bitcoin_key_2: pubkey_4,
1907 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1909 let channel_announcement = msgs::ChannelAnnouncement {
1910 node_signature_1: sig_1,
1911 node_signature_2: sig_2,
1912 bitcoin_signature_1: sig_3,
1913 bitcoin_signature_2: sig_4,
1914 contents: unsigned_channel_announcement,
1916 let encoded_value = channel_announcement.encode();
1917 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1918 if unknown_features_bits {
1919 target_value.append(&mut hex::decode("0002ffff").unwrap());
1921 target_value.append(&mut hex::decode("0000").unwrap());
1923 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1924 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1926 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1928 assert_eq!(encoded_value, target_value);
1932 fn encoding_channel_announcement() {
1933 do_encoding_channel_announcement(true, false);
1934 do_encoding_channel_announcement(false, true);
1935 do_encoding_channel_announcement(false, false);
1936 do_encoding_channel_announcement(true, true);
1939 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1940 let secp_ctx = Secp256k1::new();
1941 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1942 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1943 let features = if unknown_features_bits {
1944 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
1946 // Set to some features we may support
1947 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
1949 let mut addresses = Vec::new();
1951 addresses.push(msgs::NetAddress::IPv4 {
1952 addr: [255, 254, 253, 252],
1957 addresses.push(msgs::NetAddress::IPv6 {
1958 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1963 addresses.push(msgs::NetAddress::OnionV2 {
1964 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1969 addresses.push(msgs::NetAddress::OnionV3 {
1970 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],
1976 let mut addr_len = 0;
1977 for addr in &addresses {
1978 addr_len += addr.len() + 1;
1980 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1982 timestamp: 20190119,
1987 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() },
1988 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() },
1990 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1991 let node_announcement = msgs::NodeAnnouncement {
1993 contents: unsigned_node_announcement,
1995 let encoded_value = node_announcement.encode();
1996 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1997 if unknown_features_bits {
1998 target_value.append(&mut hex::decode("0002ffff").unwrap());
2000 target_value.append(&mut hex::decode("000122").unwrap());
2002 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
2003 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
2005 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
2008 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
2011 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
2014 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
2016 if excess_address_data {
2017 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
2020 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2022 assert_eq!(encoded_value, target_value);
2026 fn encoding_node_announcement() {
2027 do_encoding_node_announcement(true, true, true, true, true, true, true);
2028 do_encoding_node_announcement(false, false, false, false, false, false, false);
2029 do_encoding_node_announcement(false, true, false, false, false, false, false);
2030 do_encoding_node_announcement(false, false, true, false, false, false, false);
2031 do_encoding_node_announcement(false, false, false, true, false, false, false);
2032 do_encoding_node_announcement(false, false, false, false, true, false, false);
2033 do_encoding_node_announcement(false, false, false, false, false, true, false);
2034 do_encoding_node_announcement(false, true, false, true, false, true, false);
2035 do_encoding_node_announcement(false, false, true, false, true, false, false);
2038 fn do_encoding_channel_update(direction: bool, disable: bool, htlc_maximum_msat: bool, excess_data: bool) {
2039 let secp_ctx = Secp256k1::new();
2040 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2041 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2042 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
2043 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2044 short_channel_id: 2316138423780173,
2045 timestamp: 20190119,
2046 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
2047 cltv_expiry_delta: 144,
2048 htlc_minimum_msat: 1000000,
2049 htlc_maximum_msat: if htlc_maximum_msat { OptionalField::Present(131355275467161) } else { OptionalField::Absent },
2050 fee_base_msat: 10000,
2051 fee_proportional_millionths: 20,
2052 excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
2054 let channel_update = msgs::ChannelUpdate {
2056 contents: unsigned_channel_update
2058 let encoded_value = channel_update.encode();
2059 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2060 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2061 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
2062 if htlc_maximum_msat {
2063 target_value.append(&mut hex::decode("01").unwrap());
2065 target_value.append(&mut hex::decode("00").unwrap());
2067 target_value.append(&mut hex::decode("00").unwrap());
2069 let flag = target_value.last_mut().unwrap();
2073 let flag = target_value.last_mut().unwrap();
2074 *flag = *flag | 1 << 1;
2076 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
2077 if htlc_maximum_msat {
2078 target_value.append(&mut hex::decode("0000777788889999").unwrap());
2081 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
2083 assert_eq!(encoded_value, target_value);
2087 fn encoding_channel_update() {
2088 do_encoding_channel_update(false, false, false, false);
2089 do_encoding_channel_update(false, false, false, true);
2090 do_encoding_channel_update(true, false, false, false);
2091 do_encoding_channel_update(true, false, false, true);
2092 do_encoding_channel_update(false, true, false, false);
2093 do_encoding_channel_update(false, true, false, true);
2094 do_encoding_channel_update(false, false, true, false);
2095 do_encoding_channel_update(false, false, true, true);
2096 do_encoding_channel_update(true, true, true, false);
2097 do_encoding_channel_update(true, true, true, true);
2100 fn do_encoding_open_channel(random_bit: bool, shutdown: bool) {
2101 let secp_ctx = Secp256k1::new();
2102 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2103 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2104 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2105 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2106 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2107 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2108 let open_channel = msgs::OpenChannel {
2109 chain_hash: BlockHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap(),
2110 temporary_channel_id: [2; 32],
2111 funding_satoshis: 1311768467284833366,
2112 push_msat: 2536655962884945560,
2113 dust_limit_satoshis: 3608586615801332854,
2114 max_htlc_value_in_flight_msat: 8517154655701053848,
2115 channel_reserve_satoshis: 8665828695742877976,
2116 htlc_minimum_msat: 2316138423780173,
2117 feerate_per_kw: 821716,
2118 to_self_delay: 49340,
2119 max_accepted_htlcs: 49340,
2120 funding_pubkey: pubkey_1,
2121 revocation_basepoint: pubkey_2,
2122 payment_point: pubkey_3,
2123 delayed_payment_basepoint: pubkey_4,
2124 htlc_basepoint: pubkey_5,
2125 first_per_commitment_point: pubkey_6,
2126 channel_flags: if random_bit { 1 << 5 } else { 0 },
2127 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
2129 let encoded_value = open_channel.encode();
2130 let mut target_value = Vec::new();
2131 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
2132 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
2134 target_value.append(&mut hex::decode("20").unwrap());
2136 target_value.append(&mut hex::decode("00").unwrap());
2139 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2141 assert_eq!(encoded_value, target_value);
2145 fn encoding_open_channel() {
2146 do_encoding_open_channel(false, false);
2147 do_encoding_open_channel(true, false);
2148 do_encoding_open_channel(false, true);
2149 do_encoding_open_channel(true, true);
2152 fn do_encoding_accept_channel(shutdown: bool) {
2153 let secp_ctx = Secp256k1::new();
2154 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2155 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2156 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2157 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2158 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
2159 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
2160 let accept_channel = msgs::AcceptChannel {
2161 temporary_channel_id: [2; 32],
2162 dust_limit_satoshis: 1311768467284833366,
2163 max_htlc_value_in_flight_msat: 2536655962884945560,
2164 channel_reserve_satoshis: 3608586615801332854,
2165 htlc_minimum_msat: 2316138423780173,
2166 minimum_depth: 821716,
2167 to_self_delay: 49340,
2168 max_accepted_htlcs: 49340,
2169 funding_pubkey: pubkey_1,
2170 revocation_basepoint: pubkey_2,
2171 payment_point: pubkey_3,
2172 delayed_payment_basepoint: pubkey_4,
2173 htlc_basepoint: pubkey_5,
2174 first_per_commitment_point: pubkey_6,
2175 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
2177 let encoded_value = accept_channel.encode();
2178 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
2180 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2182 assert_eq!(encoded_value, target_value);
2186 fn encoding_accept_channel() {
2187 do_encoding_accept_channel(false);
2188 do_encoding_accept_channel(true);
2192 fn encoding_funding_created() {
2193 let secp_ctx = Secp256k1::new();
2194 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2195 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2196 let funding_created = msgs::FundingCreated {
2197 temporary_channel_id: [2; 32],
2198 funding_txid: Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
2199 funding_output_index: 255,
2202 let encoded_value = funding_created.encode();
2203 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2204 assert_eq!(encoded_value, target_value);
2208 fn encoding_funding_signed() {
2209 let secp_ctx = Secp256k1::new();
2210 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2211 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2212 let funding_signed = msgs::FundingSigned {
2213 channel_id: [2; 32],
2216 let encoded_value = funding_signed.encode();
2217 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2218 assert_eq!(encoded_value, target_value);
2222 fn encoding_funding_locked() {
2223 let secp_ctx = Secp256k1::new();
2224 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2225 let funding_locked = msgs::FundingLocked {
2226 channel_id: [2; 32],
2227 next_per_commitment_point: pubkey_1,
2229 let encoded_value = funding_locked.encode();
2230 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2231 assert_eq!(encoded_value, target_value);
2234 fn do_encoding_shutdown(script_type: u8) {
2235 let secp_ctx = Secp256k1::new();
2236 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2237 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
2238 let shutdown = msgs::Shutdown {
2239 channel_id: [2; 32],
2241 if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() }
2242 else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() }
2243 else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).unwrap().script_pubkey() }
2244 else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
2246 let encoded_value = shutdown.encode();
2247 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
2248 if script_type == 1 {
2249 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
2250 } else if script_type == 2 {
2251 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
2252 } else if script_type == 3 {
2253 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
2254 } else if script_type == 4 {
2255 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
2257 assert_eq!(encoded_value, target_value);
2261 fn encoding_shutdown() {
2262 do_encoding_shutdown(1);
2263 do_encoding_shutdown(2);
2264 do_encoding_shutdown(3);
2265 do_encoding_shutdown(4);
2269 fn encoding_closing_signed() {
2270 let secp_ctx = Secp256k1::new();
2271 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2272 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2273 let closing_signed = msgs::ClosingSigned {
2274 channel_id: [2; 32],
2275 fee_satoshis: 2316138423780173,
2278 let encoded_value = closing_signed.encode();
2279 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2280 assert_eq!(encoded_value, target_value);
2284 fn encoding_update_add_htlc() {
2285 let secp_ctx = Secp256k1::new();
2286 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2287 let onion_routing_packet = msgs::OnionPacket {
2289 public_key: Ok(pubkey_1),
2290 hop_data: [1; 20*65],
2293 let update_add_htlc = msgs::UpdateAddHTLC {
2294 channel_id: [2; 32],
2295 htlc_id: 2316138423780173,
2296 amount_msat: 3608586615801332854,
2297 payment_hash: PaymentHash([1; 32]),
2298 cltv_expiry: 821716,
2299 onion_routing_packet
2301 let encoded_value = update_add_htlc.encode();
2302 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
2303 assert_eq!(encoded_value, target_value);
2307 fn encoding_update_fulfill_htlc() {
2308 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
2309 channel_id: [2; 32],
2310 htlc_id: 2316138423780173,
2311 payment_preimage: PaymentPreimage([1; 32]),
2313 let encoded_value = update_fulfill_htlc.encode();
2314 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
2315 assert_eq!(encoded_value, target_value);
2319 fn encoding_update_fail_htlc() {
2320 let reason = OnionErrorPacket {
2321 data: [1; 32].to_vec(),
2323 let update_fail_htlc = msgs::UpdateFailHTLC {
2324 channel_id: [2; 32],
2325 htlc_id: 2316138423780173,
2328 let encoded_value = update_fail_htlc.encode();
2329 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
2330 assert_eq!(encoded_value, target_value);
2334 fn encoding_update_fail_malformed_htlc() {
2335 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
2336 channel_id: [2; 32],
2337 htlc_id: 2316138423780173,
2338 sha256_of_onion: [1; 32],
2341 let encoded_value = update_fail_malformed_htlc.encode();
2342 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
2343 assert_eq!(encoded_value, target_value);
2346 fn do_encoding_commitment_signed(htlcs: bool) {
2347 let secp_ctx = Secp256k1::new();
2348 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2349 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
2350 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
2351 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
2352 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
2353 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
2354 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
2355 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
2356 let commitment_signed = msgs::CommitmentSigned {
2357 channel_id: [2; 32],
2359 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
2361 let encoded_value = commitment_signed.encode();
2362 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
2364 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
2366 target_value.append(&mut hex::decode("0000").unwrap());
2368 assert_eq!(encoded_value, target_value);
2372 fn encoding_commitment_signed() {
2373 do_encoding_commitment_signed(true);
2374 do_encoding_commitment_signed(false);
2378 fn encoding_revoke_and_ack() {
2379 let secp_ctx = Secp256k1::new();
2380 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2381 let raa = msgs::RevokeAndACK {
2382 channel_id: [2; 32],
2383 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],
2384 next_per_commitment_point: pubkey_1,
2386 let encoded_value = raa.encode();
2387 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2388 assert_eq!(encoded_value, target_value);
2392 fn encoding_update_fee() {
2393 let update_fee = msgs::UpdateFee {
2394 channel_id: [2; 32],
2395 feerate_per_kw: 20190119,
2397 let encoded_value = update_fee.encode();
2398 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2399 assert_eq!(encoded_value, target_value);
2403 fn encoding_init() {
2404 assert_eq!(msgs::Init {
2405 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
2406 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2407 assert_eq!(msgs::Init {
2408 features: InitFeatures::from_le_bytes(vec![0xFF]),
2409 }.encode(), hex::decode("0001ff0001ff").unwrap());
2410 assert_eq!(msgs::Init {
2411 features: InitFeatures::from_le_bytes(vec![]),
2412 }.encode(), hex::decode("00000000").unwrap());
2416 fn encoding_error() {
2417 let error = msgs::ErrorMessage {
2418 channel_id: [2; 32],
2419 data: String::from("rust-lightning"),
2421 let encoded_value = error.encode();
2422 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2423 assert_eq!(encoded_value, target_value);
2427 fn encoding_ping() {
2428 let ping = msgs::Ping {
2432 let encoded_value = ping.encode();
2433 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2434 assert_eq!(encoded_value, target_value);
2438 fn encoding_pong() {
2439 let pong = msgs::Pong {
2442 let encoded_value = pong.encode();
2443 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2444 assert_eq!(encoded_value, target_value);
2448 fn encoding_legacy_onion_hop_data() {
2449 let msg = msgs::OnionHopData {
2450 format: OnionHopDataFormat::Legacy {
2451 short_channel_id: 0xdeadbeef1bad1dea,
2453 amt_to_forward: 0x0badf00d01020304,
2454 outgoing_cltv_value: 0xffffffff,
2456 let encoded_value = msg.encode();
2457 let target_value = hex::decode("00deadbeef1bad1dea0badf00d01020304ffffffff000000000000000000000000").unwrap();
2458 assert_eq!(encoded_value, target_value);
2462 fn encoding_nonfinal_onion_hop_data() {
2463 let mut msg = msgs::OnionHopData {
2464 format: OnionHopDataFormat::NonFinalNode {
2465 short_channel_id: 0xdeadbeef1bad1dea,
2467 amt_to_forward: 0x0badf00d01020304,
2468 outgoing_cltv_value: 0xffffffff,
2470 let encoded_value = msg.encode();
2471 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2472 assert_eq!(encoded_value, target_value);
2473 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2474 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2475 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2476 } else { panic!(); }
2477 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2478 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2482 fn encoding_final_onion_hop_data() {
2483 let mut msg = msgs::OnionHopData {
2484 format: OnionHopDataFormat::FinalNode {
2487 amt_to_forward: 0x0badf00d01020304,
2488 outgoing_cltv_value: 0xffffffff,
2490 let encoded_value = msg.encode();
2491 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2492 assert_eq!(encoded_value, target_value);
2493 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2494 if let OnionHopDataFormat::FinalNode { payment_data: None } = msg.format { } else { panic!(); }
2495 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2496 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2500 fn encoding_final_onion_hop_data_with_secret() {
2501 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
2502 let mut msg = msgs::OnionHopData {
2503 format: OnionHopDataFormat::FinalNode {
2504 payment_data: Some(FinalOnionHopData {
2505 payment_secret: expected_payment_secret,
2506 total_msat: 0x1badca1f
2509 amt_to_forward: 0x0badf00d01020304,
2510 outgoing_cltv_value: 0xffffffff,
2512 let encoded_value = msg.encode();
2513 let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
2514 assert_eq!(encoded_value, target_value);
2515 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2516 if let OnionHopDataFormat::FinalNode {
2517 payment_data: Some(FinalOnionHopData {
2519 total_msat: 0x1badca1f
2522 assert_eq!(payment_secret, expected_payment_secret);
2523 } else { panic!(); }
2524 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2525 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2529 fn encoding_query_channel_range() {
2530 let mut query_channel_range = msgs::QueryChannelRange {
2531 chain_hash: BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap(),
2532 first_blocknum: 100000,
2533 number_of_blocks: 1500,
2535 let encoded_value = query_channel_range.encode();
2536 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000186a0000005dc").unwrap();
2537 assert_eq!(encoded_value, target_value);
2539 query_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2540 assert_eq!(query_channel_range.first_blocknum, 100000);
2541 assert_eq!(query_channel_range.number_of_blocks, 1500);
2545 fn encoding_reply_channel_range() {
2546 do_encoding_reply_channel_range(0);
2547 do_encoding_reply_channel_range(1);
2550 fn do_encoding_reply_channel_range(encoding_type: u8) {
2551 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206000b8a06000005dc01").unwrap();
2552 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2553 let mut reply_channel_range = msgs::ReplyChannelRange {
2554 chain_hash: expected_chain_hash,
2555 first_blocknum: 756230,
2556 number_of_blocks: 1500,
2557 sync_complete: true,
2558 short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2561 if encoding_type == 0 {
2562 target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2563 let encoded_value = reply_channel_range.encode();
2564 assert_eq!(encoded_value, target_value);
2566 reply_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2567 assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
2568 assert_eq!(reply_channel_range.first_blocknum, 756230);
2569 assert_eq!(reply_channel_range.number_of_blocks, 1500);
2570 assert_eq!(reply_channel_range.sync_complete, true);
2571 assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
2572 assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
2573 assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
2575 target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2576 let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2577 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2582 fn encoding_query_short_channel_ids() {
2583 do_encoding_query_short_channel_ids(0);
2584 do_encoding_query_short_channel_ids(1);
2587 fn do_encoding_query_short_channel_ids(encoding_type: u8) {
2588 let mut target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206").unwrap();
2589 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2590 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
2591 chain_hash: expected_chain_hash,
2592 short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
2595 if encoding_type == 0 {
2596 target_value.append(&mut hex::decode("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
2597 let encoded_value = query_short_channel_ids.encode();
2598 assert_eq!(encoded_value, target_value);
2600 query_short_channel_ids = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2601 assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
2602 assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
2603 assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
2604 assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
2606 target_value.append(&mut hex::decode("001601789c636000833e08659309a65878be010010a9023a").unwrap());
2607 let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
2608 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
2613 fn encoding_reply_short_channel_ids_end() {
2614 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2615 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
2616 chain_hash: expected_chain_hash,
2617 full_information: true,
2619 let encoded_value = reply_short_channel_ids_end.encode();
2620 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e220601").unwrap();
2621 assert_eq!(encoded_value, target_value);
2623 reply_short_channel_ids_end = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2624 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
2625 assert_eq!(reply_short_channel_ids_end.full_information, true);
2629 fn encoding_gossip_timestamp_filter(){
2630 let expected_chain_hash = BlockHash::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
2631 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
2632 chain_hash: expected_chain_hash,
2633 first_timestamp: 1590000000,
2634 timestamp_range: 0xffff_ffff,
2636 let encoded_value = gossip_timestamp_filter.encode();
2637 let target_value = hex::decode("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e22065ec57980ffffffff").unwrap();
2638 assert_eq!(encoded_value, target_value);
2640 gossip_timestamp_filter = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2641 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
2642 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
2643 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);