1 //! Wire messages, traits representing wire message handlers, and a few error types live here.
3 //! For a normal node you probably don't need to use anything here, however, if you wish to split a
4 //! node into an internet-facing route/message socket handling daemon and a separate daemon (or
5 //! server entirely) which handles only channel-related messages you may wish to implement
6 //! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across
9 //! Note that if you go with such an architecture (instead of passing raw socket events to a
10 //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the
11 //! source node_id of the message, however this does allow you to significantly reduce bandwidth
12 //! between the systems as routing messages can represent a significant chunk of bandwidth usage
13 //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids
14 //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send
15 //! raw socket events into your non-internet-facing system and then send routing events back to
16 //! track the network on the less-secure system.
18 use secp256k1::key::PublicKey;
19 use secp256k1::Signature;
21 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
22 use bitcoin::blockdata::script::Script;
24 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use std::error::Error;
29 use std::result::Result;
32 use util::ser::{Readable, Writeable, Writer, FixedLengthReader};
34 use ln::channelmanager::{PaymentPreimage, PaymentHash};
36 /// 21 million * 10^8 * 1000
37 pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
39 /// An error in decoding a message or struct.
41 pub enum DecodeError {
42 /// A version byte specified something we don't know how to handle.
43 /// Includes unknown realm byte in an OnionHopData packet
45 /// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type)
46 UnknownRequiredFeature,
47 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
48 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
52 /// node_announcement included more than one address of a given type!
53 ExtraAddressesPerType,
54 /// A length descriptor in the packet didn't describe the later data correctly
56 /// Error from std::io
60 /// An init message to be sent or received from a peer
62 #[cfg(not(feature = "fuzztarget"))]
63 pub(crate) features: InitFeatures,
64 #[cfg(feature = "fuzztarget")]
65 pub features: InitFeatures,
68 /// An error message to be sent or received from a peer
70 pub struct ErrorMessage {
71 pub(crate) channel_id: [u8; 32],
72 pub(crate) data: String,
75 /// A ping message to be sent or received from a peer
77 pub(crate) ponglen: u16,
78 pub(crate) byteslen: u16,
81 /// A pong message to be sent or received from a peer
83 pub(crate) byteslen: u16,
86 /// An open_channel message to be sent or received from a peer
88 pub struct OpenChannel {
89 pub(crate) chain_hash: Sha256dHash,
90 pub(crate) temporary_channel_id: [u8; 32],
91 pub(crate) funding_satoshis: u64,
92 pub(crate) push_msat: u64,
93 pub(crate) dust_limit_satoshis: u64,
94 pub(crate) max_htlc_value_in_flight_msat: u64,
95 pub(crate) channel_reserve_satoshis: u64,
96 pub(crate) htlc_minimum_msat: u64,
97 pub(crate) feerate_per_kw: u32,
98 pub(crate) to_self_delay: u16,
99 pub(crate) max_accepted_htlcs: u16,
100 pub(crate) funding_pubkey: PublicKey,
101 pub(crate) revocation_basepoint: PublicKey,
102 pub(crate) payment_basepoint: PublicKey,
103 pub(crate) delayed_payment_basepoint: PublicKey,
104 pub(crate) htlc_basepoint: PublicKey,
105 pub(crate) first_per_commitment_point: PublicKey,
106 pub(crate) channel_flags: u8,
107 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
110 /// An accept_channel message to be sent or received from a peer
112 pub struct AcceptChannel {
113 pub(crate) temporary_channel_id: [u8; 32],
114 pub(crate) dust_limit_satoshis: u64,
115 pub(crate) max_htlc_value_in_flight_msat: u64,
116 pub(crate) channel_reserve_satoshis: u64,
117 pub(crate) htlc_minimum_msat: u64,
118 pub(crate) minimum_depth: u32,
119 pub(crate) to_self_delay: u16,
120 pub(crate) max_accepted_htlcs: u16,
121 pub(crate) funding_pubkey: PublicKey,
122 pub(crate) revocation_basepoint: PublicKey,
123 pub(crate) payment_basepoint: PublicKey,
124 pub(crate) delayed_payment_basepoint: PublicKey,
125 pub(crate) htlc_basepoint: PublicKey,
126 pub(crate) first_per_commitment_point: PublicKey,
127 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
130 /// A funding_created message to be sent or received from a peer
132 pub struct FundingCreated {
133 pub(crate) temporary_channel_id: [u8; 32],
134 pub(crate) funding_txid: Sha256dHash,
135 pub(crate) funding_output_index: u16,
136 pub(crate) signature: Signature,
139 /// A funding_signed message to be sent or received from a peer
141 pub struct FundingSigned {
142 pub(crate) channel_id: [u8; 32],
143 pub(crate) signature: Signature,
146 /// A funding_locked message to be sent or received from a peer
147 #[derive(Clone, PartialEq)]
148 #[allow(missing_docs)]
149 pub struct FundingLocked {
150 pub channel_id: [u8; 32],
151 pub next_per_commitment_point: PublicKey,
154 /// A shutdown message to be sent or received from a peer
155 #[derive(Clone, PartialEq)]
156 pub struct Shutdown {
157 pub(crate) channel_id: [u8; 32],
158 pub(crate) scriptpubkey: Script,
161 /// A closing_signed message to be sent or received from a peer
162 #[derive(Clone, PartialEq)]
163 pub struct ClosingSigned {
164 pub(crate) channel_id: [u8; 32],
165 pub(crate) fee_satoshis: u64,
166 pub(crate) signature: Signature,
169 /// An update_add_htlc message to be sent or received from a peer
170 #[derive(Clone, PartialEq)]
171 pub struct UpdateAddHTLC {
172 pub(crate) channel_id: [u8; 32],
173 pub(crate) htlc_id: u64,
174 pub(crate) amount_msat: u64,
175 pub(crate) payment_hash: PaymentHash,
176 pub(crate) cltv_expiry: u32,
177 pub(crate) onion_routing_packet: OnionPacket,
180 /// An update_fulfill_htlc message to be sent or received from a peer
181 #[derive(Clone, PartialEq)]
182 pub struct UpdateFulfillHTLC {
183 pub(crate) channel_id: [u8; 32],
184 pub(crate) htlc_id: u64,
185 pub(crate) payment_preimage: PaymentPreimage,
188 /// An update_fail_htlc message to be sent or received from a peer
189 #[derive(Clone, PartialEq)]
190 pub struct UpdateFailHTLC {
191 pub(crate) channel_id: [u8; 32],
192 pub(crate) htlc_id: u64,
193 pub(crate) reason: OnionErrorPacket,
196 /// An update_fail_malformed_htlc message to be sent or received from a peer
197 #[derive(Clone, PartialEq)]
198 pub struct UpdateFailMalformedHTLC {
199 pub(crate) channel_id: [u8; 32],
200 pub(crate) htlc_id: u64,
201 pub(crate) sha256_of_onion: [u8; 32],
202 pub(crate) failure_code: u16,
205 /// A commitment_signed message to be sent or received from a peer
206 #[derive(Clone, PartialEq)]
207 pub struct CommitmentSigned {
208 pub(crate) channel_id: [u8; 32],
209 pub(crate) signature: Signature,
210 pub(crate) htlc_signatures: Vec<Signature>,
213 /// A revoke_and_ack message to be sent or received from a peer
214 #[derive(Clone, PartialEq)]
215 pub struct RevokeAndACK {
216 pub(crate) channel_id: [u8; 32],
217 pub(crate) per_commitment_secret: [u8; 32],
218 pub(crate) next_per_commitment_point: PublicKey,
221 /// An update_fee message to be sent or received from a peer
222 #[derive(PartialEq, Clone)]
223 pub struct UpdateFee {
224 pub(crate) channel_id: [u8; 32],
225 pub(crate) feerate_per_kw: u32,
228 #[derive(PartialEq, Clone)]
229 pub(crate) struct DataLossProtect {
230 pub(crate) your_last_per_commitment_secret: [u8; 32],
231 pub(crate) my_current_per_commitment_point: PublicKey,
234 /// A channel_reestablish message to be sent or received from a peer
235 #[derive(PartialEq, Clone)]
236 pub struct ChannelReestablish {
237 pub(crate) channel_id: [u8; 32],
238 pub(crate) next_local_commitment_number: u64,
239 pub(crate) next_remote_commitment_number: u64,
240 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
243 /// An announcement_signatures message to be sent or received from a peer
244 #[derive(PartialEq, Clone, Debug)]
245 pub struct AnnouncementSignatures {
246 pub(crate) channel_id: [u8; 32],
247 pub(crate) short_channel_id: u64,
248 pub(crate) node_signature: Signature,
249 pub(crate) bitcoin_signature: Signature,
252 /// An address which can be used to connect to a remote peer
253 #[derive(Clone, PartialEq, Debug)]
254 pub enum NetAddress {
255 /// An IPv4 address/port on which the peer is listening.
257 /// The 4-byte IPv4 address
259 /// The port on which the node is listening
262 /// An IPv6 address/port on which the peer is listening.
264 /// The 16-byte IPv6 address
266 /// The port on which the node is listening
269 /// An old-style Tor onion address/port on which the peer is listening.
271 /// The bytes (usually encoded in base32 with ".onion" appended)
273 /// The port on which the node is listening
276 /// A new-style Tor onion address/port on which the peer is listening.
277 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
278 /// wrap as base32 and append ".onion".
280 /// The ed25519 long-term public key of the peer
281 ed25519_pubkey: [u8; 32],
282 /// The checksum of the pubkey and version, as included in the onion address
284 /// The version byte, as defined by the Tor Onion v3 spec.
286 /// The port on which the node is listening
291 fn get_id(&self) -> u8 {
293 &NetAddress::IPv4 {..} => { 1 },
294 &NetAddress::IPv6 {..} => { 2 },
295 &NetAddress::OnionV2 {..} => { 3 },
296 &NetAddress::OnionV3 {..} => { 4 },
300 /// Strict byte-length of address descriptor, 1-byte type not recorded
301 fn len(&self) -> u16 {
303 &NetAddress::IPv4 { .. } => { 6 },
304 &NetAddress::IPv6 { .. } => { 18 },
305 &NetAddress::OnionV2 { .. } => { 12 },
306 &NetAddress::OnionV3 { .. } => { 37 },
311 /// A "set" of addresses which enforces that there can be only up to one of each net address type.
312 pub struct NetAddressSet {
313 v4: Option<NetAddress>,
314 v6: Option<NetAddress>,
315 onion2: Option<NetAddress>,
316 onion3: Option<NetAddress>,
319 /// Creates a new, empty, NetAddressSet
320 pub fn new() -> Self {
321 NetAddressSet { v4: None, v6: None, onion2: None, onion3: None }
324 /// Sets the IPv4 socket address in this set, overwriting any previous IPv4 socket addresses
326 pub fn set_v4(&mut self, addr: [u8; 4], port: u16) {
327 self.v4 = Some(NetAddress::IPv4 { addr, port });
329 /// Sets the IPv6 socket address in this set, overwriting any previous IPv4 socket addresses
331 pub fn set_v6(&mut self, addr: [u8; 16], port: u16) {
332 self.v6 = Some(NetAddress::IPv6 { addr, port });
334 /// Sets the Tor Onion v2 socket address in this set, overwriting any previous IPv4 socket
335 /// address (if any).
336 pub fn set_onion_v2(&mut self, addr: [u8; 10], port: u16) {
337 self.onion2 = Some(NetAddress::OnionV2 { addr, port });
339 /// Sets the Tor Onion v3 socket address in this set, overwriting any previous IPv4 socket
340 /// address (if any).
341 pub fn set_onion_v3(&mut self, ed25519_pubkey: [u8; 32], checksum: u16, version: u8, port: u16) {
342 self.onion3 = Some(NetAddress::OnionV3 { ed25519_pubkey, checksum, version, port });
345 pub(crate) fn to_vec(mut self) -> Vec<NetAddress> {
346 let mut res = Vec::new();
347 if let Some(addr) = self.v4.take() {
350 if let Some(addr) = self.v6.take() {
353 if let Some(addr) = self.onion2.take() {
356 if let Some(addr) = self.onion3.take() {
363 impl Writeable for NetAddress {
364 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
366 &NetAddress::IPv4 { ref addr, ref port } => {
371 &NetAddress::IPv6 { ref addr, ref port } => {
376 &NetAddress::OnionV2 { ref addr, ref port } => {
381 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
383 ed25519_pubkey.write(writer)?;
384 checksum.write(writer)?;
385 version.write(writer)?;
393 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
394 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
395 let byte = <u8 as Readable<R>>::read(reader)?;
398 Ok(Ok(NetAddress::IPv4 {
399 addr: Readable::read(reader)?,
400 port: Readable::read(reader)?,
404 Ok(Ok(NetAddress::IPv6 {
405 addr: Readable::read(reader)?,
406 port: Readable::read(reader)?,
410 Ok(Ok(NetAddress::OnionV2 {
411 addr: Readable::read(reader)?,
412 port: Readable::read(reader)?,
416 Ok(Ok(NetAddress::OnionV3 {
417 ed25519_pubkey: Readable::read(reader)?,
418 checksum: Readable::read(reader)?,
419 version: Readable::read(reader)?,
420 port: Readable::read(reader)?,
423 _ => return Ok(Err(byte)),
428 // Only exposed as broadcast of node_announcement should be filtered by node_id
429 /// The unsigned part of a node_announcement
430 #[derive(PartialEq, Clone, Debug)]
431 pub struct UnsignedNodeAnnouncement {
432 pub(crate) features: NodeFeatures,
433 pub(crate) timestamp: u32,
434 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
436 pub node_id: PublicKey,
437 pub(crate) rgb: [u8; 3],
438 pub(crate) alias: [u8; 32],
439 /// List of addresses on which this node is reachable. Note that you may only have up to one
440 /// address of each type, if you have more, they may be silently discarded or we may panic!
441 pub(crate) addresses: Vec<NetAddress>,
442 pub(crate) excess_address_data: Vec<u8>,
443 pub(crate) excess_data: Vec<u8>,
445 #[derive(PartialEq, Clone)]
446 /// A node_announcement message to be sent or received from a peer
447 pub struct NodeAnnouncement {
448 pub(crate) signature: Signature,
449 pub(crate) contents: UnsignedNodeAnnouncement,
452 // Only exposed as broadcast of channel_announcement should be filtered by node_id
453 /// The unsigned part of a channel_announcement
454 #[derive(PartialEq, Clone, Debug)]
455 pub struct UnsignedChannelAnnouncement {
456 pub(crate) features: ChannelFeatures,
457 pub(crate) chain_hash: Sha256dHash,
458 pub(crate) short_channel_id: u64,
459 /// One of the two node_ids which are endpoints of this channel
460 pub node_id_1: PublicKey,
461 /// The other of the two node_ids which are endpoints of this channel
462 pub node_id_2: PublicKey,
463 pub(crate) bitcoin_key_1: PublicKey,
464 pub(crate) bitcoin_key_2: PublicKey,
465 pub(crate) excess_data: Vec<u8>,
467 /// A channel_announcement message to be sent or received from a peer
468 #[derive(PartialEq, Clone, Debug)]
469 pub struct ChannelAnnouncement {
470 pub(crate) node_signature_1: Signature,
471 pub(crate) node_signature_2: Signature,
472 pub(crate) bitcoin_signature_1: Signature,
473 pub(crate) bitcoin_signature_2: Signature,
474 pub(crate) contents: UnsignedChannelAnnouncement,
477 #[derive(PartialEq, Clone, Debug)]
478 pub(crate) struct UnsignedChannelUpdate {
479 pub(crate) chain_hash: Sha256dHash,
480 pub(crate) short_channel_id: u64,
481 pub(crate) timestamp: u32,
482 pub(crate) flags: u16,
483 pub(crate) cltv_expiry_delta: u16,
484 pub(crate) htlc_minimum_msat: u64,
485 pub(crate) fee_base_msat: u32,
486 pub(crate) fee_proportional_millionths: u32,
487 pub(crate) excess_data: Vec<u8>,
489 /// A channel_update message to be sent or received from a peer
490 #[derive(PartialEq, Clone, Debug)]
491 pub struct ChannelUpdate {
492 pub(crate) signature: Signature,
493 pub(crate) contents: UnsignedChannelUpdate,
496 /// Used to put an error message in a LightningError
498 pub enum ErrorAction {
499 /// The peer took some action which made us think they were useless. Disconnect them.
501 /// An error message which we should make an effort to send before we disconnect.
502 msg: Option<ErrorMessage>
504 /// The peer did something harmless that we weren't able to process, just log and ignore
506 /// The peer did something incorrect. Tell them.
508 /// The message to send.
513 /// An Err type for failure to process messages.
514 pub struct LightningError {
515 /// A human-readable message describing the error
516 pub err: &'static str,
517 /// The action which should be taken against the offending peer.
518 pub action: ErrorAction,
521 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
522 /// transaction updates if they were pending.
523 #[derive(PartialEq, Clone)]
524 pub struct CommitmentUpdate {
525 /// update_add_htlc messages which should be sent
526 pub update_add_htlcs: Vec<UpdateAddHTLC>,
527 /// update_fulfill_htlc messages which should be sent
528 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
529 /// update_fail_htlc messages which should be sent
530 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
531 /// update_fail_malformed_htlc messages which should be sent
532 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
533 /// An update_fee message which should be sent
534 pub update_fee: Option<UpdateFee>,
535 /// Finally, the commitment_signed message which should be sent
536 pub commitment_signed: CommitmentSigned,
539 /// The information we received from a peer along the route of a payment we originated. This is
540 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
541 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
543 pub enum HTLCFailChannelUpdate {
544 /// We received an error which included a full ChannelUpdate message.
545 ChannelUpdateMessage {
546 /// The unwrapped message we received
549 /// We received an error which indicated only that a channel has been closed
551 /// The short_channel_id which has now closed.
552 short_channel_id: u64,
553 /// when this true, this channel should be permanently removed from the
554 /// consideration. Otherwise, this channel can be restored as new channel_update is received
557 /// We received an error which indicated only that a node has failed
559 /// The node_id that has failed.
561 /// when this true, node should be permanently removed from the
562 /// consideration. Otherwise, the channels connected to this node can be
563 /// restored as new channel_update is received
568 /// Messages could have optional fields to use with extended features
569 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
570 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
571 /// separate enum type for them.
572 #[derive(Clone, PartialEq)]
573 pub enum OptionalField<T> {
574 /// Optional field is included in message
576 /// Optional field is absent in message
580 /// A trait to describe an object which can receive channel messages.
582 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
583 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
584 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
586 /// Handle an incoming open_channel message from the given peer.
587 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
588 /// Handle an incoming accept_channel message from the given peer.
589 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
590 /// Handle an incoming funding_created message from the given peer.
591 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
592 /// Handle an incoming funding_signed message from the given peer.
593 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
594 /// Handle an incoming funding_locked message from the given peer.
595 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
598 /// Handle an incoming shutdown message from the given peer.
599 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
600 /// Handle an incoming closing_signed message from the given peer.
601 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
604 /// Handle an incoming update_add_htlc message from the given peer.
605 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
606 /// Handle an incoming update_fulfill_htlc message from the given peer.
607 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
608 /// Handle an incoming update_fail_htlc message from the given peer.
609 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
610 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
611 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
612 /// Handle an incoming commitment_signed message from the given peer.
613 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
614 /// Handle an incoming revoke_and_ack message from the given peer.
615 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
617 /// Handle an incoming update_fee message from the given peer.
618 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
620 // Channel-to-announce:
621 /// Handle an incoming announcement_signatures message from the given peer.
622 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
624 // Connection loss/reestablish:
625 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
626 /// is believed to be possible in the future (eg they're sending us messages we don't
627 /// understand or indicate they require unknown feature bits), no_connection_possible is set
628 /// and any outstanding channels should be failed.
629 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
631 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
632 fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init);
633 /// Handle an incoming channel_reestablish message from the given peer.
634 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
637 /// Handle an incoming error message from the given peer.
638 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
641 /// A trait to describe an object which can receive routing messages.
642 pub trait RoutingMessageHandler : Send + Sync {
643 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
644 /// false or returning an Err otherwise.
645 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
646 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
647 /// or returning an Err otherwise.
648 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
649 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
650 /// false or returning an Err otherwise.
651 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
652 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
653 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
654 /// Gets a subset of the channel announcements and updates required to dump our routing table
655 /// to a remote node, starting at the short_channel_id indicated by starting_point and
656 /// including batch_amount entries.
657 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
658 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
659 /// starting at the node *after* the provided publickey and including batch_amount entries.
660 /// If None is provided for starting_point, we start at the first node.
661 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
664 mod fuzzy_internal_msgs {
665 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
666 // them from untrusted input):
668 pub(crate) struct FinalOnionHopData {
669 pub(crate) payment_secret: [u8; 32],
670 pub(crate) total_msat: u64,
673 pub(crate) enum OnionHopDataFormat {
674 Legacy { // aka Realm-0
675 short_channel_id: u64,
678 short_channel_id: u64,
681 payment_data: Option<FinalOnionHopData>,
685 pub struct OnionHopData {
686 pub(crate) format: OnionHopDataFormat,
687 pub(crate) amt_to_forward: u64,
688 pub(crate) outgoing_cltv_value: u32,
689 // 12 bytes of 0-padding for Legacy format
692 pub struct DecodedOnionErrorPacket {
693 pub(crate) hmac: [u8; 32],
694 pub(crate) failuremsg: Vec<u8>,
695 pub(crate) pad: Vec<u8>,
698 #[cfg(feature = "fuzztarget")]
699 pub use self::fuzzy_internal_msgs::*;
700 #[cfg(not(feature = "fuzztarget"))]
701 pub(crate) use self::fuzzy_internal_msgs::*;
704 pub(crate) struct OnionPacket {
705 pub(crate) version: u8,
706 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
707 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
708 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
709 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
710 pub(crate) hop_data: [u8; 20*65],
711 pub(crate) hmac: [u8; 32],
714 impl PartialEq for OnionPacket {
715 fn eq(&self, other: &OnionPacket) -> bool {
716 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
717 if i != j { return false; }
719 self.version == other.version &&
720 self.public_key == other.public_key &&
721 self.hmac == other.hmac
725 #[derive(Clone, PartialEq)]
726 pub(crate) struct OnionErrorPacket {
727 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
728 // (TODO) We limit it in decode to much lower...
729 pub(crate) data: Vec<u8>,
732 impl Error for DecodeError {
733 fn description(&self) -> &str {
735 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
736 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
737 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
738 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
739 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
740 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
741 DecodeError::Io(ref e) => e.description(),
745 impl fmt::Display for DecodeError {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 f.write_str(self.description())
751 impl fmt::Debug for LightningError {
752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
753 f.write_str(self.err)
757 impl From<::std::io::Error> for DecodeError {
758 fn from(e: ::std::io::Error) -> Self {
759 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
760 DecodeError::ShortRead
767 impl Writeable for OptionalField<Script> {
768 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
770 OptionalField::Present(ref script) => {
771 // Note that Writeable for script includes the 16-bit length tag for us
774 OptionalField::Absent => {}
780 impl<R: Read> Readable<R> for OptionalField<Script> {
781 fn read(r: &mut R) -> Result<Self, DecodeError> {
782 match <u16 as Readable<R>>::read(r) {
784 let mut buf = vec![0; len as usize];
785 r.read_exact(&mut buf)?;
786 Ok(OptionalField::Present(Script::from(buf)))
788 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
794 impl_writeable_len_match!(AcceptChannel, {
795 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
798 temporary_channel_id,
800 max_htlc_value_in_flight_msat,
801 channel_reserve_satoshis,
807 revocation_basepoint,
809 delayed_payment_basepoint,
811 first_per_commitment_point,
812 shutdown_scriptpubkey
815 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
822 impl Writeable for ChannelReestablish {
823 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
824 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
825 self.channel_id.write(w)?;
826 self.next_local_commitment_number.write(w)?;
827 self.next_remote_commitment_number.write(w)?;
828 match self.data_loss_protect {
829 OptionalField::Present(ref data_loss_protect) => {
830 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
831 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
833 OptionalField::Absent => {}
839 impl<R: Read> Readable<R> for ChannelReestablish{
840 fn read(r: &mut R) -> Result<Self, DecodeError> {
842 channel_id: Readable::read(r)?,
843 next_local_commitment_number: Readable::read(r)?,
844 next_remote_commitment_number: Readable::read(r)?,
846 match <[u8; 32] as Readable<R>>::read(r) {
847 Ok(your_last_per_commitment_secret) =>
848 OptionalField::Present(DataLossProtect {
849 your_last_per_commitment_secret,
850 my_current_per_commitment_point: Readable::read(r)?,
852 Err(DecodeError::ShortRead) => OptionalField::Absent,
853 Err(e) => return Err(e)
860 impl_writeable!(ClosingSigned, 32+8+64, {
866 impl_writeable_len_match!(CommitmentSigned, {
867 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
874 impl_writeable_len_match!(DecodedOnionErrorPacket, {
875 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
882 impl_writeable!(FundingCreated, 32+32+2+64, {
883 temporary_channel_id,
885 funding_output_index,
889 impl_writeable!(FundingSigned, 32+64, {
894 impl_writeable!(FundingLocked, 32+33, {
896 next_per_commitment_point
899 impl Writeable for Init {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
901 // global_features gets the bottom 13 bits of our features, and local_features gets all of
902 // our relevant feature bits. This keeps us compatible with old nodes.
903 self.features.write_up_to_13(w)?;
904 self.features.write(w)
908 impl<R: Read> Readable<R> for Init {
909 fn read(r: &mut R) -> Result<Self, DecodeError> {
910 let global_features: InitFeatures = Readable::read(r)?;
911 let features: InitFeatures = Readable::read(r)?;
913 features: features.or(global_features),
918 impl_writeable_len_match!(OpenChannel, {
919 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
923 temporary_channel_id,
927 max_htlc_value_in_flight_msat,
928 channel_reserve_satoshis,
934 revocation_basepoint,
936 delayed_payment_basepoint,
938 first_per_commitment_point,
940 shutdown_scriptpubkey
943 impl_writeable!(RevokeAndACK, 32+32+33, {
945 per_commitment_secret,
946 next_per_commitment_point
949 impl_writeable_len_match!(Shutdown, {
950 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
956 impl_writeable_len_match!(UpdateFailHTLC, {
957 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
964 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
971 impl_writeable!(UpdateFee, 32+4, {
976 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
982 impl_writeable_len_match!(OnionErrorPacket, {
983 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
988 impl Writeable for OnionPacket {
989 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
990 w.size_hint(1 + 33 + 20*65 + 32);
991 self.version.write(w)?;
992 match self.public_key {
993 Ok(pubkey) => pubkey.write(w)?,
994 Err(_) => [0u8;33].write(w)?,
996 w.write_all(&self.hop_data)?;
1002 impl<R: Read> Readable<R> for OnionPacket {
1003 fn read(r: &mut R) -> Result<Self, DecodeError> {
1005 version: Readable::read(r)?,
1007 let mut buf = [0u8;33];
1008 r.read_exact(&mut buf)?;
1009 PublicKey::from_slice(&buf)
1011 hop_data: Readable::read(r)?,
1012 hmac: Readable::read(r)?,
1017 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1023 onion_routing_packet
1026 impl_writeable!(FinalOnionHopData, 32+8, {
1031 impl Writeable for OnionHopData {
1032 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1035 OnionHopDataFormat::Legacy { short_channel_id } => {
1037 short_channel_id.write(w)?;
1038 self.amt_to_forward.write(w)?;
1039 self.outgoing_cltv_value.write(w)?;
1041 OnionHopDataFormat::NonFinalNode { short_channel_id } => {
1042 encode_varint_length_prefixed_tlv!(w, {
1043 (2, self.amt_to_forward),
1044 (4, self.outgoing_cltv_value),
1045 (6, short_channel_id)
1048 OnionHopDataFormat::FinalNode { ref payment_data } => {
1049 if let &Some(ref final_data) = payment_data {
1050 encode_varint_length_prefixed_tlv!(w, {
1051 (2, self.amt_to_forward),
1052 (4, self.outgoing_cltv_value),
1056 encode_varint_length_prefixed_tlv!(w, {
1057 (2, self.amt_to_forward),
1058 (4, self.outgoing_cltv_value)
1064 OnionHopDataFormat::Legacy { .. } => {
1065 w.write_all(&[0;12])?;
1073 impl<R: Read> Readable<R> for OnionHopData {
1074 fn read(mut r: &mut R) -> Result<Self, DecodeError> {
1075 use bitcoin::consensus::encode::{Decodable, Error, VarInt};
1076 let v: VarInt = Decodable::consensus_decode(&mut r)
1077 .map_err(|e| match e {
1078 Error::Io(ioe) => DecodeError::from(ioe),
1079 _ => DecodeError::InvalidValue
1081 let (format, amt, cltv_value) = if v.0 != 0 {
1082 let mut rd = FixedLengthReader { read: r, read_len: 0, max_len: v.0 };
1083 let mut amt: u64 = 0;
1084 let mut cltv_value: u32 = 0;
1085 let mut short_id: Option<u64> = None;
1086 let mut payment_data: Option<FinalOnionHopData> = None;
1087 decode_tlv!(&mut rd, {
1094 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
1095 let format = if let Some(short_channel_id) = short_id {
1096 if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
1097 OnionHopDataFormat::NonFinalNode {
1101 if let &Some(ref data) = &payment_data {
1102 if data.total_msat > MAX_VALUE_MSAT {
1103 return Err(DecodeError::InvalidValue);
1106 OnionHopDataFormat::FinalNode {
1110 (format, amt, cltv_value)
1112 let format = OnionHopDataFormat::Legacy {
1113 short_channel_id: Readable::read(r)?,
1115 let amt: u64 = Readable::read(r)?;
1116 let cltv_value: u32 = Readable::read(r)?;
1117 if amt > MAX_VALUE_MSAT {
1118 return Err(DecodeError::InvalidValue);
1120 r.read_exact(&mut [0; 12])?;
1121 (format, amt, cltv_value)
1126 amt_to_forward: amt,
1127 outgoing_cltv_value: cltv_value,
1132 impl Writeable for Ping {
1133 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1134 w.size_hint(self.byteslen as usize + 4);
1135 self.ponglen.write(w)?;
1136 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1141 impl<R: Read> Readable<R> for Ping {
1142 fn read(r: &mut R) -> Result<Self, DecodeError> {
1144 ponglen: Readable::read(r)?,
1146 let byteslen = Readable::read(r)?;
1147 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1154 impl Writeable for Pong {
1155 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1156 w.size_hint(self.byteslen as usize + 2);
1157 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1162 impl<R: Read> Readable<R> for Pong {
1163 fn read(r: &mut R) -> Result<Self, DecodeError> {
1166 let byteslen = Readable::read(r)?;
1167 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1174 impl Writeable for UnsignedChannelAnnouncement {
1175 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1176 w.size_hint(2 + 2*32 + 4*33 + self.features.byte_count() + self.excess_data.len());
1177 self.features.write(w)?;
1178 self.chain_hash.write(w)?;
1179 self.short_channel_id.write(w)?;
1180 self.node_id_1.write(w)?;
1181 self.node_id_2.write(w)?;
1182 self.bitcoin_key_1.write(w)?;
1183 self.bitcoin_key_2.write(w)?;
1184 w.write_all(&self.excess_data[..])?;
1189 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1190 fn read(r: &mut R) -> Result<Self, DecodeError> {
1192 features: Readable::read(r)?,
1193 chain_hash: Readable::read(r)?,
1194 short_channel_id: Readable::read(r)?,
1195 node_id_1: Readable::read(r)?,
1196 node_id_2: Readable::read(r)?,
1197 bitcoin_key_1: Readable::read(r)?,
1198 bitcoin_key_2: Readable::read(r)?,
1200 let mut excess_data = vec![];
1201 r.read_to_end(&mut excess_data)?;
1208 impl_writeable_len_match!(ChannelAnnouncement, {
1209 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1210 2 + 2*32 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1214 bitcoin_signature_1,
1215 bitcoin_signature_2,
1219 impl Writeable for UnsignedChannelUpdate {
1220 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1221 w.size_hint(64 + self.excess_data.len());
1222 self.chain_hash.write(w)?;
1223 self.short_channel_id.write(w)?;
1224 self.timestamp.write(w)?;
1225 self.flags.write(w)?;
1226 self.cltv_expiry_delta.write(w)?;
1227 self.htlc_minimum_msat.write(w)?;
1228 self.fee_base_msat.write(w)?;
1229 self.fee_proportional_millionths.write(w)?;
1230 w.write_all(&self.excess_data[..])?;
1235 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1236 fn read(r: &mut R) -> Result<Self, DecodeError> {
1238 chain_hash: Readable::read(r)?,
1239 short_channel_id: Readable::read(r)?,
1240 timestamp: Readable::read(r)?,
1241 flags: Readable::read(r)?,
1242 cltv_expiry_delta: Readable::read(r)?,
1243 htlc_minimum_msat: Readable::read(r)?,
1244 fee_base_msat: Readable::read(r)?,
1245 fee_proportional_millionths: Readable::read(r)?,
1247 let mut excess_data = vec![];
1248 r.read_to_end(&mut excess_data)?;
1255 impl_writeable_len_match!(ChannelUpdate, {
1256 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1257 64 + excess_data.len() + 64 }
1263 impl Writeable for ErrorMessage {
1264 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1265 w.size_hint(32 + 2 + self.data.len());
1266 self.channel_id.write(w)?;
1267 (self.data.len() as u16).write(w)?;
1268 w.write_all(self.data.as_bytes())?;
1273 impl<R: Read> Readable<R> for ErrorMessage {
1274 fn read(r: &mut R) -> Result<Self, DecodeError> {
1276 channel_id: Readable::read(r)?,
1278 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1279 let mut data = vec![];
1280 let data_len = r.read_to_end(&mut data)?;
1281 sz = cmp::min(data_len, sz);
1282 match String::from_utf8(data[..sz as usize].to_vec()) {
1284 Err(_) => return Err(DecodeError::InvalidValue),
1291 impl Writeable for UnsignedNodeAnnouncement {
1292 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1293 w.size_hint(64 + 76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1294 self.features.write(w)?;
1295 self.timestamp.write(w)?;
1296 self.node_id.write(w)?;
1297 w.write_all(&self.rgb)?;
1298 self.alias.write(w)?;
1300 let mut addrs_to_encode = self.addresses.clone();
1301 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1302 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1303 let mut addr_len = 0;
1304 for addr in &addrs_to_encode {
1305 addr_len += 1 + addr.len();
1307 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1308 for addr in addrs_to_encode {
1311 w.write_all(&self.excess_address_data[..])?;
1312 w.write_all(&self.excess_data[..])?;
1317 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1318 fn read(r: &mut R) -> Result<Self, DecodeError> {
1319 let features: NodeFeatures = Readable::read(r)?;
1320 let timestamp: u32 = Readable::read(r)?;
1321 let node_id: PublicKey = Readable::read(r)?;
1322 let mut rgb = [0; 3];
1323 r.read_exact(&mut rgb)?;
1324 let alias: [u8; 32] = Readable::read(r)?;
1326 let addr_len: u16 = Readable::read(r)?;
1327 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1328 let mut addr_readpos = 0;
1329 let mut excess = false;
1330 let mut excess_byte = 0;
1332 if addr_len <= addr_readpos { break; }
1333 match Readable::read(r) {
1336 NetAddress::IPv4 { .. } => {
1337 if addresses.len() > 0 {
1338 return Err(DecodeError::ExtraAddressesPerType);
1341 NetAddress::IPv6 { .. } => {
1342 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1343 return Err(DecodeError::ExtraAddressesPerType);
1346 NetAddress::OnionV2 { .. } => {
1347 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1348 return Err(DecodeError::ExtraAddressesPerType);
1351 NetAddress::OnionV3 { .. } => {
1352 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1353 return Err(DecodeError::ExtraAddressesPerType);
1357 if addr_len < addr_readpos + 1 + addr.len() {
1358 return Err(DecodeError::BadLengthDescriptor);
1360 addr_readpos += (1 + addr.len()) as u16;
1361 addresses.push(addr);
1363 Ok(Err(unknown_descriptor)) => {
1365 excess_byte = unknown_descriptor;
1368 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1369 Err(e) => return Err(e),
1373 let mut excess_data = vec![];
1374 let excess_address_data = if addr_readpos < addr_len {
1375 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1376 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1378 excess_address_data[0] = excess_byte;
1383 excess_data.push(excess_byte);
1387 r.read_to_end(&mut excess_data)?;
1388 Ok(UnsignedNodeAnnouncement {
1395 excess_address_data,
1401 impl_writeable_len_match!(NodeAnnouncement, {
1402 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1403 64 + 76 + features.byte_count() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1413 use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1414 use ln::channelmanager::{PaymentPreimage, PaymentHash};
1415 use util::ser::{Writeable, Readable};
1417 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1418 use bitcoin_hashes::hex::FromHex;
1419 use bitcoin::util::address::Address;
1420 use bitcoin::network::constants::Network;
1421 use bitcoin::blockdata::script::Builder;
1422 use bitcoin::blockdata::opcodes;
1424 use secp256k1::key::{PublicKey,SecretKey};
1425 use secp256k1::{Secp256k1, Message};
1427 use std::io::Cursor;
1430 fn encoding_channel_reestablish_no_secret() {
1431 let cr = msgs::ChannelReestablish {
1432 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],
1433 next_local_commitment_number: 3,
1434 next_remote_commitment_number: 4,
1435 data_loss_protect: OptionalField::Absent,
1438 let encoded_value = cr.encode();
1441 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]
1446 fn encoding_channel_reestablish_with_secret() {
1448 let secp_ctx = Secp256k1::new();
1449 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1452 let cr = msgs::ChannelReestablish {
1453 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],
1454 next_local_commitment_number: 3,
1455 next_remote_commitment_number: 4,
1456 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1459 let encoded_value = cr.encode();
1462 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]
1466 macro_rules! get_keys_from {
1467 ($slice: expr, $secp_ctx: expr) => {
1469 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1470 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1476 macro_rules! get_sig_on {
1477 ($privkey: expr, $ctx: expr, $string: expr) => {
1479 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1480 $ctx.sign(&sighash, &$privkey)
1486 fn encoding_announcement_signatures() {
1487 let secp_ctx = Secp256k1::new();
1488 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1489 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1490 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1491 let announcement_signatures = msgs::AnnouncementSignatures {
1492 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],
1493 short_channel_id: 2316138423780173,
1494 node_signature: sig_1,
1495 bitcoin_signature: sig_2,
1498 let encoded_value = announcement_signatures.encode();
1499 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1502 fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
1503 let secp_ctx = Secp256k1::new();
1504 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1505 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1506 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1507 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1508 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1509 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1510 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1511 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1512 let mut features = ChannelFeatures::supported();
1513 if unknown_features_bits {
1514 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
1516 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1518 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1519 short_channel_id: 2316138423780173,
1520 node_id_1: pubkey_1,
1521 node_id_2: pubkey_2,
1522 bitcoin_key_1: pubkey_3,
1523 bitcoin_key_2: pubkey_4,
1524 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1526 let channel_announcement = msgs::ChannelAnnouncement {
1527 node_signature_1: sig_1,
1528 node_signature_2: sig_2,
1529 bitcoin_signature_1: sig_3,
1530 bitcoin_signature_2: sig_4,
1531 contents: unsigned_channel_announcement,
1533 let encoded_value = channel_announcement.encode();
1534 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1535 if unknown_features_bits {
1536 target_value.append(&mut hex::decode("0002ffff").unwrap());
1538 target_value.append(&mut hex::decode("0000").unwrap());
1540 if non_bitcoin_chain_hash {
1541 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1543 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1545 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1547 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1549 assert_eq!(encoded_value, target_value);
1553 fn encoding_channel_announcement() {
1554 do_encoding_channel_announcement(false, false, false);
1555 do_encoding_channel_announcement(true, false, false);
1556 do_encoding_channel_announcement(true, true, false);
1557 do_encoding_channel_announcement(true, true, true);
1558 do_encoding_channel_announcement(false, true, true);
1559 do_encoding_channel_announcement(false, false, true);
1560 do_encoding_channel_announcement(false, true, false);
1561 do_encoding_channel_announcement(true, false, true);
1564 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1565 let secp_ctx = Secp256k1::new();
1566 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1567 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1568 let features = if unknown_features_bits {
1569 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
1571 // Set to some features we may support
1572 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
1574 let mut addresses = Vec::new();
1576 addresses.push(msgs::NetAddress::IPv4 {
1577 addr: [255, 254, 253, 252],
1582 addresses.push(msgs::NetAddress::IPv6 {
1583 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1588 addresses.push(msgs::NetAddress::OnionV2 {
1589 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1594 addresses.push(msgs::NetAddress::OnionV3 {
1595 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],
1601 let mut addr_len = 0;
1602 for addr in &addresses {
1603 addr_len += addr.len() + 1;
1605 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1607 timestamp: 20190119,
1612 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() },
1613 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() },
1615 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1616 let node_announcement = msgs::NodeAnnouncement {
1618 contents: unsigned_node_announcement,
1620 let encoded_value = node_announcement.encode();
1621 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1622 if unknown_features_bits {
1623 target_value.append(&mut hex::decode("0002ffff").unwrap());
1625 target_value.append(&mut hex::decode("000122").unwrap());
1627 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1628 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1630 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1633 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1636 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1639 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1641 if excess_address_data {
1642 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1645 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1647 assert_eq!(encoded_value, target_value);
1651 fn encoding_node_announcement() {
1652 do_encoding_node_announcement(true, true, true, true, true, true, true);
1653 do_encoding_node_announcement(false, false, false, false, false, false, false);
1654 do_encoding_node_announcement(false, true, false, false, false, false, false);
1655 do_encoding_node_announcement(false, false, true, false, false, false, false);
1656 do_encoding_node_announcement(false, false, false, true, false, false, false);
1657 do_encoding_node_announcement(false, false, false, false, true, false, false);
1658 do_encoding_node_announcement(false, false, false, false, false, true, false);
1659 do_encoding_node_announcement(false, true, false, true, false, true, false);
1660 do_encoding_node_announcement(false, false, true, false, true, false, false);
1663 fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
1664 let secp_ctx = Secp256k1::new();
1665 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1666 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1667 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1668 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1669 short_channel_id: 2316138423780173,
1670 timestamp: 20190119,
1671 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
1672 cltv_expiry_delta: 144,
1673 htlc_minimum_msat: 1000000,
1674 fee_base_msat: 10000,
1675 fee_proportional_millionths: 20,
1676 excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1678 let channel_update = msgs::ChannelUpdate {
1680 contents: unsigned_channel_update
1682 let encoded_value = channel_update.encode();
1683 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1684 if non_bitcoin_chain_hash {
1685 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1687 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1689 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1690 if htlc_maximum_msat {
1691 target_value.append(&mut hex::decode("01").unwrap());
1693 target_value.append(&mut hex::decode("00").unwrap());
1695 target_value.append(&mut hex::decode("00").unwrap());
1697 let flag = target_value.last_mut().unwrap();
1701 let flag = target_value.last_mut().unwrap();
1702 *flag = *flag | 1 << 1;
1704 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1705 if htlc_maximum_msat {
1706 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1708 assert_eq!(encoded_value, target_value);
1712 fn encoding_channel_update() {
1713 do_encoding_channel_update(false, false, false, false);
1714 do_encoding_channel_update(true, false, false, false);
1715 do_encoding_channel_update(false, true, false, false);
1716 do_encoding_channel_update(false, false, true, false);
1717 do_encoding_channel_update(false, false, false, true);
1718 do_encoding_channel_update(true, true, true, true);
1721 fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
1722 let secp_ctx = Secp256k1::new();
1723 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1724 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1725 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1726 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1727 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1728 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1729 let open_channel = msgs::OpenChannel {
1730 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1731 temporary_channel_id: [2; 32],
1732 funding_satoshis: 1311768467284833366,
1733 push_msat: 2536655962884945560,
1734 dust_limit_satoshis: 3608586615801332854,
1735 max_htlc_value_in_flight_msat: 8517154655701053848,
1736 channel_reserve_satoshis: 8665828695742877976,
1737 htlc_minimum_msat: 2316138423780173,
1738 feerate_per_kw: 821716,
1739 to_self_delay: 49340,
1740 max_accepted_htlcs: 49340,
1741 funding_pubkey: pubkey_1,
1742 revocation_basepoint: pubkey_2,
1743 payment_basepoint: pubkey_3,
1744 delayed_payment_basepoint: pubkey_4,
1745 htlc_basepoint: pubkey_5,
1746 first_per_commitment_point: pubkey_6,
1747 channel_flags: if random_bit { 1 << 5 } else { 0 },
1748 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1750 let encoded_value = open_channel.encode();
1751 let mut target_value = Vec::new();
1752 if non_bitcoin_chain_hash {
1753 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1755 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1757 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1759 target_value.append(&mut hex::decode("20").unwrap());
1761 target_value.append(&mut hex::decode("00").unwrap());
1764 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1766 assert_eq!(encoded_value, target_value);
1770 fn encoding_open_channel() {
1771 do_encoding_open_channel(false, false, false);
1772 do_encoding_open_channel(true, false, false);
1773 do_encoding_open_channel(false, true, false);
1774 do_encoding_open_channel(false, false, true);
1775 do_encoding_open_channel(true, true, true);
1778 fn do_encoding_accept_channel(shutdown: bool) {
1779 let secp_ctx = Secp256k1::new();
1780 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1781 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1782 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1783 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1784 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1785 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1786 let accept_channel = msgs::AcceptChannel {
1787 temporary_channel_id: [2; 32],
1788 dust_limit_satoshis: 1311768467284833366,
1789 max_htlc_value_in_flight_msat: 2536655962884945560,
1790 channel_reserve_satoshis: 3608586615801332854,
1791 htlc_minimum_msat: 2316138423780173,
1792 minimum_depth: 821716,
1793 to_self_delay: 49340,
1794 max_accepted_htlcs: 49340,
1795 funding_pubkey: pubkey_1,
1796 revocation_basepoint: pubkey_2,
1797 payment_basepoint: pubkey_3,
1798 delayed_payment_basepoint: pubkey_4,
1799 htlc_basepoint: pubkey_5,
1800 first_per_commitment_point: pubkey_6,
1801 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1803 let encoded_value = accept_channel.encode();
1804 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1806 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1808 assert_eq!(encoded_value, target_value);
1812 fn encoding_accept_channel() {
1813 do_encoding_accept_channel(false);
1814 do_encoding_accept_channel(true);
1818 fn encoding_funding_created() {
1819 let secp_ctx = Secp256k1::new();
1820 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1821 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1822 let funding_created = msgs::FundingCreated {
1823 temporary_channel_id: [2; 32],
1824 funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1825 funding_output_index: 255,
1828 let encoded_value = funding_created.encode();
1829 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1830 assert_eq!(encoded_value, target_value);
1834 fn encoding_funding_signed() {
1835 let secp_ctx = Secp256k1::new();
1836 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1837 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1838 let funding_signed = msgs::FundingSigned {
1839 channel_id: [2; 32],
1842 let encoded_value = funding_signed.encode();
1843 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1844 assert_eq!(encoded_value, target_value);
1848 fn encoding_funding_locked() {
1849 let secp_ctx = Secp256k1::new();
1850 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1851 let funding_locked = msgs::FundingLocked {
1852 channel_id: [2; 32],
1853 next_per_commitment_point: pubkey_1,
1855 let encoded_value = funding_locked.encode();
1856 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1857 assert_eq!(encoded_value, target_value);
1860 fn do_encoding_shutdown(script_type: u8) {
1861 let secp_ctx = Secp256k1::new();
1862 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1863 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1864 let shutdown = msgs::Shutdown {
1865 channel_id: [2; 32],
1866 scriptpubkey: if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else if script_type == 2 { Address::p2sh(&script, Network::Testnet).script_pubkey() } else if script_type == 3 { Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey() } else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
1868 let encoded_value = shutdown.encode();
1869 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1870 if script_type == 1 {
1871 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1872 } else if script_type == 2 {
1873 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1874 } else if script_type == 3 {
1875 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1876 } else if script_type == 4 {
1877 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1879 assert_eq!(encoded_value, target_value);
1883 fn encoding_shutdown() {
1884 do_encoding_shutdown(1);
1885 do_encoding_shutdown(2);
1886 do_encoding_shutdown(3);
1887 do_encoding_shutdown(4);
1891 fn encoding_closing_signed() {
1892 let secp_ctx = Secp256k1::new();
1893 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1894 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1895 let closing_signed = msgs::ClosingSigned {
1896 channel_id: [2; 32],
1897 fee_satoshis: 2316138423780173,
1900 let encoded_value = closing_signed.encode();
1901 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1902 assert_eq!(encoded_value, target_value);
1906 fn encoding_update_add_htlc() {
1907 let secp_ctx = Secp256k1::new();
1908 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1909 let onion_routing_packet = msgs::OnionPacket {
1911 public_key: Ok(pubkey_1),
1912 hop_data: [1; 20*65],
1915 let update_add_htlc = msgs::UpdateAddHTLC {
1916 channel_id: [2; 32],
1917 htlc_id: 2316138423780173,
1918 amount_msat: 3608586615801332854,
1919 payment_hash: PaymentHash([1; 32]),
1920 cltv_expiry: 821716,
1921 onion_routing_packet
1923 let encoded_value = update_add_htlc.encode();
1924 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
1925 assert_eq!(encoded_value, target_value);
1929 fn encoding_update_fulfill_htlc() {
1930 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
1931 channel_id: [2; 32],
1932 htlc_id: 2316138423780173,
1933 payment_preimage: PaymentPreimage([1; 32]),
1935 let encoded_value = update_fulfill_htlc.encode();
1936 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
1937 assert_eq!(encoded_value, target_value);
1941 fn encoding_update_fail_htlc() {
1942 let reason = OnionErrorPacket {
1943 data: [1; 32].to_vec(),
1945 let update_fail_htlc = msgs::UpdateFailHTLC {
1946 channel_id: [2; 32],
1947 htlc_id: 2316138423780173,
1950 let encoded_value = update_fail_htlc.encode();
1951 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
1952 assert_eq!(encoded_value, target_value);
1956 fn encoding_update_fail_malformed_htlc() {
1957 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
1958 channel_id: [2; 32],
1959 htlc_id: 2316138423780173,
1960 sha256_of_onion: [1; 32],
1963 let encoded_value = update_fail_malformed_htlc.encode();
1964 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
1965 assert_eq!(encoded_value, target_value);
1968 fn do_encoding_commitment_signed(htlcs: bool) {
1969 let secp_ctx = Secp256k1::new();
1970 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1971 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1972 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1973 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1974 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1975 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1976 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1977 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1978 let commitment_signed = msgs::CommitmentSigned {
1979 channel_id: [2; 32],
1981 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
1983 let encoded_value = commitment_signed.encode();
1984 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1986 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1988 target_value.append(&mut hex::decode("0000").unwrap());
1990 assert_eq!(encoded_value, target_value);
1994 fn encoding_commitment_signed() {
1995 do_encoding_commitment_signed(true);
1996 do_encoding_commitment_signed(false);
2000 fn encoding_revoke_and_ack() {
2001 let secp_ctx = Secp256k1::new();
2002 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
2003 let raa = msgs::RevokeAndACK {
2004 channel_id: [2; 32],
2005 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],
2006 next_per_commitment_point: pubkey_1,
2008 let encoded_value = raa.encode();
2009 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
2010 assert_eq!(encoded_value, target_value);
2014 fn encoding_update_fee() {
2015 let update_fee = msgs::UpdateFee {
2016 channel_id: [2; 32],
2017 feerate_per_kw: 20190119,
2019 let encoded_value = update_fee.encode();
2020 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
2021 assert_eq!(encoded_value, target_value);
2025 fn encoding_init() {
2026 assert_eq!(msgs::Init {
2027 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
2028 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
2029 assert_eq!(msgs::Init {
2030 features: InitFeatures::from_le_bytes(vec![0xFF]),
2031 }.encode(), hex::decode("0001ff0001ff").unwrap());
2032 assert_eq!(msgs::Init {
2033 features: InitFeatures::from_le_bytes(vec![]),
2034 }.encode(), hex::decode("00000000").unwrap());
2038 fn encoding_error() {
2039 let error = msgs::ErrorMessage {
2040 channel_id: [2; 32],
2041 data: String::from("rust-lightning"),
2043 let encoded_value = error.encode();
2044 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2045 assert_eq!(encoded_value, target_value);
2049 fn encoding_ping() {
2050 let ping = msgs::Ping {
2054 let encoded_value = ping.encode();
2055 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2056 assert_eq!(encoded_value, target_value);
2060 fn encoding_pong() {
2061 let pong = msgs::Pong {
2064 let encoded_value = pong.encode();
2065 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2066 assert_eq!(encoded_value, target_value);
2070 fn encoding_legacy_onion_hop_data() {
2071 let msg = msgs::OnionHopData {
2072 format: OnionHopDataFormat::Legacy {
2073 short_channel_id: 0xdeadbeef1bad1dea,
2075 amt_to_forward: 0x0badf00d01020304,
2076 outgoing_cltv_value: 0xffffffff,
2078 let encoded_value = msg.encode();
2079 let target_value = hex::decode("00deadbeef1bad1dea0badf00d01020304ffffffff000000000000000000000000").unwrap();
2080 assert_eq!(encoded_value, target_value);
2084 fn encoding_nonfinal_onion_hop_data() {
2085 let mut msg = msgs::OnionHopData {
2086 format: OnionHopDataFormat::NonFinalNode {
2087 short_channel_id: 0xdeadbeef1bad1dea,
2089 amt_to_forward: 0x0badf00d01020304,
2090 outgoing_cltv_value: 0xffffffff,
2092 let encoded_value = msg.encode();
2093 let target_value = hex::decode("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
2094 assert_eq!(encoded_value, target_value);
2095 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2096 if let OnionHopDataFormat::NonFinalNode { short_channel_id } = msg.format {
2097 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
2098 } else { panic!(); }
2099 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2100 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2104 fn encoding_final_onion_hop_data() {
2105 let mut msg = msgs::OnionHopData {
2106 format: OnionHopDataFormat::FinalNode {
2109 amt_to_forward: 0x0badf00d01020304,
2110 outgoing_cltv_value: 0xffffffff,
2112 let encoded_value = msg.encode();
2113 let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
2114 assert_eq!(encoded_value, target_value);
2115 msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2116 if let OnionHopDataFormat::FinalNode { payment_data: None } = msg.format { } else { panic!(); }
2117 assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2118 assert_eq!(msg.outgoing_cltv_value, 0xffffffff);