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};
34 use ln::channelmanager::{PaymentPreimage, PaymentHash};
36 /// An error in decoding a message or struct.
38 pub enum DecodeError {
39 /// A version byte specified something we don't know how to handle.
40 /// Includes unknown realm byte in an OnionHopData packet
42 /// Unknown feature mandating we fail to parse message
43 UnknownRequiredFeature,
44 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
45 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
49 /// node_announcement included more than one address of a given type!
50 ExtraAddressesPerType,
51 /// A length descriptor in the packet didn't describe the later data correctly
53 /// Error from std::io
57 /// An init message to be sent or received from a peer
59 pub(crate) features: InitFeatures,
62 /// An error message to be sent or received from a peer
64 pub struct ErrorMessage {
65 pub(crate) channel_id: [u8; 32],
66 pub(crate) data: String,
69 /// A ping message to be sent or received from a peer
71 pub(crate) ponglen: u16,
72 pub(crate) byteslen: u16,
75 /// A pong message to be sent or received from a peer
77 pub(crate) byteslen: u16,
80 /// An open_channel message to be sent or received from a peer
82 pub struct OpenChannel {
83 pub(crate) chain_hash: Sha256dHash,
84 pub(crate) temporary_channel_id: [u8; 32],
85 pub(crate) funding_satoshis: u64,
86 pub(crate) push_msat: u64,
87 pub(crate) dust_limit_satoshis: u64,
88 pub(crate) max_htlc_value_in_flight_msat: u64,
89 pub(crate) channel_reserve_satoshis: u64,
90 pub(crate) htlc_minimum_msat: u64,
91 pub(crate) feerate_per_kw: u32,
92 pub(crate) to_self_delay: u16,
93 pub(crate) max_accepted_htlcs: u16,
94 pub(crate) funding_pubkey: PublicKey,
95 pub(crate) revocation_basepoint: PublicKey,
96 pub(crate) payment_basepoint: PublicKey,
97 pub(crate) delayed_payment_basepoint: PublicKey,
98 pub(crate) htlc_basepoint: PublicKey,
99 pub(crate) first_per_commitment_point: PublicKey,
100 pub(crate) channel_flags: u8,
101 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
104 /// An accept_channel message to be sent or received from a peer
106 pub struct AcceptChannel {
107 pub(crate) temporary_channel_id: [u8; 32],
108 pub(crate) dust_limit_satoshis: u64,
109 pub(crate) max_htlc_value_in_flight_msat: u64,
110 pub(crate) channel_reserve_satoshis: u64,
111 pub(crate) htlc_minimum_msat: u64,
112 pub(crate) minimum_depth: u32,
113 pub(crate) to_self_delay: u16,
114 pub(crate) max_accepted_htlcs: u16,
115 pub(crate) funding_pubkey: PublicKey,
116 pub(crate) revocation_basepoint: PublicKey,
117 pub(crate) payment_basepoint: PublicKey,
118 pub(crate) delayed_payment_basepoint: PublicKey,
119 pub(crate) htlc_basepoint: PublicKey,
120 pub(crate) first_per_commitment_point: PublicKey,
121 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
124 /// A funding_created message to be sent or received from a peer
126 pub struct FundingCreated {
127 pub(crate) temporary_channel_id: [u8; 32],
128 pub(crate) funding_txid: Sha256dHash,
129 pub(crate) funding_output_index: u16,
130 pub(crate) signature: Signature,
133 /// A funding_signed message to be sent or received from a peer
135 pub struct FundingSigned {
136 pub(crate) channel_id: [u8; 32],
137 pub(crate) signature: Signature,
140 /// A funding_locked message to be sent or received from a peer
141 #[derive(Clone, PartialEq)]
142 #[allow(missing_docs)]
143 pub struct FundingLocked {
144 pub channel_id: [u8; 32],
145 pub next_per_commitment_point: PublicKey,
148 /// A shutdown message to be sent or received from a peer
149 #[derive(Clone, PartialEq)]
150 pub struct Shutdown {
151 pub(crate) channel_id: [u8; 32],
152 pub(crate) scriptpubkey: Script,
155 /// A closing_signed message to be sent or received from a peer
156 #[derive(Clone, PartialEq)]
157 pub struct ClosingSigned {
158 pub(crate) channel_id: [u8; 32],
159 pub(crate) fee_satoshis: u64,
160 pub(crate) signature: Signature,
163 /// An update_add_htlc message to be sent or received from a peer
164 #[derive(Clone, PartialEq)]
165 pub struct UpdateAddHTLC {
166 pub(crate) channel_id: [u8; 32],
167 pub(crate) htlc_id: u64,
168 pub(crate) amount_msat: u64,
169 pub(crate) payment_hash: PaymentHash,
170 pub(crate) cltv_expiry: u32,
171 pub(crate) onion_routing_packet: OnionPacket,
174 /// An update_fulfill_htlc message to be sent or received from a peer
175 #[derive(Clone, PartialEq)]
176 pub struct UpdateFulfillHTLC {
177 pub(crate) channel_id: [u8; 32],
178 pub(crate) htlc_id: u64,
179 pub(crate) payment_preimage: PaymentPreimage,
182 /// An update_fail_htlc message to be sent or received from a peer
183 #[derive(Clone, PartialEq)]
184 pub struct UpdateFailHTLC {
185 pub(crate) channel_id: [u8; 32],
186 pub(crate) htlc_id: u64,
187 pub(crate) reason: OnionErrorPacket,
190 /// An update_fail_malformed_htlc message to be sent or received from a peer
191 #[derive(Clone, PartialEq)]
192 pub struct UpdateFailMalformedHTLC {
193 pub(crate) channel_id: [u8; 32],
194 pub(crate) htlc_id: u64,
195 pub(crate) sha256_of_onion: [u8; 32],
196 pub(crate) failure_code: u16,
199 /// A commitment_signed message to be sent or received from a peer
200 #[derive(Clone, PartialEq)]
201 pub struct CommitmentSigned {
202 pub(crate) channel_id: [u8; 32],
203 pub(crate) signature: Signature,
204 pub(crate) htlc_signatures: Vec<Signature>,
207 /// A revoke_and_ack message to be sent or received from a peer
208 #[derive(Clone, PartialEq)]
209 pub struct RevokeAndACK {
210 pub(crate) channel_id: [u8; 32],
211 pub(crate) per_commitment_secret: [u8; 32],
212 pub(crate) next_per_commitment_point: PublicKey,
215 /// An update_fee message to be sent or received from a peer
216 #[derive(PartialEq, Clone)]
217 pub struct UpdateFee {
218 pub(crate) channel_id: [u8; 32],
219 pub(crate) feerate_per_kw: u32,
222 #[derive(PartialEq, Clone)]
223 pub(crate) struct DataLossProtect {
224 pub(crate) your_last_per_commitment_secret: [u8; 32],
225 pub(crate) my_current_per_commitment_point: PublicKey,
228 /// A channel_reestablish message to be sent or received from a peer
229 #[derive(PartialEq, Clone)]
230 pub struct ChannelReestablish {
231 pub(crate) channel_id: [u8; 32],
232 pub(crate) next_local_commitment_number: u64,
233 pub(crate) next_remote_commitment_number: u64,
234 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
237 /// An announcement_signatures message to be sent or received from a peer
238 #[derive(PartialEq, Clone, Debug)]
239 pub struct AnnouncementSignatures {
240 pub(crate) channel_id: [u8; 32],
241 pub(crate) short_channel_id: u64,
242 pub(crate) node_signature: Signature,
243 pub(crate) bitcoin_signature: Signature,
246 /// An address which can be used to connect to a remote peer
247 #[derive(Clone, PartialEq, Debug)]
248 pub enum NetAddress {
249 /// An IPv4 address/port on which the peer is listening.
251 /// The 4-byte IPv4 address
253 /// The port on which the node is listening
256 /// An IPv6 address/port on which the peer is listening.
258 /// The 16-byte IPv6 address
260 /// The port on which the node is listening
263 /// An old-style Tor onion address/port on which the peer is listening.
265 /// The bytes (usually encoded in base32 with ".onion" appended)
267 /// The port on which the node is listening
270 /// A new-style Tor onion address/port on which the peer is listening.
271 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
272 /// wrap as base32 and append ".onion".
274 /// The ed25519 long-term public key of the peer
275 ed25519_pubkey: [u8; 32],
276 /// The checksum of the pubkey and version, as included in the onion address
278 /// The version byte, as defined by the Tor Onion v3 spec.
280 /// The port on which the node is listening
285 fn get_id(&self) -> u8 {
287 &NetAddress::IPv4 {..} => { 1 },
288 &NetAddress::IPv6 {..} => { 2 },
289 &NetAddress::OnionV2 {..} => { 3 },
290 &NetAddress::OnionV3 {..} => { 4 },
294 /// Strict byte-length of address descriptor, 1-byte type not recorded
295 fn len(&self) -> u16 {
297 &NetAddress::IPv4 { .. } => { 6 },
298 &NetAddress::IPv6 { .. } => { 18 },
299 &NetAddress::OnionV2 { .. } => { 12 },
300 &NetAddress::OnionV3 { .. } => { 37 },
305 impl Writeable for NetAddress {
306 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
308 &NetAddress::IPv4 { ref addr, ref port } => {
313 &NetAddress::IPv6 { ref addr, ref port } => {
318 &NetAddress::OnionV2 { ref addr, ref port } => {
323 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
325 ed25519_pubkey.write(writer)?;
326 checksum.write(writer)?;
327 version.write(writer)?;
335 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
336 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
337 let byte = <u8 as Readable<R>>::read(reader)?;
340 Ok(Ok(NetAddress::IPv4 {
341 addr: Readable::read(reader)?,
342 port: Readable::read(reader)?,
346 Ok(Ok(NetAddress::IPv6 {
347 addr: Readable::read(reader)?,
348 port: Readable::read(reader)?,
352 Ok(Ok(NetAddress::OnionV2 {
353 addr: Readable::read(reader)?,
354 port: Readable::read(reader)?,
358 Ok(Ok(NetAddress::OnionV3 {
359 ed25519_pubkey: Readable::read(reader)?,
360 checksum: Readable::read(reader)?,
361 version: Readable::read(reader)?,
362 port: Readable::read(reader)?,
365 _ => return Ok(Err(byte)),
370 // Only exposed as broadcast of node_announcement should be filtered by node_id
371 /// The unsigned part of a node_announcement
372 #[derive(PartialEq, Clone, Debug)]
373 pub struct UnsignedNodeAnnouncement {
374 pub(crate) features: NodeFeatures,
375 pub(crate) timestamp: u32,
376 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
378 pub node_id: PublicKey,
379 pub(crate) rgb: [u8; 3],
380 pub(crate) alias: [u8; 32],
381 /// List of addresses on which this node is reachable. Note that you may only have up to one
382 /// address of each type, if you have more, they may be silently discarded or we may panic!
383 pub(crate) addresses: Vec<NetAddress>,
384 pub(crate) excess_address_data: Vec<u8>,
385 pub(crate) excess_data: Vec<u8>,
387 #[derive(PartialEq, Clone)]
388 /// A node_announcement message to be sent or received from a peer
389 pub struct NodeAnnouncement {
390 pub(crate) signature: Signature,
391 pub(crate) contents: UnsignedNodeAnnouncement,
394 // Only exposed as broadcast of channel_announcement should be filtered by node_id
395 /// The unsigned part of a channel_announcement
396 #[derive(PartialEq, Clone, Debug)]
397 pub struct UnsignedChannelAnnouncement {
398 pub(crate) features: ChannelFeatures,
399 pub(crate) chain_hash: Sha256dHash,
400 pub(crate) short_channel_id: u64,
401 /// One of the two node_ids which are endpoints of this channel
402 pub node_id_1: PublicKey,
403 /// The other of the two node_ids which are endpoints of this channel
404 pub node_id_2: PublicKey,
405 pub(crate) bitcoin_key_1: PublicKey,
406 pub(crate) bitcoin_key_2: PublicKey,
407 pub(crate) excess_data: Vec<u8>,
409 /// A channel_announcement message to be sent or received from a peer
410 #[derive(PartialEq, Clone, Debug)]
411 pub struct ChannelAnnouncement {
412 pub(crate) node_signature_1: Signature,
413 pub(crate) node_signature_2: Signature,
414 pub(crate) bitcoin_signature_1: Signature,
415 pub(crate) bitcoin_signature_2: Signature,
416 pub(crate) contents: UnsignedChannelAnnouncement,
419 #[derive(PartialEq, Clone, Debug)]
420 pub(crate) struct UnsignedChannelUpdate {
421 pub(crate) chain_hash: Sha256dHash,
422 pub(crate) short_channel_id: u64,
423 pub(crate) timestamp: u32,
424 pub(crate) flags: u16,
425 pub(crate) cltv_expiry_delta: u16,
426 pub(crate) htlc_minimum_msat: u64,
427 pub(crate) fee_base_msat: u32,
428 pub(crate) fee_proportional_millionths: u32,
429 pub(crate) excess_data: Vec<u8>,
431 /// A channel_update message to be sent or received from a peer
432 #[derive(PartialEq, Clone, Debug)]
433 pub struct ChannelUpdate {
434 pub(crate) signature: Signature,
435 pub(crate) contents: UnsignedChannelUpdate,
438 /// Used to put an error message in a LightningError
440 pub enum ErrorAction {
441 /// The peer took some action which made us think they were useless. Disconnect them.
443 /// An error message which we should make an effort to send before we disconnect.
444 msg: Option<ErrorMessage>
446 /// The peer did something harmless that we weren't able to process, just log and ignore
448 /// The peer did something incorrect. Tell them.
450 /// The message to send.
455 /// An Err type for failure to process messages.
456 pub struct LightningError {
457 /// A human-readable message describing the error
458 pub err: &'static str,
459 /// The action which should be taken against the offending peer.
460 pub action: ErrorAction,
463 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
464 /// transaction updates if they were pending.
465 #[derive(PartialEq, Clone)]
466 pub struct CommitmentUpdate {
467 /// update_add_htlc messages which should be sent
468 pub update_add_htlcs: Vec<UpdateAddHTLC>,
469 /// update_fulfill_htlc messages which should be sent
470 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
471 /// update_fail_htlc messages which should be sent
472 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
473 /// update_fail_malformed_htlc messages which should be sent
474 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
475 /// An update_fee message which should be sent
476 pub update_fee: Option<UpdateFee>,
477 /// Finally, the commitment_signed message which should be sent
478 pub commitment_signed: CommitmentSigned,
481 /// The information we received from a peer along the route of a payment we originated. This is
482 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
483 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
485 pub enum HTLCFailChannelUpdate {
486 /// We received an error which included a full ChannelUpdate message.
487 ChannelUpdateMessage {
488 /// The unwrapped message we received
491 /// We received an error which indicated only that a channel has been closed
493 /// The short_channel_id which has now closed.
494 short_channel_id: u64,
495 /// when this true, this channel should be permanently removed from the
496 /// consideration. Otherwise, this channel can be restored as new channel_update is received
499 /// We received an error which indicated only that a node has failed
501 /// The node_id that has failed.
503 /// when this true, node should be permanently removed from the
504 /// consideration. Otherwise, the channels connected to this node can be
505 /// restored as new channel_update is received
510 /// Messages could have optional fields to use with extended features
511 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
512 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
513 /// separate enum type for them.
514 #[derive(Clone, PartialEq)]
515 pub enum OptionalField<T> {
516 /// Optional field is included in message
518 /// Optional field is absent in message
522 /// A trait to describe an object which can receive channel messages.
524 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
525 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
526 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
528 /// Handle an incoming open_channel message from the given peer.
529 fn handle_open_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &OpenChannel);
530 /// Handle an incoming accept_channel message from the given peer.
531 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_features: InitFeatures, msg: &AcceptChannel);
532 /// Handle an incoming funding_created message from the given peer.
533 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated);
534 /// Handle an incoming funding_signed message from the given peer.
535 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned);
536 /// Handle an incoming funding_locked message from the given peer.
537 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked);
540 /// Handle an incoming shutdown message from the given peer.
541 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown);
542 /// Handle an incoming closing_signed message from the given peer.
543 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned);
546 /// Handle an incoming update_add_htlc message from the given peer.
547 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC);
548 /// Handle an incoming update_fulfill_htlc message from the given peer.
549 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC);
550 /// Handle an incoming update_fail_htlc message from the given peer.
551 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC);
552 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
553 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC);
554 /// Handle an incoming commitment_signed message from the given peer.
555 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned);
556 /// Handle an incoming revoke_and_ack message from the given peer.
557 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK);
559 /// Handle an incoming update_fee message from the given peer.
560 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee);
562 // Channel-to-announce:
563 /// Handle an incoming announcement_signatures message from the given peer.
564 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures);
566 // Connection loss/reestablish:
567 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
568 /// is believed to be possible in the future (eg they're sending us messages we don't
569 /// understand or indicate they require unknown feature bits), no_connection_possible is set
570 /// and any outstanding channels should be failed.
571 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
573 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
574 fn peer_connected(&self, their_node_id: &PublicKey);
575 /// Handle an incoming channel_reestablish message from the given peer.
576 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish);
579 /// Handle an incoming error message from the given peer.
580 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
583 /// A trait to describe an object which can receive routing messages.
584 pub trait RoutingMessageHandler : Send + Sync {
585 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
586 /// false or returning an Err otherwise.
587 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
588 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
589 /// or returning an Err otherwise.
590 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
591 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
592 /// false or returning an Err otherwise.
593 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, LightningError>;
594 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
595 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
596 /// Gets a subset of the channel announcements and updates required to dump our routing table
597 /// to a remote node, starting at the short_channel_id indicated by starting_point and
598 /// including batch_amount entries.
599 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
600 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
601 /// starting at the node *after* the provided publickey and including batch_amount entries.
602 /// If None is provided for starting_point, we start at the first node.
603 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
606 pub(crate) struct OnionRealm0HopData {
607 pub(crate) short_channel_id: u64,
608 pub(crate) amt_to_forward: u64,
609 pub(crate) outgoing_cltv_value: u32,
610 // 12 bytes of 0-padding
613 mod fuzzy_internal_msgs {
614 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
615 // them from untrusted input):
617 use super::OnionRealm0HopData;
618 pub struct OnionHopData {
619 pub(crate) realm: u8,
620 pub(crate) data: OnionRealm0HopData,
621 pub(crate) hmac: [u8; 32],
624 pub struct DecodedOnionErrorPacket {
625 pub(crate) hmac: [u8; 32],
626 pub(crate) failuremsg: Vec<u8>,
627 pub(crate) pad: Vec<u8>,
630 #[cfg(feature = "fuzztarget")]
631 pub use self::fuzzy_internal_msgs::*;
632 #[cfg(not(feature = "fuzztarget"))]
633 pub(crate) use self::fuzzy_internal_msgs::*;
636 pub(crate) struct OnionPacket {
637 pub(crate) version: u8,
638 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
639 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
640 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
641 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
642 pub(crate) hop_data: [u8; 20*65],
643 pub(crate) hmac: [u8; 32],
646 impl PartialEq for OnionPacket {
647 fn eq(&self, other: &OnionPacket) -> bool {
648 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
649 if i != j { return false; }
651 self.version == other.version &&
652 self.public_key == other.public_key &&
653 self.hmac == other.hmac
657 #[derive(Clone, PartialEq)]
658 pub(crate) struct OnionErrorPacket {
659 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
660 // (TODO) We limit it in decode to much lower...
661 pub(crate) data: Vec<u8>,
664 impl Error for DecodeError {
665 fn description(&self) -> &str {
667 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
668 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
669 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
670 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
671 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
672 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
673 DecodeError::Io(ref e) => e.description(),
677 impl fmt::Display for DecodeError {
678 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
679 f.write_str(self.description())
683 impl fmt::Debug for LightningError {
684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
685 f.write_str(self.err)
689 impl From<::std::io::Error> for DecodeError {
690 fn from(e: ::std::io::Error) -> Self {
691 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
692 DecodeError::ShortRead
699 impl Writeable for OptionalField<Script> {
700 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
702 OptionalField::Present(ref script) => {
703 // Note that Writeable for script includes the 16-bit length tag for us
706 OptionalField::Absent => {}
712 impl<R: Read> Readable<R> for OptionalField<Script> {
713 fn read(r: &mut R) -> Result<Self, DecodeError> {
714 match <u16 as Readable<R>>::read(r) {
716 let mut buf = vec![0; len as usize];
717 r.read_exact(&mut buf)?;
718 Ok(OptionalField::Present(Script::from(buf)))
720 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
726 impl_writeable_len_match!(AcceptChannel, {
727 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
730 temporary_channel_id,
732 max_htlc_value_in_flight_msat,
733 channel_reserve_satoshis,
739 revocation_basepoint,
741 delayed_payment_basepoint,
743 first_per_commitment_point,
744 shutdown_scriptpubkey
747 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
754 impl Writeable for ChannelReestablish {
755 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
756 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
757 self.channel_id.write(w)?;
758 self.next_local_commitment_number.write(w)?;
759 self.next_remote_commitment_number.write(w)?;
760 match self.data_loss_protect {
761 OptionalField::Present(ref data_loss_protect) => {
762 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
763 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
765 OptionalField::Absent => {}
771 impl<R: Read> Readable<R> for ChannelReestablish{
772 fn read(r: &mut R) -> Result<Self, DecodeError> {
774 channel_id: Readable::read(r)?,
775 next_local_commitment_number: Readable::read(r)?,
776 next_remote_commitment_number: Readable::read(r)?,
778 match <[u8; 32] as Readable<R>>::read(r) {
779 Ok(your_last_per_commitment_secret) =>
780 OptionalField::Present(DataLossProtect {
781 your_last_per_commitment_secret,
782 my_current_per_commitment_point: Readable::read(r)?,
784 Err(DecodeError::ShortRead) => OptionalField::Absent,
785 Err(e) => return Err(e)
792 impl_writeable!(ClosingSigned, 32+8+64, {
798 impl_writeable_len_match!(CommitmentSigned, {
799 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
806 impl_writeable_len_match!(DecodedOnionErrorPacket, {
807 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
814 impl_writeable!(FundingCreated, 32+32+2+64, {
815 temporary_channel_id,
817 funding_output_index,
821 impl_writeable!(FundingSigned, 32+64, {
826 impl_writeable!(FundingLocked, 32+33, {
828 next_per_commitment_point
831 impl Writeable for Init {
832 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
833 // global_features gets the bottom 13 bits of our features, and local_features gets all of
834 // our relevant feature bits. This keeps us compatible with old nodes.
835 self.features.write_up_to_13(w)?;
836 self.features.write(w)
840 impl<R: Read> Readable<R> for Init {
841 fn read(r: &mut R) -> Result<Self, DecodeError> {
842 let global_features: InitFeatures = Readable::read(r)?;
843 let features: InitFeatures = Readable::read(r)?;
845 features: features.or(global_features),
850 impl_writeable_len_match!(OpenChannel, {
851 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
855 temporary_channel_id,
859 max_htlc_value_in_flight_msat,
860 channel_reserve_satoshis,
866 revocation_basepoint,
868 delayed_payment_basepoint,
870 first_per_commitment_point,
872 shutdown_scriptpubkey
875 impl_writeable!(RevokeAndACK, 32+32+33, {
877 per_commitment_secret,
878 next_per_commitment_point
881 impl_writeable_len_match!(Shutdown, {
882 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
888 impl_writeable_len_match!(UpdateFailHTLC, {
889 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
896 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
903 impl_writeable!(UpdateFee, 32+4, {
908 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
914 impl_writeable_len_match!(OnionErrorPacket, {
915 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
920 impl Writeable for OnionPacket {
921 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
922 w.size_hint(1 + 33 + 20*65 + 32);
923 self.version.write(w)?;
924 match self.public_key {
925 Ok(pubkey) => pubkey.write(w)?,
926 Err(_) => [0u8;33].write(w)?,
928 w.write_all(&self.hop_data)?;
934 impl<R: Read> Readable<R> for OnionPacket {
935 fn read(r: &mut R) -> Result<Self, DecodeError> {
937 version: Readable::read(r)?,
939 let mut buf = [0u8;33];
940 r.read_exact(&mut buf)?;
941 PublicKey::from_slice(&buf)
943 hop_data: Readable::read(r)?,
944 hmac: Readable::read(r)?,
949 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
958 impl Writeable for OnionRealm0HopData {
959 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
961 self.short_channel_id.write(w)?;
962 self.amt_to_forward.write(w)?;
963 self.outgoing_cltv_value.write(w)?;
964 w.write_all(&[0;12])?;
969 impl<R: Read> Readable<R> for OnionRealm0HopData {
970 fn read(r: &mut R) -> Result<Self, DecodeError> {
971 Ok(OnionRealm0HopData {
972 short_channel_id: Readable::read(r)?,
973 amt_to_forward: Readable::read(r)?,
974 outgoing_cltv_value: {
975 let v: u32 = Readable::read(r)?;
976 r.read_exact(&mut [0; 12])?;
983 impl Writeable for OnionHopData {
984 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
986 self.realm.write(w)?;
993 impl<R: Read> Readable<R> for OnionHopData {
994 fn read(r: &mut R) -> Result<Self, DecodeError> {
997 let r: u8 = Readable::read(r)?;
999 return Err(DecodeError::UnknownVersion);
1003 data: Readable::read(r)?,
1004 hmac: Readable::read(r)?,
1009 impl Writeable for Ping {
1010 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1011 w.size_hint(self.byteslen as usize + 4);
1012 self.ponglen.write(w)?;
1013 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1018 impl<R: Read> Readable<R> for Ping {
1019 fn read(r: &mut R) -> Result<Self, DecodeError> {
1021 ponglen: Readable::read(r)?,
1023 let byteslen = Readable::read(r)?;
1024 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1031 impl Writeable for Pong {
1032 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1033 w.size_hint(self.byteslen as usize + 2);
1034 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1039 impl<R: Read> Readable<R> for Pong {
1040 fn read(r: &mut R) -> Result<Self, DecodeError> {
1043 let byteslen = Readable::read(r)?;
1044 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1051 impl Writeable for UnsignedChannelAnnouncement {
1052 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1053 w.size_hint(2 + 2*32 + 4*33 + self.features.byte_count() + self.excess_data.len());
1054 self.features.write(w)?;
1055 self.chain_hash.write(w)?;
1056 self.short_channel_id.write(w)?;
1057 self.node_id_1.write(w)?;
1058 self.node_id_2.write(w)?;
1059 self.bitcoin_key_1.write(w)?;
1060 self.bitcoin_key_2.write(w)?;
1061 w.write_all(&self.excess_data[..])?;
1066 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1067 fn read(r: &mut R) -> Result<Self, DecodeError> {
1069 features: Readable::read(r)?,
1070 chain_hash: Readable::read(r)?,
1071 short_channel_id: Readable::read(r)?,
1072 node_id_1: Readable::read(r)?,
1073 node_id_2: Readable::read(r)?,
1074 bitcoin_key_1: Readable::read(r)?,
1075 bitcoin_key_2: Readable::read(r)?,
1077 let mut excess_data = vec![];
1078 r.read_to_end(&mut excess_data)?;
1085 impl_writeable_len_match!(ChannelAnnouncement, {
1086 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1087 2 + 2*32 + 4*33 + features.byte_count() + excess_data.len() + 4*64 }
1091 bitcoin_signature_1,
1092 bitcoin_signature_2,
1096 impl Writeable for UnsignedChannelUpdate {
1097 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1098 w.size_hint(64 + self.excess_data.len());
1099 self.chain_hash.write(w)?;
1100 self.short_channel_id.write(w)?;
1101 self.timestamp.write(w)?;
1102 self.flags.write(w)?;
1103 self.cltv_expiry_delta.write(w)?;
1104 self.htlc_minimum_msat.write(w)?;
1105 self.fee_base_msat.write(w)?;
1106 self.fee_proportional_millionths.write(w)?;
1107 w.write_all(&self.excess_data[..])?;
1112 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1113 fn read(r: &mut R) -> Result<Self, DecodeError> {
1115 chain_hash: Readable::read(r)?,
1116 short_channel_id: Readable::read(r)?,
1117 timestamp: Readable::read(r)?,
1118 flags: Readable::read(r)?,
1119 cltv_expiry_delta: Readable::read(r)?,
1120 htlc_minimum_msat: Readable::read(r)?,
1121 fee_base_msat: Readable::read(r)?,
1122 fee_proportional_millionths: Readable::read(r)?,
1124 let mut excess_data = vec![];
1125 r.read_to_end(&mut excess_data)?;
1132 impl_writeable_len_match!(ChannelUpdate, {
1133 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1134 64 + excess_data.len() + 64 }
1140 impl Writeable for ErrorMessage {
1141 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1142 w.size_hint(32 + 2 + self.data.len());
1143 self.channel_id.write(w)?;
1144 (self.data.len() as u16).write(w)?;
1145 w.write_all(self.data.as_bytes())?;
1150 impl<R: Read> Readable<R> for ErrorMessage {
1151 fn read(r: &mut R) -> Result<Self, DecodeError> {
1153 channel_id: Readable::read(r)?,
1155 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1156 let mut data = vec![];
1157 let data_len = r.read_to_end(&mut data)?;
1158 sz = cmp::min(data_len, sz);
1159 match String::from_utf8(data[..sz as usize].to_vec()) {
1161 Err(_) => return Err(DecodeError::InvalidValue),
1168 impl Writeable for UnsignedNodeAnnouncement {
1169 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1170 w.size_hint(64 + 76 + self.features.byte_count() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1171 self.features.write(w)?;
1172 self.timestamp.write(w)?;
1173 self.node_id.write(w)?;
1174 w.write_all(&self.rgb)?;
1175 self.alias.write(w)?;
1177 let mut addrs_to_encode = self.addresses.clone();
1178 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1179 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1180 let mut addr_len = 0;
1181 for addr in &addrs_to_encode {
1182 addr_len += 1 + addr.len();
1184 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1185 for addr in addrs_to_encode {
1188 w.write_all(&self.excess_address_data[..])?;
1189 w.write_all(&self.excess_data[..])?;
1194 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1195 fn read(r: &mut R) -> Result<Self, DecodeError> {
1196 let features: NodeFeatures = Readable::read(r)?;
1197 let timestamp: u32 = Readable::read(r)?;
1198 let node_id: PublicKey = Readable::read(r)?;
1199 let mut rgb = [0; 3];
1200 r.read_exact(&mut rgb)?;
1201 let alias: [u8; 32] = Readable::read(r)?;
1203 let addr_len: u16 = Readable::read(r)?;
1204 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1205 let mut addr_readpos = 0;
1206 let mut excess = false;
1207 let mut excess_byte = 0;
1209 if addr_len <= addr_readpos { break; }
1210 match Readable::read(r) {
1213 NetAddress::IPv4 { .. } => {
1214 if addresses.len() > 0 {
1215 return Err(DecodeError::ExtraAddressesPerType);
1218 NetAddress::IPv6 { .. } => {
1219 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1220 return Err(DecodeError::ExtraAddressesPerType);
1223 NetAddress::OnionV2 { .. } => {
1224 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1225 return Err(DecodeError::ExtraAddressesPerType);
1228 NetAddress::OnionV3 { .. } => {
1229 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1230 return Err(DecodeError::ExtraAddressesPerType);
1234 if addr_len < addr_readpos + 1 + addr.len() {
1235 return Err(DecodeError::BadLengthDescriptor);
1237 addr_readpos += (1 + addr.len()) as u16;
1238 addresses.push(addr);
1240 Ok(Err(unknown_descriptor)) => {
1242 excess_byte = unknown_descriptor;
1245 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1246 Err(e) => return Err(e),
1250 let mut excess_data = vec![];
1251 let excess_address_data = if addr_readpos < addr_len {
1252 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1253 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1255 excess_address_data[0] = excess_byte;
1260 excess_data.push(excess_byte);
1264 r.read_to_end(&mut excess_data)?;
1265 Ok(UnsignedNodeAnnouncement {
1272 excess_address_data,
1278 impl_writeable_len_match!(NodeAnnouncement, {
1279 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1280 64 + 76 + features.byte_count() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1290 use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket};
1291 use ln::channelmanager::{PaymentPreimage, PaymentHash};
1292 use util::ser::Writeable;
1294 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1295 use bitcoin_hashes::hex::FromHex;
1296 use bitcoin::util::address::Address;
1297 use bitcoin::network::constants::Network;
1298 use bitcoin::blockdata::script::Builder;
1299 use bitcoin::blockdata::opcodes;
1301 use secp256k1::key::{PublicKey,SecretKey};
1302 use secp256k1::{Secp256k1, Message};
1305 fn encoding_channel_reestablish_no_secret() {
1306 let cr = msgs::ChannelReestablish {
1307 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],
1308 next_local_commitment_number: 3,
1309 next_remote_commitment_number: 4,
1310 data_loss_protect: OptionalField::Absent,
1313 let encoded_value = cr.encode();
1316 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]
1321 fn encoding_channel_reestablish_with_secret() {
1323 let secp_ctx = Secp256k1::new();
1324 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1327 let cr = msgs::ChannelReestablish {
1328 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],
1329 next_local_commitment_number: 3,
1330 next_remote_commitment_number: 4,
1331 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1334 let encoded_value = cr.encode();
1337 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]
1341 macro_rules! get_keys_from {
1342 ($slice: expr, $secp_ctx: expr) => {
1344 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1345 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1351 macro_rules! get_sig_on {
1352 ($privkey: expr, $ctx: expr, $string: expr) => {
1354 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1355 $ctx.sign(&sighash, &$privkey)
1361 fn encoding_announcement_signatures() {
1362 let secp_ctx = Secp256k1::new();
1363 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1364 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1365 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1366 let announcement_signatures = msgs::AnnouncementSignatures {
1367 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],
1368 short_channel_id: 2316138423780173,
1369 node_signature: sig_1,
1370 bitcoin_signature: sig_2,
1373 let encoded_value = announcement_signatures.encode();
1374 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1377 fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
1378 let secp_ctx = Secp256k1::new();
1379 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1380 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1381 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1382 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1383 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1384 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1385 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1386 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1387 let mut features = ChannelFeatures::supported();
1388 if unknown_features_bits {
1389 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
1391 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1393 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1394 short_channel_id: 2316138423780173,
1395 node_id_1: pubkey_1,
1396 node_id_2: pubkey_2,
1397 bitcoin_key_1: pubkey_3,
1398 bitcoin_key_2: pubkey_4,
1399 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1401 let channel_announcement = msgs::ChannelAnnouncement {
1402 node_signature_1: sig_1,
1403 node_signature_2: sig_2,
1404 bitcoin_signature_1: sig_3,
1405 bitcoin_signature_2: sig_4,
1406 contents: unsigned_channel_announcement,
1408 let encoded_value = channel_announcement.encode();
1409 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1410 if unknown_features_bits {
1411 target_value.append(&mut hex::decode("0002ffff").unwrap());
1413 target_value.append(&mut hex::decode("0000").unwrap());
1415 if non_bitcoin_chain_hash {
1416 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1418 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1420 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1422 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1424 assert_eq!(encoded_value, target_value);
1428 fn encoding_channel_announcement() {
1429 do_encoding_channel_announcement(false, false, false);
1430 do_encoding_channel_announcement(true, false, false);
1431 do_encoding_channel_announcement(true, true, false);
1432 do_encoding_channel_announcement(true, true, true);
1433 do_encoding_channel_announcement(false, true, true);
1434 do_encoding_channel_announcement(false, false, true);
1435 do_encoding_channel_announcement(false, true, false);
1436 do_encoding_channel_announcement(true, false, true);
1439 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1440 let secp_ctx = Secp256k1::new();
1441 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1442 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1443 let features = if unknown_features_bits {
1444 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
1446 // Set to some features we may support
1447 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
1449 let mut addresses = Vec::new();
1451 addresses.push(msgs::NetAddress::IPv4 {
1452 addr: [255, 254, 253, 252],
1457 addresses.push(msgs::NetAddress::IPv6 {
1458 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1463 addresses.push(msgs::NetAddress::OnionV2 {
1464 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1469 addresses.push(msgs::NetAddress::OnionV3 {
1470 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],
1476 let mut addr_len = 0;
1477 for addr in &addresses {
1478 addr_len += addr.len() + 1;
1480 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1482 timestamp: 20190119,
1487 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() },
1488 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() },
1490 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1491 let node_announcement = msgs::NodeAnnouncement {
1493 contents: unsigned_node_announcement,
1495 let encoded_value = node_announcement.encode();
1496 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1497 if unknown_features_bits {
1498 target_value.append(&mut hex::decode("0002ffff").unwrap());
1500 target_value.append(&mut hex::decode("000122").unwrap());
1502 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1503 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1505 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1508 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1511 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1514 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1516 if excess_address_data {
1517 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1520 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1522 assert_eq!(encoded_value, target_value);
1526 fn encoding_node_announcement() {
1527 do_encoding_node_announcement(true, true, true, true, true, true, true);
1528 do_encoding_node_announcement(false, false, false, false, false, false, false);
1529 do_encoding_node_announcement(false, true, false, false, false, false, false);
1530 do_encoding_node_announcement(false, false, true, false, false, false, false);
1531 do_encoding_node_announcement(false, false, false, true, false, false, false);
1532 do_encoding_node_announcement(false, false, false, false, true, false, false);
1533 do_encoding_node_announcement(false, false, false, false, false, true, false);
1534 do_encoding_node_announcement(false, true, false, true, false, true, false);
1535 do_encoding_node_announcement(false, false, true, false, true, false, false);
1538 fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
1539 let secp_ctx = Secp256k1::new();
1540 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1541 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1542 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1543 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1544 short_channel_id: 2316138423780173,
1545 timestamp: 20190119,
1546 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
1547 cltv_expiry_delta: 144,
1548 htlc_minimum_msat: 1000000,
1549 fee_base_msat: 10000,
1550 fee_proportional_millionths: 20,
1551 excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1553 let channel_update = msgs::ChannelUpdate {
1555 contents: unsigned_channel_update
1557 let encoded_value = channel_update.encode();
1558 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1559 if non_bitcoin_chain_hash {
1560 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1562 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1564 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1565 if htlc_maximum_msat {
1566 target_value.append(&mut hex::decode("01").unwrap());
1568 target_value.append(&mut hex::decode("00").unwrap());
1570 target_value.append(&mut hex::decode("00").unwrap());
1572 let flag = target_value.last_mut().unwrap();
1576 let flag = target_value.last_mut().unwrap();
1577 *flag = *flag | 1 << 1;
1579 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1580 if htlc_maximum_msat {
1581 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1583 assert_eq!(encoded_value, target_value);
1587 fn encoding_channel_update() {
1588 do_encoding_channel_update(false, false, false, false);
1589 do_encoding_channel_update(true, false, false, false);
1590 do_encoding_channel_update(false, true, false, false);
1591 do_encoding_channel_update(false, false, true, false);
1592 do_encoding_channel_update(false, false, false, true);
1593 do_encoding_channel_update(true, true, true, true);
1596 fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
1597 let secp_ctx = Secp256k1::new();
1598 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1599 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1600 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1601 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1602 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1603 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1604 let open_channel = msgs::OpenChannel {
1605 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1606 temporary_channel_id: [2; 32],
1607 funding_satoshis: 1311768467284833366,
1608 push_msat: 2536655962884945560,
1609 dust_limit_satoshis: 3608586615801332854,
1610 max_htlc_value_in_flight_msat: 8517154655701053848,
1611 channel_reserve_satoshis: 8665828695742877976,
1612 htlc_minimum_msat: 2316138423780173,
1613 feerate_per_kw: 821716,
1614 to_self_delay: 49340,
1615 max_accepted_htlcs: 49340,
1616 funding_pubkey: pubkey_1,
1617 revocation_basepoint: pubkey_2,
1618 payment_basepoint: pubkey_3,
1619 delayed_payment_basepoint: pubkey_4,
1620 htlc_basepoint: pubkey_5,
1621 first_per_commitment_point: pubkey_6,
1622 channel_flags: if random_bit { 1 << 5 } else { 0 },
1623 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1625 let encoded_value = open_channel.encode();
1626 let mut target_value = Vec::new();
1627 if non_bitcoin_chain_hash {
1628 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1630 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1632 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1634 target_value.append(&mut hex::decode("20").unwrap());
1636 target_value.append(&mut hex::decode("00").unwrap());
1639 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1641 assert_eq!(encoded_value, target_value);
1645 fn encoding_open_channel() {
1646 do_encoding_open_channel(false, false, false);
1647 do_encoding_open_channel(true, false, false);
1648 do_encoding_open_channel(false, true, false);
1649 do_encoding_open_channel(false, false, true);
1650 do_encoding_open_channel(true, true, true);
1653 fn do_encoding_accept_channel(shutdown: bool) {
1654 let secp_ctx = Secp256k1::new();
1655 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1656 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1657 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1658 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1659 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1660 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1661 let accept_channel = msgs::AcceptChannel {
1662 temporary_channel_id: [2; 32],
1663 dust_limit_satoshis: 1311768467284833366,
1664 max_htlc_value_in_flight_msat: 2536655962884945560,
1665 channel_reserve_satoshis: 3608586615801332854,
1666 htlc_minimum_msat: 2316138423780173,
1667 minimum_depth: 821716,
1668 to_self_delay: 49340,
1669 max_accepted_htlcs: 49340,
1670 funding_pubkey: pubkey_1,
1671 revocation_basepoint: pubkey_2,
1672 payment_basepoint: pubkey_3,
1673 delayed_payment_basepoint: pubkey_4,
1674 htlc_basepoint: pubkey_5,
1675 first_per_commitment_point: pubkey_6,
1676 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1678 let encoded_value = accept_channel.encode();
1679 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1681 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1683 assert_eq!(encoded_value, target_value);
1687 fn encoding_accept_channel() {
1688 do_encoding_accept_channel(false);
1689 do_encoding_accept_channel(true);
1693 fn encoding_funding_created() {
1694 let secp_ctx = Secp256k1::new();
1695 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1696 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1697 let funding_created = msgs::FundingCreated {
1698 temporary_channel_id: [2; 32],
1699 funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1700 funding_output_index: 255,
1703 let encoded_value = funding_created.encode();
1704 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1705 assert_eq!(encoded_value, target_value);
1709 fn encoding_funding_signed() {
1710 let secp_ctx = Secp256k1::new();
1711 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1712 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1713 let funding_signed = msgs::FundingSigned {
1714 channel_id: [2; 32],
1717 let encoded_value = funding_signed.encode();
1718 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1719 assert_eq!(encoded_value, target_value);
1723 fn encoding_funding_locked() {
1724 let secp_ctx = Secp256k1::new();
1725 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1726 let funding_locked = msgs::FundingLocked {
1727 channel_id: [2; 32],
1728 next_per_commitment_point: pubkey_1,
1730 let encoded_value = funding_locked.encode();
1731 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1732 assert_eq!(encoded_value, target_value);
1735 fn do_encoding_shutdown(script_type: u8) {
1736 let secp_ctx = Secp256k1::new();
1737 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1738 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1739 let shutdown = msgs::Shutdown {
1740 channel_id: [2; 32],
1741 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() },
1743 let encoded_value = shutdown.encode();
1744 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1745 if script_type == 1 {
1746 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1747 } else if script_type == 2 {
1748 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1749 } else if script_type == 3 {
1750 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1751 } else if script_type == 4 {
1752 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1754 assert_eq!(encoded_value, target_value);
1758 fn encoding_shutdown() {
1759 do_encoding_shutdown(1);
1760 do_encoding_shutdown(2);
1761 do_encoding_shutdown(3);
1762 do_encoding_shutdown(4);
1766 fn encoding_closing_signed() {
1767 let secp_ctx = Secp256k1::new();
1768 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1769 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1770 let closing_signed = msgs::ClosingSigned {
1771 channel_id: [2; 32],
1772 fee_satoshis: 2316138423780173,
1775 let encoded_value = closing_signed.encode();
1776 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1777 assert_eq!(encoded_value, target_value);
1781 fn encoding_update_add_htlc() {
1782 let secp_ctx = Secp256k1::new();
1783 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1784 let onion_routing_packet = msgs::OnionPacket {
1786 public_key: Ok(pubkey_1),
1787 hop_data: [1; 20*65],
1790 let update_add_htlc = msgs::UpdateAddHTLC {
1791 channel_id: [2; 32],
1792 htlc_id: 2316138423780173,
1793 amount_msat: 3608586615801332854,
1794 payment_hash: PaymentHash([1; 32]),
1795 cltv_expiry: 821716,
1796 onion_routing_packet
1798 let encoded_value = update_add_htlc.encode();
1799 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
1800 assert_eq!(encoded_value, target_value);
1804 fn encoding_update_fulfill_htlc() {
1805 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
1806 channel_id: [2; 32],
1807 htlc_id: 2316138423780173,
1808 payment_preimage: PaymentPreimage([1; 32]),
1810 let encoded_value = update_fulfill_htlc.encode();
1811 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
1812 assert_eq!(encoded_value, target_value);
1816 fn encoding_update_fail_htlc() {
1817 let reason = OnionErrorPacket {
1818 data: [1; 32].to_vec(),
1820 let update_fail_htlc = msgs::UpdateFailHTLC {
1821 channel_id: [2; 32],
1822 htlc_id: 2316138423780173,
1825 let encoded_value = update_fail_htlc.encode();
1826 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
1827 assert_eq!(encoded_value, target_value);
1831 fn encoding_update_fail_malformed_htlc() {
1832 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
1833 channel_id: [2; 32],
1834 htlc_id: 2316138423780173,
1835 sha256_of_onion: [1; 32],
1838 let encoded_value = update_fail_malformed_htlc.encode();
1839 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
1840 assert_eq!(encoded_value, target_value);
1843 fn do_encoding_commitment_signed(htlcs: bool) {
1844 let secp_ctx = Secp256k1::new();
1845 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1846 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1847 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1848 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1849 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1850 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1851 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1852 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1853 let commitment_signed = msgs::CommitmentSigned {
1854 channel_id: [2; 32],
1856 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
1858 let encoded_value = commitment_signed.encode();
1859 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1861 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1863 target_value.append(&mut hex::decode("0000").unwrap());
1865 assert_eq!(encoded_value, target_value);
1869 fn encoding_commitment_signed() {
1870 do_encoding_commitment_signed(true);
1871 do_encoding_commitment_signed(false);
1875 fn encoding_revoke_and_ack() {
1876 let secp_ctx = Secp256k1::new();
1877 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1878 let raa = msgs::RevokeAndACK {
1879 channel_id: [2; 32],
1880 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],
1881 next_per_commitment_point: pubkey_1,
1883 let encoded_value = raa.encode();
1884 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1885 assert_eq!(encoded_value, target_value);
1889 fn encoding_update_fee() {
1890 let update_fee = msgs::UpdateFee {
1891 channel_id: [2; 32],
1892 feerate_per_kw: 20190119,
1894 let encoded_value = update_fee.encode();
1895 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
1896 assert_eq!(encoded_value, target_value);
1900 fn encoding_init() {
1901 assert_eq!(msgs::Init {
1902 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
1903 }.encode(), hex::decode("00023fff0003ffffff").unwrap());
1904 assert_eq!(msgs::Init {
1905 features: InitFeatures::from_le_bytes(vec![0xFF]),
1906 }.encode(), hex::decode("0001ff0001ff").unwrap());
1907 assert_eq!(msgs::Init {
1908 features: InitFeatures::from_le_bytes(vec![]),
1909 }.encode(), hex::decode("00000000").unwrap());
1913 fn encoding_error() {
1914 let error = msgs::ErrorMessage {
1915 channel_id: [2; 32],
1916 data: String::from("rust-lightning"),
1918 let encoded_value = error.encode();
1919 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
1920 assert_eq!(encoded_value, target_value);
1924 fn encoding_ping() {
1925 let ping = msgs::Ping {
1929 let encoded_value = ping.encode();
1930 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
1931 assert_eq!(encoded_value, target_value);
1935 fn encoding_pong() {
1936 let pong = msgs::Pong {
1939 let encoded_value = pong.encode();
1940 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
1941 assert_eq!(encoded_value, target_value);