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 std::error::Error;
27 use std::result::Result;
30 use util::ser::{Readable, Writeable, Writer};
32 use ln::channelmanager::{PaymentPreimage, PaymentHash};
34 /// An error in decoding a message or struct.
36 pub enum DecodeError {
37 /// A version byte specified something we don't know how to handle.
38 /// Includes unknown realm byte in an OnionHopData packet
40 /// Unknown feature mandating we fail to parse message
41 UnknownRequiredFeature,
42 /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0
43 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, etc
47 /// node_announcement included more than one address of a given type!
48 ExtraAddressesPerType,
49 /// A length descriptor in the packet didn't describe the later data correctly
51 /// Error from std::io
55 /// Tracks localfeatures which are only in init messages
56 #[derive(Clone, PartialEq)]
57 pub struct LocalFeatures {
62 /// Create a blank LocalFeatures flags (visibility extended for fuzz tests)
63 pub fn new() -> LocalFeatures {
69 pub(crate) fn supports_data_loss_protect(&self) -> bool {
70 self.flags.len() > 0 && (self.flags[0] & 3) != 0
72 pub(crate) fn requires_data_loss_protect(&self) -> bool {
73 self.flags.len() > 0 && (self.flags[0] & 1) != 0
76 pub(crate) fn initial_routing_sync(&self) -> bool {
77 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
79 pub(crate) fn set_initial_routing_sync(&mut self) {
80 if self.flags.len() == 0 {
81 self.flags.resize(1, 1 << 3);
83 self.flags[0] |= 1 << 3;
87 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
88 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
90 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
91 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
94 pub(crate) fn requires_unknown_bits(&self) -> bool {
95 self.flags.iter().enumerate().any(|(idx, &byte)| {
96 ( idx != 0 && (byte & 0x55) != 0 ) || ( idx == 0 && (byte & 0x14) != 0 )
100 pub(crate) fn supports_unknown_bits(&self) -> bool {
101 self.flags.iter().enumerate().any(|(idx, &byte)| {
102 ( idx != 0 && byte != 0 ) || ( idx == 0 && (byte & 0xc4) != 0 )
107 /// Tracks globalfeatures which are in init messages and routing announcements
108 #[derive(Clone, PartialEq, Debug)]
109 pub struct GlobalFeatures {
112 // Used to test encoding of diverse msgs
117 impl GlobalFeatures {
118 pub(crate) fn new() -> GlobalFeatures {
124 pub(crate) fn requires_unknown_bits(&self) -> bool {
125 for &byte in self.flags.iter() {
126 if (byte & 0x55) != 0 {
133 pub(crate) fn supports_unknown_bits(&self) -> bool {
134 for &byte in self.flags.iter() {
143 /// An init message to be sent or received from a peer
145 pub(crate) global_features: GlobalFeatures,
146 pub(crate) local_features: LocalFeatures,
149 /// An error message to be sent or received from a peer
151 pub struct ErrorMessage {
152 pub(crate) channel_id: [u8; 32],
153 pub(crate) data: String,
156 /// A ping message to be sent or received from a peer
158 pub(crate) ponglen: u16,
159 pub(crate) byteslen: u16,
162 /// A pong message to be sent or received from a peer
164 pub(crate) byteslen: u16,
167 /// An open_channel message to be sent or received from a peer
169 pub struct OpenChannel {
170 pub(crate) chain_hash: Sha256dHash,
171 pub(crate) temporary_channel_id: [u8; 32],
172 pub(crate) funding_satoshis: u64,
173 pub(crate) push_msat: u64,
174 pub(crate) dust_limit_satoshis: u64,
175 pub(crate) max_htlc_value_in_flight_msat: u64,
176 pub(crate) channel_reserve_satoshis: u64,
177 pub(crate) htlc_minimum_msat: u64,
178 pub(crate) feerate_per_kw: u32,
179 pub(crate) to_self_delay: u16,
180 pub(crate) max_accepted_htlcs: u16,
181 pub(crate) funding_pubkey: PublicKey,
182 pub(crate) revocation_basepoint: PublicKey,
183 pub(crate) payment_basepoint: PublicKey,
184 pub(crate) delayed_payment_basepoint: PublicKey,
185 pub(crate) htlc_basepoint: PublicKey,
186 pub(crate) first_per_commitment_point: PublicKey,
187 pub(crate) channel_flags: u8,
188 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
191 /// An accept_channel message to be sent or received from a peer
193 pub struct AcceptChannel {
194 pub(crate) temporary_channel_id: [u8; 32],
195 pub(crate) dust_limit_satoshis: u64,
196 pub(crate) max_htlc_value_in_flight_msat: u64,
197 pub(crate) channel_reserve_satoshis: u64,
198 pub(crate) htlc_minimum_msat: u64,
199 pub(crate) minimum_depth: u32,
200 pub(crate) to_self_delay: u16,
201 pub(crate) max_accepted_htlcs: u16,
202 pub(crate) funding_pubkey: PublicKey,
203 pub(crate) revocation_basepoint: PublicKey,
204 pub(crate) payment_basepoint: PublicKey,
205 pub(crate) delayed_payment_basepoint: PublicKey,
206 pub(crate) htlc_basepoint: PublicKey,
207 pub(crate) first_per_commitment_point: PublicKey,
208 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
211 /// A funding_created message to be sent or received from a peer
213 pub struct FundingCreated {
214 pub(crate) temporary_channel_id: [u8; 32],
215 pub(crate) funding_txid: Sha256dHash,
216 pub(crate) funding_output_index: u16,
217 pub(crate) signature: Signature,
220 /// A funding_signed message to be sent or received from a peer
222 pub struct FundingSigned {
223 pub(crate) channel_id: [u8; 32],
224 pub(crate) signature: Signature,
227 /// A funding_locked message to be sent or received from a peer
228 #[derive(Clone, PartialEq)]
229 pub struct FundingLocked {
230 pub(crate) channel_id: [u8; 32],
231 pub(crate) next_per_commitment_point: PublicKey,
234 /// A shutdown message to be sent or received from a peer
235 #[derive(Clone, PartialEq)]
236 pub struct Shutdown {
237 pub(crate) channel_id: [u8; 32],
238 pub(crate) scriptpubkey: Script,
241 /// A closing_signed message to be sent or received from a peer
242 #[derive(Clone, PartialEq)]
243 pub struct ClosingSigned {
244 pub(crate) channel_id: [u8; 32],
245 pub(crate) fee_satoshis: u64,
246 pub(crate) signature: Signature,
249 /// An update_add_htlc message to be sent or received from a peer
250 #[derive(Clone, PartialEq)]
251 pub struct UpdateAddHTLC {
252 pub(crate) channel_id: [u8; 32],
253 pub(crate) htlc_id: u64,
254 pub(crate) amount_msat: u64,
255 pub(crate) payment_hash: PaymentHash,
256 pub(crate) cltv_expiry: u32,
257 pub(crate) onion_routing_packet: OnionPacket,
260 /// An update_fulfill_htlc message to be sent or received from a peer
261 #[derive(Clone, PartialEq)]
262 pub struct UpdateFulfillHTLC {
263 pub(crate) channel_id: [u8; 32],
264 pub(crate) htlc_id: u64,
265 pub(crate) payment_preimage: PaymentPreimage,
268 /// An update_fail_htlc message to be sent or received from a peer
269 #[derive(Clone, PartialEq)]
270 pub struct UpdateFailHTLC {
271 pub(crate) channel_id: [u8; 32],
272 pub(crate) htlc_id: u64,
273 pub(crate) reason: OnionErrorPacket,
276 /// An update_fail_malformed_htlc message to be sent or received from a peer
277 #[derive(Clone, PartialEq)]
278 pub struct UpdateFailMalformedHTLC {
279 pub(crate) channel_id: [u8; 32],
280 pub(crate) htlc_id: u64,
281 pub(crate) sha256_of_onion: [u8; 32],
282 pub(crate) failure_code: u16,
285 /// A commitment_signed message to be sent or received from a peer
286 #[derive(Clone, PartialEq)]
287 pub struct CommitmentSigned {
288 pub(crate) channel_id: [u8; 32],
289 pub(crate) signature: Signature,
290 pub(crate) htlc_signatures: Vec<Signature>,
293 /// A revoke_and_ack message to be sent or received from a peer
294 #[derive(Clone, PartialEq)]
295 pub struct RevokeAndACK {
296 pub(crate) channel_id: [u8; 32],
297 pub(crate) per_commitment_secret: [u8; 32],
298 pub(crate) next_per_commitment_point: PublicKey,
301 /// An update_fee message to be sent or received from a peer
302 #[derive(PartialEq, Clone)]
303 pub struct UpdateFee {
304 pub(crate) channel_id: [u8; 32],
305 pub(crate) feerate_per_kw: u32,
308 #[derive(PartialEq, Clone)]
309 pub(crate) struct DataLossProtect {
310 pub(crate) your_last_per_commitment_secret: [u8; 32],
311 pub(crate) my_current_per_commitment_point: PublicKey,
314 /// A channel_reestablish message to be sent or received from a peer
315 #[derive(PartialEq, Clone)]
316 pub struct ChannelReestablish {
317 pub(crate) channel_id: [u8; 32],
318 pub(crate) next_local_commitment_number: u64,
319 pub(crate) next_remote_commitment_number: u64,
320 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
323 /// An announcement_signatures message to be sent or received from a peer
324 #[derive(PartialEq, Clone, Debug)]
325 pub struct AnnouncementSignatures {
326 pub(crate) channel_id: [u8; 32],
327 pub(crate) short_channel_id: u64,
328 pub(crate) node_signature: Signature,
329 pub(crate) bitcoin_signature: Signature,
332 /// An address which can be used to connect to a remote peer
333 #[derive(Clone, PartialEq, Debug)]
334 pub enum NetAddress {
335 /// An IPv4 address/port on which the peer is listening.
337 /// The 4-byte IPv4 address
339 /// The port on which the node is listening
342 /// An IPv6 address/port on which the peer is listening.
344 /// The 16-byte IPv6 address
346 /// The port on which the node is listening
349 /// An old-style Tor onion address/port on which the peer is listening.
351 /// The bytes (usually encoded in base32 with ".onion" appended)
353 /// The port on which the node is listening
356 /// A new-style Tor onion address/port on which the peer is listening.
357 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
358 /// wrap as base32 and append ".onion".
360 /// The ed25519 long-term public key of the peer
361 ed25519_pubkey: [u8; 32],
362 /// The checksum of the pubkey and version, as included in the onion address
364 /// The version byte, as defined by the Tor Onion v3 spec.
366 /// The port on which the node is listening
371 fn get_id(&self) -> u8 {
373 &NetAddress::IPv4 {..} => { 1 },
374 &NetAddress::IPv6 {..} => { 2 },
375 &NetAddress::OnionV2 {..} => { 3 },
376 &NetAddress::OnionV3 {..} => { 4 },
380 /// Strict byte-length of address descriptor, 1-byte type not recorded
381 fn len(&self) -> u16 {
383 &NetAddress::IPv4 { .. } => { 6 },
384 &NetAddress::IPv6 { .. } => { 18 },
385 &NetAddress::OnionV2 { .. } => { 12 },
386 &NetAddress::OnionV3 { .. } => { 37 },
391 impl Writeable for NetAddress {
392 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
394 &NetAddress::IPv4 { ref addr, ref port } => {
399 &NetAddress::IPv6 { ref addr, ref port } => {
404 &NetAddress::OnionV2 { ref addr, ref port } => {
409 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
411 ed25519_pubkey.write(writer)?;
412 checksum.write(writer)?;
413 version.write(writer)?;
421 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
422 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
423 let byte = <u8 as Readable<R>>::read(reader)?;
426 Ok(Ok(NetAddress::IPv4 {
427 addr: Readable::read(reader)?,
428 port: Readable::read(reader)?,
432 Ok(Ok(NetAddress::IPv6 {
433 addr: Readable::read(reader)?,
434 port: Readable::read(reader)?,
438 Ok(Ok(NetAddress::OnionV2 {
439 addr: Readable::read(reader)?,
440 port: Readable::read(reader)?,
444 Ok(Ok(NetAddress::OnionV3 {
445 ed25519_pubkey: Readable::read(reader)?,
446 checksum: Readable::read(reader)?,
447 version: Readable::read(reader)?,
448 port: Readable::read(reader)?,
451 _ => return Ok(Err(byte)),
456 // Only exposed as broadcast of node_announcement should be filtered by node_id
457 /// The unsigned part of a node_announcement
458 #[derive(PartialEq, Clone, Debug)]
459 pub struct UnsignedNodeAnnouncement {
460 pub(crate) features: GlobalFeatures,
461 pub(crate) timestamp: u32,
462 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
464 pub node_id: PublicKey,
465 pub(crate) rgb: [u8; 3],
466 pub(crate) alias: [u8; 32],
467 /// List of addresses on which this node is reachable. Note that you may only have up to one
468 /// address of each type, if you have more, they may be silently discarded or we may panic!
469 pub(crate) addresses: Vec<NetAddress>,
470 pub(crate) excess_address_data: Vec<u8>,
471 pub(crate) excess_data: Vec<u8>,
473 #[derive(PartialEq, Clone)]
474 /// A node_announcement message to be sent or received from a peer
475 pub struct NodeAnnouncement {
476 pub(crate) signature: Signature,
477 pub(crate) contents: UnsignedNodeAnnouncement,
480 // Only exposed as broadcast of channel_announcement should be filtered by node_id
481 /// The unsigned part of a channel_announcement
482 #[derive(PartialEq, Clone, Debug)]
483 pub struct UnsignedChannelAnnouncement {
484 pub(crate) features: GlobalFeatures,
485 pub(crate) chain_hash: Sha256dHash,
486 pub(crate) short_channel_id: u64,
487 /// One of the two node_ids which are endpoints of this channel
488 pub node_id_1: PublicKey,
489 /// The other of the two node_ids which are endpoints of this channel
490 pub node_id_2: PublicKey,
491 pub(crate) bitcoin_key_1: PublicKey,
492 pub(crate) bitcoin_key_2: PublicKey,
493 pub(crate) excess_data: Vec<u8>,
495 /// A channel_announcement message to be sent or received from a peer
496 #[derive(PartialEq, Clone, Debug)]
497 pub struct ChannelAnnouncement {
498 pub(crate) node_signature_1: Signature,
499 pub(crate) node_signature_2: Signature,
500 pub(crate) bitcoin_signature_1: Signature,
501 pub(crate) bitcoin_signature_2: Signature,
502 pub(crate) contents: UnsignedChannelAnnouncement,
505 #[derive(PartialEq, Clone, Debug)]
506 pub(crate) struct UnsignedChannelUpdate {
507 pub(crate) chain_hash: Sha256dHash,
508 pub(crate) short_channel_id: u64,
509 pub(crate) timestamp: u32,
510 pub(crate) flags: u16,
511 pub(crate) cltv_expiry_delta: u16,
512 pub(crate) htlc_minimum_msat: u64,
513 pub(crate) fee_base_msat: u32,
514 pub(crate) fee_proportional_millionths: u32,
515 pub(crate) excess_data: Vec<u8>,
517 /// A channel_update message to be sent or received from a peer
518 #[derive(PartialEq, Clone, Debug)]
519 pub struct ChannelUpdate {
520 pub(crate) signature: Signature,
521 pub(crate) contents: UnsignedChannelUpdate,
524 /// Used to put an error message in a HandleError
526 pub enum ErrorAction {
527 /// The peer took some action which made us think they were useless. Disconnect them.
529 /// An error message which we should make an effort to send before we disconnect.
530 msg: Option<ErrorMessage>
532 /// The peer did something harmless that we weren't able to process, just log and ignore
534 /// The peer did something incorrect. Tell them.
536 /// The message to send.
541 /// An Err type for failure to process messages.
542 pub struct HandleError { //TODO: rename me
543 /// A human-readable message describing the error
544 pub err: &'static str,
545 /// The action which should be taken against the offending peer.
546 pub action: Option<ErrorAction>, //TODO: Make this required
549 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
550 /// transaction updates if they were pending.
551 #[derive(PartialEq, Clone)]
552 pub struct CommitmentUpdate {
553 /// update_add_htlc messages which should be sent
554 pub update_add_htlcs: Vec<UpdateAddHTLC>,
555 /// update_fulfill_htlc messages which should be sent
556 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
557 /// update_fail_htlc messages which should be sent
558 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
559 /// update_fail_malformed_htlc messages which should be sent
560 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
561 /// An update_fee message which should be sent
562 pub update_fee: Option<UpdateFee>,
563 /// Finally, the commitment_signed message which should be sent
564 pub commitment_signed: CommitmentSigned,
567 /// The information we received from a peer along the route of a payment we originated. This is
568 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
569 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
571 pub enum HTLCFailChannelUpdate {
572 /// We received an error which included a full ChannelUpdate message.
573 ChannelUpdateMessage {
574 /// The unwrapped message we received
577 /// We received an error which indicated only that a channel has been closed
579 /// The short_channel_id which has now closed.
580 short_channel_id: u64,
581 /// when this true, this channel should be permanently removed from the
582 /// consideration. Otherwise, this channel can be restored as new channel_update is received
585 /// We received an error which indicated only that a node has failed
587 /// The node_id that has failed.
589 /// when this true, node should be permanently removed from the
590 /// consideration. Otherwise, the channels connected to this node can be
591 /// restored as new channel_update is received
596 /// Messages could have optional fields to use with extended features
597 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
598 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
599 /// separate enum type for them.
600 #[derive(Clone, PartialEq)]
601 pub enum OptionalField<T> {
602 /// Optional field is included in message
604 /// Optional field is absent in message
608 /// A trait to describe an object which can receive channel messages.
610 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
611 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
612 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
614 /// Handle an incoming open_channel message from the given peer.
615 fn handle_open_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &OpenChannel) -> Result<(), HandleError>;
616 /// Handle an incoming accept_channel message from the given peer.
617 fn handle_accept_channel(&self, their_node_id: &PublicKey, their_local_features: LocalFeatures, msg: &AcceptChannel) -> Result<(), HandleError>;
618 /// Handle an incoming funding_created message from the given peer.
619 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
620 /// Handle an incoming funding_signed message from the given peer.
621 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
622 /// Handle an incoming funding_locked message from the given peer.
623 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
626 /// Handle an incoming shutdown message from the given peer.
627 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
628 /// Handle an incoming closing_signed message from the given peer.
629 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
632 /// Handle an incoming update_add_htlc message from the given peer.
633 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
634 /// Handle an incoming update_fulfill_htlc message from the given peer.
635 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
636 /// Handle an incoming update_fail_htlc message from the given peer.
637 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
638 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
639 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
640 /// Handle an incoming commitment_signed message from the given peer.
641 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
642 /// Handle an incoming revoke_and_ack message from the given peer.
643 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
645 /// Handle an incoming update_fee message from the given peer.
646 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
648 // Channel-to-announce:
649 /// Handle an incoming announcement_signatures message from the given peer.
650 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
652 // Connection loss/reestablish:
653 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
654 /// is believed to be possible in the future (eg they're sending us messages we don't
655 /// understand or indicate they require unknown feature bits), no_connection_possible is set
656 /// and any outstanding channels should be failed.
657 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
659 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
660 fn peer_connected(&self, their_node_id: &PublicKey);
661 /// Handle an incoming channel_reestablish message from the given peer.
662 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
665 /// Handle an incoming error message from the given peer.
666 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
669 /// A trait to describe an object which can receive routing messages.
670 pub trait RoutingMessageHandler : Send + Sync {
671 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
672 /// false or returning an Err otherwise.
673 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
674 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
675 /// or returning an Err otherwise.
676 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
677 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
678 /// false or returning an Err otherwise.
679 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
680 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
681 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
682 /// Gets a subset of the channel announcements and updates required to dump our routing table
683 /// to a remote node, starting at the short_channel_id indicated by starting_point and
684 /// including batch_amount entries.
685 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
686 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
687 /// starting at the node *after* the provided publickey and including batch_amount entries.
688 /// If None is provided for starting_point, we start at the first node.
689 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
692 pub(crate) struct OnionRealm0HopData {
693 pub(crate) short_channel_id: u64,
694 pub(crate) amt_to_forward: u64,
695 pub(crate) outgoing_cltv_value: u32,
696 // 12 bytes of 0-padding
699 mod fuzzy_internal_msgs {
700 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
701 // them from untrusted input):
703 use super::OnionRealm0HopData;
704 pub struct OnionHopData {
705 pub(crate) realm: u8,
706 pub(crate) data: OnionRealm0HopData,
707 pub(crate) hmac: [u8; 32],
709 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
711 pub struct DecodedOnionErrorPacket {
712 pub(crate) hmac: [u8; 32],
713 pub(crate) failuremsg: Vec<u8>,
714 pub(crate) pad: Vec<u8>,
717 #[cfg(feature = "fuzztarget")]
718 pub use self::fuzzy_internal_msgs::*;
719 #[cfg(not(feature = "fuzztarget"))]
720 pub(crate) use self::fuzzy_internal_msgs::*;
723 pub(crate) struct OnionPacket {
724 pub(crate) version: u8,
725 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
726 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
727 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
728 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
729 pub(crate) hop_data: [u8; 20*65],
730 pub(crate) hmac: [u8; 32],
733 impl PartialEq for OnionPacket {
734 fn eq(&self, other: &OnionPacket) -> bool {
735 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
736 if i != j { return false; }
738 self.version == other.version &&
739 self.public_key == other.public_key &&
740 self.hmac == other.hmac
744 #[derive(Clone, PartialEq)]
745 pub(crate) struct OnionErrorPacket {
746 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
747 // (TODO) We limit it in decode to much lower...
748 pub(crate) data: Vec<u8>,
751 impl Error for DecodeError {
752 fn description(&self) -> &str {
754 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
755 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
756 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
757 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
758 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
759 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
760 DecodeError::Io(ref e) => e.description(),
764 impl fmt::Display for DecodeError {
765 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
766 f.write_str(self.description())
770 impl fmt::Debug for HandleError {
771 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
772 f.write_str(self.err)
776 impl From<::std::io::Error> for DecodeError {
777 fn from(e: ::std::io::Error) -> Self {
778 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
779 DecodeError::ShortRead
786 impl Writeable for OptionalField<Script> {
787 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
789 OptionalField::Present(ref script) => {
790 // Note that Writeable for script includes the 16-bit length tag for us
793 OptionalField::Absent => {}
799 impl<R: Read> Readable<R> for OptionalField<Script> {
800 fn read(r: &mut R) -> Result<Self, DecodeError> {
801 match <u16 as Readable<R>>::read(r) {
803 let mut buf = vec![0; len as usize];
804 r.read_exact(&mut buf)?;
805 Ok(OptionalField::Present(Script::from(buf)))
807 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
813 impl_writeable_len_match!(AcceptChannel, {
814 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
817 temporary_channel_id,
819 max_htlc_value_in_flight_msat,
820 channel_reserve_satoshis,
826 revocation_basepoint,
828 delayed_payment_basepoint,
830 first_per_commitment_point,
831 shutdown_scriptpubkey
834 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
841 impl Writeable for ChannelReestablish {
842 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
843 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
844 self.channel_id.write(w)?;
845 self.next_local_commitment_number.write(w)?;
846 self.next_remote_commitment_number.write(w)?;
847 match self.data_loss_protect {
848 OptionalField::Present(ref data_loss_protect) => {
849 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
850 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
852 OptionalField::Absent => {}
858 impl<R: Read> Readable<R> for ChannelReestablish{
859 fn read(r: &mut R) -> Result<Self, DecodeError> {
861 channel_id: Readable::read(r)?,
862 next_local_commitment_number: Readable::read(r)?,
863 next_remote_commitment_number: Readable::read(r)?,
865 match <[u8; 32] as Readable<R>>::read(r) {
866 Ok(your_last_per_commitment_secret) =>
867 OptionalField::Present(DataLossProtect {
868 your_last_per_commitment_secret,
869 my_current_per_commitment_point: Readable::read(r)?,
871 Err(DecodeError::ShortRead) => OptionalField::Absent,
872 Err(e) => return Err(e)
879 impl_writeable!(ClosingSigned, 32+8+64, {
885 impl_writeable_len_match!(CommitmentSigned, {
886 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
893 impl_writeable_len_match!(DecodedOnionErrorPacket, {
894 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
901 impl_writeable!(FundingCreated, 32+32+2+64, {
902 temporary_channel_id,
904 funding_output_index,
908 impl_writeable!(FundingSigned, 32+64, {
913 impl_writeable!(FundingLocked, 32+33, {
915 next_per_commitment_point
918 impl_writeable_len_match!(GlobalFeatures, {
919 { GlobalFeatures { ref flags }, flags.len() + 2 }
924 impl_writeable_len_match!(LocalFeatures, {
925 { LocalFeatures { ref flags }, flags.len() + 2 }
930 impl_writeable_len_match!(Init, {
931 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
937 impl_writeable_len_match!(OpenChannel, {
938 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
942 temporary_channel_id,
946 max_htlc_value_in_flight_msat,
947 channel_reserve_satoshis,
953 revocation_basepoint,
955 delayed_payment_basepoint,
957 first_per_commitment_point,
959 shutdown_scriptpubkey
962 impl_writeable!(RevokeAndACK, 32+32+33, {
964 per_commitment_secret,
965 next_per_commitment_point
968 impl_writeable_len_match!(Shutdown, {
969 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
975 impl_writeable_len_match!(UpdateFailHTLC, {
976 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
983 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
990 impl_writeable!(UpdateFee, 32+4, {
995 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1001 impl_writeable_len_match!(OnionErrorPacket, {
1002 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1007 impl Writeable for OnionPacket {
1008 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1009 w.size_hint(1 + 33 + 20*65 + 32);
1010 self.version.write(w)?;
1011 match self.public_key {
1012 Ok(pubkey) => pubkey.write(w)?,
1013 Err(_) => [0u8;33].write(w)?,
1015 w.write_all(&self.hop_data)?;
1016 self.hmac.write(w)?;
1021 impl<R: Read> Readable<R> for OnionPacket {
1022 fn read(r: &mut R) -> Result<Self, DecodeError> {
1024 version: Readable::read(r)?,
1026 let mut buf = [0u8;33];
1027 r.read_exact(&mut buf)?;
1028 PublicKey::from_slice(&buf)
1030 hop_data: Readable::read(r)?,
1031 hmac: Readable::read(r)?,
1036 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1042 onion_routing_packet
1045 impl Writeable for OnionRealm0HopData {
1046 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1048 self.short_channel_id.write(w)?;
1049 self.amt_to_forward.write(w)?;
1050 self.outgoing_cltv_value.write(w)?;
1051 w.write_all(&[0;12])?;
1056 impl<R: Read> Readable<R> for OnionRealm0HopData {
1057 fn read(r: &mut R) -> Result<Self, DecodeError> {
1058 Ok(OnionRealm0HopData {
1059 short_channel_id: Readable::read(r)?,
1060 amt_to_forward: Readable::read(r)?,
1061 outgoing_cltv_value: {
1062 let v: u32 = Readable::read(r)?;
1063 r.read_exact(&mut [0; 12])?;
1070 impl Writeable for OnionHopData {
1071 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1073 self.realm.write(w)?;
1074 self.data.write(w)?;
1075 self.hmac.write(w)?;
1080 impl<R: Read> Readable<R> for OnionHopData {
1081 fn read(r: &mut R) -> Result<Self, DecodeError> {
1084 let r: u8 = Readable::read(r)?;
1086 return Err(DecodeError::UnknownVersion);
1090 data: Readable::read(r)?,
1091 hmac: Readable::read(r)?,
1096 impl Writeable for Ping {
1097 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1098 w.size_hint(self.byteslen as usize + 4);
1099 self.ponglen.write(w)?;
1100 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1105 impl<R: Read> Readable<R> for Ping {
1106 fn read(r: &mut R) -> Result<Self, DecodeError> {
1108 ponglen: Readable::read(r)?,
1110 let byteslen = Readable::read(r)?;
1111 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1118 impl Writeable for Pong {
1119 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1120 w.size_hint(self.byteslen as usize + 2);
1121 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1126 impl<R: Read> Readable<R> for Pong {
1127 fn read(r: &mut R) -> Result<Self, DecodeError> {
1130 let byteslen = Readable::read(r)?;
1131 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1138 impl Writeable for UnsignedChannelAnnouncement {
1139 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1140 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1141 self.features.write(w)?;
1142 self.chain_hash.write(w)?;
1143 self.short_channel_id.write(w)?;
1144 self.node_id_1.write(w)?;
1145 self.node_id_2.write(w)?;
1146 self.bitcoin_key_1.write(w)?;
1147 self.bitcoin_key_2.write(w)?;
1148 w.write_all(&self.excess_data[..])?;
1153 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1154 fn read(r: &mut R) -> Result<Self, DecodeError> {
1157 let f: GlobalFeatures = Readable::read(r)?;
1158 if f.requires_unknown_bits() {
1159 return Err(DecodeError::UnknownRequiredFeature);
1163 chain_hash: Readable::read(r)?,
1164 short_channel_id: Readable::read(r)?,
1165 node_id_1: Readable::read(r)?,
1166 node_id_2: Readable::read(r)?,
1167 bitcoin_key_1: Readable::read(r)?,
1168 bitcoin_key_2: Readable::read(r)?,
1170 let mut excess_data = vec![];
1171 r.read_to_end(&mut excess_data)?;
1178 impl_writeable_len_match!(ChannelAnnouncement, {
1179 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1180 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1184 bitcoin_signature_1,
1185 bitcoin_signature_2,
1189 impl Writeable for UnsignedChannelUpdate {
1190 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1191 w.size_hint(64 + self.excess_data.len());
1192 self.chain_hash.write(w)?;
1193 self.short_channel_id.write(w)?;
1194 self.timestamp.write(w)?;
1195 self.flags.write(w)?;
1196 self.cltv_expiry_delta.write(w)?;
1197 self.htlc_minimum_msat.write(w)?;
1198 self.fee_base_msat.write(w)?;
1199 self.fee_proportional_millionths.write(w)?;
1200 w.write_all(&self.excess_data[..])?;
1205 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1206 fn read(r: &mut R) -> Result<Self, DecodeError> {
1208 chain_hash: Readable::read(r)?,
1209 short_channel_id: Readable::read(r)?,
1210 timestamp: Readable::read(r)?,
1211 flags: Readable::read(r)?,
1212 cltv_expiry_delta: Readable::read(r)?,
1213 htlc_minimum_msat: Readable::read(r)?,
1214 fee_base_msat: Readable::read(r)?,
1215 fee_proportional_millionths: Readable::read(r)?,
1217 let mut excess_data = vec![];
1218 r.read_to_end(&mut excess_data)?;
1225 impl_writeable_len_match!(ChannelUpdate, {
1226 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1227 64 + excess_data.len() + 64 }
1233 impl Writeable for ErrorMessage {
1234 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1235 w.size_hint(32 + 2 + self.data.len());
1236 self.channel_id.write(w)?;
1237 (self.data.len() as u16).write(w)?;
1238 w.write_all(self.data.as_bytes())?;
1243 impl<R: Read> Readable<R> for ErrorMessage {
1244 fn read(r: &mut R) -> Result<Self, DecodeError> {
1246 channel_id: Readable::read(r)?,
1248 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1249 let mut data = vec![];
1250 let data_len = r.read_to_end(&mut data)?;
1251 sz = cmp::min(data_len, sz);
1252 match String::from_utf8(data[..sz as usize].to_vec()) {
1254 Err(_) => return Err(DecodeError::InvalidValue),
1261 impl Writeable for UnsignedNodeAnnouncement {
1262 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1263 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1264 self.features.write(w)?;
1265 self.timestamp.write(w)?;
1266 self.node_id.write(w)?;
1267 w.write_all(&self.rgb)?;
1268 self.alias.write(w)?;
1270 let mut addrs_to_encode = self.addresses.clone();
1271 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1272 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1273 let mut addr_len = 0;
1274 for addr in &addrs_to_encode {
1275 addr_len += 1 + addr.len();
1277 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1278 for addr in addrs_to_encode {
1281 w.write_all(&self.excess_address_data[..])?;
1282 w.write_all(&self.excess_data[..])?;
1287 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1288 fn read(r: &mut R) -> Result<Self, DecodeError> {
1289 let features: GlobalFeatures = Readable::read(r)?;
1290 if features.requires_unknown_bits() {
1291 return Err(DecodeError::UnknownRequiredFeature);
1293 let timestamp: u32 = Readable::read(r)?;
1294 let node_id: PublicKey = Readable::read(r)?;
1295 let mut rgb = [0; 3];
1296 r.read_exact(&mut rgb)?;
1297 let alias: [u8; 32] = Readable::read(r)?;
1299 let addr_len: u16 = Readable::read(r)?;
1300 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1301 let mut addr_readpos = 0;
1302 let mut excess = false;
1303 let mut excess_byte = 0;
1305 if addr_len <= addr_readpos { break; }
1306 match Readable::read(r) {
1309 NetAddress::IPv4 { .. } => {
1310 if addresses.len() > 0 {
1311 return Err(DecodeError::ExtraAddressesPerType);
1314 NetAddress::IPv6 { .. } => {
1315 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1316 return Err(DecodeError::ExtraAddressesPerType);
1319 NetAddress::OnionV2 { .. } => {
1320 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1321 return Err(DecodeError::ExtraAddressesPerType);
1324 NetAddress::OnionV3 { .. } => {
1325 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1326 return Err(DecodeError::ExtraAddressesPerType);
1330 if addr_len < addr_readpos + 1 + addr.len() {
1331 return Err(DecodeError::BadLengthDescriptor);
1333 addr_readpos += (1 + addr.len()) as u16;
1334 addresses.push(addr);
1336 Ok(Err(unknown_descriptor)) => {
1338 excess_byte = unknown_descriptor;
1341 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1342 Err(e) => return Err(e),
1346 let mut excess_data = vec![];
1347 let excess_address_data = if addr_readpos < addr_len {
1348 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1349 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1351 excess_address_data[0] = excess_byte;
1356 excess_data.push(excess_byte);
1360 r.read_to_end(&mut excess_data)?;
1361 Ok(UnsignedNodeAnnouncement {
1368 excess_address_data,
1374 impl_writeable_len_match!(NodeAnnouncement, {
1375 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1376 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1386 use ln::msgs::{GlobalFeatures, LocalFeatures, OptionalField, OnionErrorPacket};
1387 use ln::channelmanager::{PaymentPreimage, PaymentHash};
1388 use util::ser::Writeable;
1390 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1391 use bitcoin_hashes::hex::FromHex;
1392 use bitcoin::util::address::Address;
1393 use bitcoin::network::constants::Network;
1394 use bitcoin::blockdata::script::Builder;
1395 use bitcoin::blockdata::opcodes;
1397 use secp256k1::key::{PublicKey,SecretKey};
1398 use secp256k1::{Secp256k1, Message};
1401 fn encoding_channel_reestablish_no_secret() {
1402 let cr = msgs::ChannelReestablish {
1403 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],
1404 next_local_commitment_number: 3,
1405 next_remote_commitment_number: 4,
1406 data_loss_protect: OptionalField::Absent,
1409 let encoded_value = cr.encode();
1412 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]
1417 fn encoding_channel_reestablish_with_secret() {
1419 let secp_ctx = Secp256k1::new();
1420 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1423 let cr = msgs::ChannelReestablish {
1424 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],
1425 next_local_commitment_number: 3,
1426 next_remote_commitment_number: 4,
1427 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1430 let encoded_value = cr.encode();
1433 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]
1437 macro_rules! get_keys_from {
1438 ($slice: expr, $secp_ctx: expr) => {
1440 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1441 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1447 macro_rules! get_sig_on {
1448 ($privkey: expr, $ctx: expr, $string: expr) => {
1450 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1451 $ctx.sign(&sighash, &$privkey)
1457 fn encoding_announcement_signatures() {
1458 let secp_ctx = Secp256k1::new();
1459 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1460 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1461 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1462 let announcement_signatures = msgs::AnnouncementSignatures {
1463 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],
1464 short_channel_id: 2316138423780173,
1465 node_signature: sig_1,
1466 bitcoin_signature: sig_2,
1469 let encoded_value = announcement_signatures.encode();
1470 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1473 fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
1474 let secp_ctx = Secp256k1::new();
1475 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1476 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1477 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1478 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1479 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1480 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1481 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1482 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1483 let mut features = GlobalFeatures::new();
1484 if unknown_features_bits {
1485 features.flags = vec![0xFF, 0xFF];
1487 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1489 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1490 short_channel_id: 2316138423780173,
1491 node_id_1: pubkey_1,
1492 node_id_2: pubkey_2,
1493 bitcoin_key_1: pubkey_3,
1494 bitcoin_key_2: pubkey_4,
1495 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1497 let channel_announcement = msgs::ChannelAnnouncement {
1498 node_signature_1: sig_1,
1499 node_signature_2: sig_2,
1500 bitcoin_signature_1: sig_3,
1501 bitcoin_signature_2: sig_4,
1502 contents: unsigned_channel_announcement,
1504 let encoded_value = channel_announcement.encode();
1505 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1506 if unknown_features_bits {
1507 target_value.append(&mut hex::decode("0002ffff").unwrap());
1509 target_value.append(&mut hex::decode("0000").unwrap());
1511 if non_bitcoin_chain_hash {
1512 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1514 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1516 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1518 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1520 assert_eq!(encoded_value, target_value);
1524 fn encoding_channel_announcement() {
1525 do_encoding_channel_announcement(false, false, false);
1526 do_encoding_channel_announcement(true, false, false);
1527 do_encoding_channel_announcement(true, true, false);
1528 do_encoding_channel_announcement(true, true, true);
1529 do_encoding_channel_announcement(false, true, true);
1530 do_encoding_channel_announcement(false, false, true);
1531 do_encoding_channel_announcement(false, true, false);
1532 do_encoding_channel_announcement(true, false, true);
1535 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1536 let secp_ctx = Secp256k1::new();
1537 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1538 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1539 let mut features = GlobalFeatures::new();
1540 if unknown_features_bits {
1541 features.flags = vec![0xFF, 0xFF];
1543 let mut addresses = Vec::new();
1545 addresses.push(msgs::NetAddress::IPv4 {
1546 addr: [255, 254, 253, 252],
1551 addresses.push(msgs::NetAddress::IPv6 {
1552 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1557 addresses.push(msgs::NetAddress::OnionV2 {
1558 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1563 addresses.push(msgs::NetAddress::OnionV3 {
1564 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],
1570 let mut addr_len = 0;
1571 for addr in &addresses {
1572 addr_len += addr.len() + 1;
1574 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1576 timestamp: 20190119,
1581 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() },
1582 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() },
1584 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1585 let node_announcement = msgs::NodeAnnouncement {
1587 contents: unsigned_node_announcement,
1589 let encoded_value = node_announcement.encode();
1590 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1591 if unknown_features_bits {
1592 target_value.append(&mut hex::decode("0002ffff").unwrap());
1594 target_value.append(&mut hex::decode("0000").unwrap());
1596 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1597 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1599 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1602 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1605 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1608 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1610 if excess_address_data {
1611 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1614 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1616 assert_eq!(encoded_value, target_value);
1620 fn encoding_node_announcement() {
1621 do_encoding_node_announcement(true, true, true, true, true, true, true);
1622 do_encoding_node_announcement(false, false, false, false, false, false, false);
1623 do_encoding_node_announcement(false, true, false, false, false, false, false);
1624 do_encoding_node_announcement(false, false, true, false, false, false, false);
1625 do_encoding_node_announcement(false, false, false, true, false, false, false);
1626 do_encoding_node_announcement(false, false, false, false, true, false, false);
1627 do_encoding_node_announcement(false, false, false, false, false, true, false);
1628 do_encoding_node_announcement(false, true, false, true, false, true, false);
1629 do_encoding_node_announcement(false, false, true, false, true, false, false);
1632 fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
1633 let secp_ctx = Secp256k1::new();
1634 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1635 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1636 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1637 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1638 short_channel_id: 2316138423780173,
1639 timestamp: 20190119,
1640 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
1641 cltv_expiry_delta: 144,
1642 htlc_minimum_msat: 1000000,
1643 fee_base_msat: 10000,
1644 fee_proportional_millionths: 20,
1645 excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1647 let channel_update = msgs::ChannelUpdate {
1649 contents: unsigned_channel_update
1651 let encoded_value = channel_update.encode();
1652 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1653 if non_bitcoin_chain_hash {
1654 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1656 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1658 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1659 if htlc_maximum_msat {
1660 target_value.append(&mut hex::decode("01").unwrap());
1662 target_value.append(&mut hex::decode("00").unwrap());
1664 target_value.append(&mut hex::decode("00").unwrap());
1666 let flag = target_value.last_mut().unwrap();
1670 let flag = target_value.last_mut().unwrap();
1671 *flag = *flag | 1 << 1;
1673 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1674 if htlc_maximum_msat {
1675 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1677 assert_eq!(encoded_value, target_value);
1681 fn encoding_channel_update() {
1682 do_encoding_channel_update(false, false, false, false);
1683 do_encoding_channel_update(true, false, false, false);
1684 do_encoding_channel_update(false, true, false, false);
1685 do_encoding_channel_update(false, false, true, false);
1686 do_encoding_channel_update(false, false, false, true);
1687 do_encoding_channel_update(true, true, true, true);
1690 fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
1691 let secp_ctx = Secp256k1::new();
1692 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1693 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1694 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1695 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1696 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1697 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1698 let open_channel = msgs::OpenChannel {
1699 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1700 temporary_channel_id: [2; 32],
1701 funding_satoshis: 1311768467284833366,
1702 push_msat: 2536655962884945560,
1703 dust_limit_satoshis: 3608586615801332854,
1704 max_htlc_value_in_flight_msat: 8517154655701053848,
1705 channel_reserve_satoshis: 8665828695742877976,
1706 htlc_minimum_msat: 2316138423780173,
1707 feerate_per_kw: 821716,
1708 to_self_delay: 49340,
1709 max_accepted_htlcs: 49340,
1710 funding_pubkey: pubkey_1,
1711 revocation_basepoint: pubkey_2,
1712 payment_basepoint: pubkey_3,
1713 delayed_payment_basepoint: pubkey_4,
1714 htlc_basepoint: pubkey_5,
1715 first_per_commitment_point: pubkey_6,
1716 channel_flags: if random_bit { 1 << 5 } else { 0 },
1717 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1719 let encoded_value = open_channel.encode();
1720 let mut target_value = Vec::new();
1721 if non_bitcoin_chain_hash {
1722 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1724 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1726 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1728 target_value.append(&mut hex::decode("20").unwrap());
1730 target_value.append(&mut hex::decode("00").unwrap());
1733 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1735 assert_eq!(encoded_value, target_value);
1739 fn encoding_open_channel() {
1740 do_encoding_open_channel(false, false, false);
1741 do_encoding_open_channel(true, false, false);
1742 do_encoding_open_channel(false, true, false);
1743 do_encoding_open_channel(false, false, true);
1744 do_encoding_open_channel(true, true, true);
1747 fn do_encoding_accept_channel(shutdown: bool) {
1748 let secp_ctx = Secp256k1::new();
1749 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1750 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1751 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1752 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1753 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1754 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1755 let accept_channel = msgs::AcceptChannel {
1756 temporary_channel_id: [2; 32],
1757 dust_limit_satoshis: 1311768467284833366,
1758 max_htlc_value_in_flight_msat: 2536655962884945560,
1759 channel_reserve_satoshis: 3608586615801332854,
1760 htlc_minimum_msat: 2316138423780173,
1761 minimum_depth: 821716,
1762 to_self_delay: 49340,
1763 max_accepted_htlcs: 49340,
1764 funding_pubkey: pubkey_1,
1765 revocation_basepoint: pubkey_2,
1766 payment_basepoint: pubkey_3,
1767 delayed_payment_basepoint: pubkey_4,
1768 htlc_basepoint: pubkey_5,
1769 first_per_commitment_point: pubkey_6,
1770 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: pubkey_1}, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1772 let encoded_value = accept_channel.encode();
1773 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1775 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1777 assert_eq!(encoded_value, target_value);
1781 fn encoding_accept_channel() {
1782 do_encoding_accept_channel(false);
1783 do_encoding_accept_channel(true);
1787 fn encoding_funding_created() {
1788 let secp_ctx = Secp256k1::new();
1789 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1790 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1791 let funding_created = msgs::FundingCreated {
1792 temporary_channel_id: [2; 32],
1793 funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1794 funding_output_index: 255,
1797 let encoded_value = funding_created.encode();
1798 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1799 assert_eq!(encoded_value, target_value);
1803 fn encoding_funding_signed() {
1804 let secp_ctx = Secp256k1::new();
1805 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1806 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1807 let funding_signed = msgs::FundingSigned {
1808 channel_id: [2; 32],
1811 let encoded_value = funding_signed.encode();
1812 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1813 assert_eq!(encoded_value, target_value);
1817 fn encoding_funding_locked() {
1818 let secp_ctx = Secp256k1::new();
1819 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1820 let funding_locked = msgs::FundingLocked {
1821 channel_id: [2; 32],
1822 next_per_commitment_point: pubkey_1,
1824 let encoded_value = funding_locked.encode();
1825 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1826 assert_eq!(encoded_value, target_value);
1829 fn do_encoding_shutdown(script_type: u8) {
1830 let secp_ctx = Secp256k1::new();
1831 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1832 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1833 let shutdown = msgs::Shutdown {
1834 channel_id: [2; 32],
1835 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() },
1837 let encoded_value = shutdown.encode();
1838 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1839 if script_type == 1 {
1840 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1841 } else if script_type == 2 {
1842 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1843 } else if script_type == 3 {
1844 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1845 } else if script_type == 4 {
1846 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1848 assert_eq!(encoded_value, target_value);
1852 fn encoding_shutdown() {
1853 do_encoding_shutdown(1);
1854 do_encoding_shutdown(2);
1855 do_encoding_shutdown(3);
1856 do_encoding_shutdown(4);
1860 fn encoding_closing_signed() {
1861 let secp_ctx = Secp256k1::new();
1862 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1863 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1864 let closing_signed = msgs::ClosingSigned {
1865 channel_id: [2; 32],
1866 fee_satoshis: 2316138423780173,
1869 let encoded_value = closing_signed.encode();
1870 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1871 assert_eq!(encoded_value, target_value);
1875 fn encoding_update_add_htlc() {
1876 let secp_ctx = Secp256k1::new();
1877 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1878 let onion_routing_packet = msgs::OnionPacket {
1880 public_key: Ok(pubkey_1),
1881 hop_data: [1; 20*65],
1884 let update_add_htlc = msgs::UpdateAddHTLC {
1885 channel_id: [2; 32],
1886 htlc_id: 2316138423780173,
1887 amount_msat: 3608586615801332854,
1888 payment_hash: PaymentHash([1; 32]),
1889 cltv_expiry: 821716,
1890 onion_routing_packet
1892 let encoded_value = update_add_htlc.encode();
1893 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
1894 assert_eq!(encoded_value, target_value);
1898 fn encoding_update_fulfill_htlc() {
1899 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
1900 channel_id: [2; 32],
1901 htlc_id: 2316138423780173,
1902 payment_preimage: PaymentPreimage([1; 32]),
1904 let encoded_value = update_fulfill_htlc.encode();
1905 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
1906 assert_eq!(encoded_value, target_value);
1910 fn encoding_update_fail_htlc() {
1911 let reason = OnionErrorPacket {
1912 data: [1; 32].to_vec(),
1914 let update_fail_htlc = msgs::UpdateFailHTLC {
1915 channel_id: [2; 32],
1916 htlc_id: 2316138423780173,
1919 let encoded_value = update_fail_htlc.encode();
1920 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
1921 assert_eq!(encoded_value, target_value);
1925 fn encoding_update_fail_malformed_htlc() {
1926 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
1927 channel_id: [2; 32],
1928 htlc_id: 2316138423780173,
1929 sha256_of_onion: [1; 32],
1932 let encoded_value = update_fail_malformed_htlc.encode();
1933 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
1934 assert_eq!(encoded_value, target_value);
1937 fn do_encoding_commitment_signed(htlcs: bool) {
1938 let secp_ctx = Secp256k1::new();
1939 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1940 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1941 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1942 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1943 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1944 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1945 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1946 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1947 let commitment_signed = msgs::CommitmentSigned {
1948 channel_id: [2; 32],
1950 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
1952 let encoded_value = commitment_signed.encode();
1953 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1955 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1957 target_value.append(&mut hex::decode("0000").unwrap());
1959 assert_eq!(encoded_value, target_value);
1963 fn encoding_commitment_signed() {
1964 do_encoding_commitment_signed(true);
1965 do_encoding_commitment_signed(false);
1969 fn encoding_revoke_and_ack() {
1970 let secp_ctx = Secp256k1::new();
1971 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1972 let raa = msgs::RevokeAndACK {
1973 channel_id: [2; 32],
1974 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],
1975 next_per_commitment_point: pubkey_1,
1977 let encoded_value = raa.encode();
1978 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1979 assert_eq!(encoded_value, target_value);
1983 fn encoding_update_fee() {
1984 let update_fee = msgs::UpdateFee {
1985 channel_id: [2; 32],
1986 feerate_per_kw: 20190119,
1988 let encoded_value = update_fee.encode();
1989 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
1990 assert_eq!(encoded_value, target_value);
1993 fn do_encoding_init(unknown_global_bits: bool, initial_routing_sync: bool) {
1994 let mut global = GlobalFeatures::new();
1995 if unknown_global_bits {
1996 global.flags = vec![0xFF, 0xFF];
1998 let mut local = LocalFeatures::new();
1999 if initial_routing_sync {
2000 local.set_initial_routing_sync();
2002 let init = msgs::Init {
2003 global_features: global,
2004 local_features: local,
2006 let encoded_value = init.encode();
2007 let mut target_value = Vec::new();
2008 if unknown_global_bits {
2009 target_value.append(&mut hex::decode("0002ffff").unwrap());
2011 target_value.append(&mut hex::decode("0000").unwrap());
2013 if initial_routing_sync {
2014 target_value.append(&mut hex::decode("000108").unwrap());
2016 target_value.append(&mut hex::decode("0000").unwrap());
2018 assert_eq!(encoded_value, target_value);
2022 fn encoding_init() {
2023 do_encoding_init(false, false);
2024 do_encoding_init(true, false);
2025 do_encoding_init(false, true);
2026 do_encoding_init(true, true);
2030 fn encoding_error() {
2031 let error = msgs::ErrorMessage {
2032 channel_id: [2; 32],
2033 data: String::from("rust-lightning"),
2035 let encoded_value = error.encode();
2036 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
2037 assert_eq!(encoded_value, target_value);
2041 fn encoding_ping() {
2042 let ping = msgs::Ping {
2046 let encoded_value = ping.encode();
2047 let target_value = hex::decode("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2048 assert_eq!(encoded_value, target_value);
2052 fn encoding_pong() {
2053 let pong = msgs::Pong {
2056 let encoded_value = pong.encode();
2057 let target_value = hex::decode("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
2058 assert_eq!(encoded_value, target_value);