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::util::hash::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 pub(crate) fn new() -> LocalFeatures {
68 pub(crate) fn supports_data_loss_protect(&self) -> bool {
69 self.flags.len() > 0 && (self.flags[0] & 3) != 0
71 pub(crate) fn requires_data_loss_protect(&self) -> bool {
72 self.flags.len() > 0 && (self.flags[0] & 1) != 0
75 pub(crate) fn initial_routing_sync(&self) -> bool {
76 self.flags.len() > 0 && (self.flags[0] & (1 << 3)) != 0
78 pub(crate) fn set_initial_routing_sync(&mut self) {
79 if self.flags.len() == 0 {
80 self.flags.resize(1, 1 << 3);
82 self.flags[0] |= 1 << 3;
86 pub(crate) fn supports_upfront_shutdown_script(&self) -> bool {
87 self.flags.len() > 0 && (self.flags[0] & (3 << 4)) != 0
89 pub(crate) fn requires_upfront_shutdown_script(&self) -> bool {
90 self.flags.len() > 0 && (self.flags[0] & (1 << 4)) != 0
93 pub(crate) fn requires_unknown_bits(&self) -> bool {
94 for (idx, &byte) in self.flags.iter().enumerate() {
95 if idx != 0 && (byte & 0x55) != 0 {
97 } else if idx == 0 && (byte & 0x14) != 0 {
104 pub(crate) fn supports_unknown_bits(&self) -> bool {
105 for (idx, &byte) in self.flags.iter().enumerate() {
106 if idx != 0 && byte != 0 {
108 } else if idx == 0 && (byte & 0xc4) != 0 {
116 /// Tracks globalfeatures which are in init messages and routing announcements
117 #[derive(Clone, PartialEq, Debug)]
118 pub struct GlobalFeatures {
121 // Used to test encoding of diverse msgs
126 impl GlobalFeatures {
127 pub(crate) fn new() -> GlobalFeatures {
133 pub(crate) fn requires_unknown_bits(&self) -> bool {
134 for &byte in self.flags.iter() {
135 if (byte & 0x55) != 0 {
142 pub(crate) fn supports_unknown_bits(&self) -> bool {
143 for &byte in self.flags.iter() {
152 /// An init message to be sent or received from a peer
154 pub(crate) global_features: GlobalFeatures,
155 pub(crate) local_features: LocalFeatures,
158 /// An error message to be sent or received from a peer
160 pub struct ErrorMessage {
161 pub(crate) channel_id: [u8; 32],
162 pub(crate) data: String,
165 /// A ping message to be sent or received from a peer
167 pub(crate) ponglen: u16,
168 pub(crate) byteslen: u16,
171 /// A pong message to be sent or received from a peer
173 pub(crate) byteslen: u16,
176 /// An open_channel message to be sent or received from a peer
178 pub struct OpenChannel {
179 pub(crate) chain_hash: Sha256dHash,
180 pub(crate) temporary_channel_id: [u8; 32],
181 pub(crate) funding_satoshis: u64,
182 pub(crate) push_msat: u64,
183 pub(crate) dust_limit_satoshis: u64,
184 pub(crate) max_htlc_value_in_flight_msat: u64,
185 pub(crate) channel_reserve_satoshis: u64,
186 pub(crate) htlc_minimum_msat: u64,
187 pub(crate) feerate_per_kw: u32,
188 pub(crate) to_self_delay: u16,
189 pub(crate) max_accepted_htlcs: u16,
190 pub(crate) funding_pubkey: PublicKey,
191 pub(crate) revocation_basepoint: PublicKey,
192 pub(crate) payment_basepoint: PublicKey,
193 pub(crate) delayed_payment_basepoint: PublicKey,
194 pub(crate) htlc_basepoint: PublicKey,
195 pub(crate) first_per_commitment_point: PublicKey,
196 pub(crate) channel_flags: u8,
197 pub(crate) shutdown_scriptpubkey: OptionalField<Script>,
200 /// An accept_channel message to be sent or received from a peer
202 pub struct AcceptChannel {
203 pub(crate) temporary_channel_id: [u8; 32],
204 pub(crate) dust_limit_satoshis: u64,
205 pub(crate) max_htlc_value_in_flight_msat: u64,
206 pub(crate) channel_reserve_satoshis: u64,
207 pub(crate) htlc_minimum_msat: u64,
208 pub(crate) minimum_depth: u32,
209 pub(crate) to_self_delay: u16,
210 pub(crate) max_accepted_htlcs: u16,
211 pub(crate) funding_pubkey: PublicKey,
212 pub(crate) revocation_basepoint: PublicKey,
213 pub(crate) payment_basepoint: PublicKey,
214 pub(crate) delayed_payment_basepoint: PublicKey,
215 pub(crate) htlc_basepoint: PublicKey,
216 pub(crate) first_per_commitment_point: PublicKey,
217 pub(crate) shutdown_scriptpubkey: OptionalField<Script>
220 /// A funding_created message to be sent or received from a peer
222 pub struct FundingCreated {
223 pub(crate) temporary_channel_id: [u8; 32],
224 pub(crate) funding_txid: Sha256dHash,
225 pub(crate) funding_output_index: u16,
226 pub(crate) signature: Signature,
229 /// A funding_signed message to be sent or received from a peer
231 pub struct FundingSigned {
232 pub(crate) channel_id: [u8; 32],
233 pub(crate) signature: Signature,
236 /// A funding_locked message to be sent or received from a peer
237 #[derive(Clone, PartialEq)]
238 pub struct FundingLocked {
239 pub(crate) channel_id: [u8; 32],
240 pub(crate) next_per_commitment_point: PublicKey,
243 /// A shutdown message to be sent or received from a peer
244 #[derive(Clone, PartialEq)]
245 pub struct Shutdown {
246 pub(crate) channel_id: [u8; 32],
247 pub(crate) scriptpubkey: Script,
250 /// A closing_signed message to be sent or received from a peer
251 #[derive(Clone, PartialEq)]
252 pub struct ClosingSigned {
253 pub(crate) channel_id: [u8; 32],
254 pub(crate) fee_satoshis: u64,
255 pub(crate) signature: Signature,
258 /// An update_add_htlc message to be sent or received from a peer
259 #[derive(Clone, PartialEq)]
260 pub struct UpdateAddHTLC {
261 pub(crate) channel_id: [u8; 32],
262 pub(crate) htlc_id: u64,
263 pub(crate) amount_msat: u64,
264 pub(crate) payment_hash: PaymentHash,
265 pub(crate) cltv_expiry: u32,
266 pub(crate) onion_routing_packet: OnionPacket,
269 /// An update_fulfill_htlc message to be sent or received from a peer
270 #[derive(Clone, PartialEq)]
271 pub struct UpdateFulfillHTLC {
272 pub(crate) channel_id: [u8; 32],
273 pub(crate) htlc_id: u64,
274 pub(crate) payment_preimage: PaymentPreimage,
277 /// An update_fail_htlc message to be sent or received from a peer
278 #[derive(Clone, PartialEq)]
279 pub struct UpdateFailHTLC {
280 pub(crate) channel_id: [u8; 32],
281 pub(crate) htlc_id: u64,
282 pub(crate) reason: OnionErrorPacket,
285 /// An update_fail_malformed_htlc message to be sent or received from a peer
286 #[derive(Clone, PartialEq)]
287 pub struct UpdateFailMalformedHTLC {
288 pub(crate) channel_id: [u8; 32],
289 pub(crate) htlc_id: u64,
290 pub(crate) sha256_of_onion: [u8; 32],
291 pub(crate) failure_code: u16,
294 /// A commitment_signed message to be sent or received from a peer
295 #[derive(Clone, PartialEq)]
296 pub struct CommitmentSigned {
297 pub(crate) channel_id: [u8; 32],
298 pub(crate) signature: Signature,
299 pub(crate) htlc_signatures: Vec<Signature>,
302 /// A revoke_and_ack message to be sent or received from a peer
303 #[derive(Clone, PartialEq)]
304 pub struct RevokeAndACK {
305 pub(crate) channel_id: [u8; 32],
306 pub(crate) per_commitment_secret: [u8; 32],
307 pub(crate) next_per_commitment_point: PublicKey,
310 /// An update_fee message to be sent or received from a peer
311 #[derive(PartialEq, Clone)]
312 pub struct UpdateFee {
313 pub(crate) channel_id: [u8; 32],
314 pub(crate) feerate_per_kw: u32,
317 #[derive(PartialEq, Clone)]
318 pub(crate) struct DataLossProtect {
319 pub(crate) your_last_per_commitment_secret: [u8; 32],
320 pub(crate) my_current_per_commitment_point: PublicKey,
323 /// A channel_reestablish message to be sent or received from a peer
324 #[derive(PartialEq, Clone)]
325 pub struct ChannelReestablish {
326 pub(crate) channel_id: [u8; 32],
327 pub(crate) next_local_commitment_number: u64,
328 pub(crate) next_remote_commitment_number: u64,
329 pub(crate) data_loss_protect: OptionalField<DataLossProtect>,
332 /// An announcement_signatures message to be sent or received from a peer
333 #[derive(PartialEq, Clone, Debug)]
334 pub struct AnnouncementSignatures {
335 pub(crate) channel_id: [u8; 32],
336 pub(crate) short_channel_id: u64,
337 pub(crate) node_signature: Signature,
338 pub(crate) bitcoin_signature: Signature,
341 /// An address which can be used to connect to a remote peer
342 #[derive(Clone, PartialEq, Debug)]
343 pub enum NetAddress {
344 /// An IPv4 address/port on which the peer is listening.
346 /// The 4-byte IPv4 address
348 /// The port on which the node is listening
351 /// An IPv6 address/port on which the peer is listening.
353 /// The 16-byte IPv6 address
355 /// The port on which the node is listening
358 /// An old-style Tor onion address/port on which the peer is listening.
360 /// The bytes (usually encoded in base32 with ".onion" appended)
362 /// The port on which the node is listening
365 /// A new-style Tor onion address/port on which the peer is listening.
366 /// To create the human-readable "hostname", concatenate ed25519_pubkey, checksum, and version,
367 /// wrap as base32 and append ".onion".
369 /// The ed25519 long-term public key of the peer
370 ed25519_pubkey: [u8; 32],
371 /// The checksum of the pubkey and version, as included in the onion address
373 /// The version byte, as defined by the Tor Onion v3 spec.
375 /// The port on which the node is listening
380 fn get_id(&self) -> u8 {
382 &NetAddress::IPv4 {..} => { 1 },
383 &NetAddress::IPv6 {..} => { 2 },
384 &NetAddress::OnionV2 {..} => { 3 },
385 &NetAddress::OnionV3 {..} => { 4 },
389 /// Strict byte-length of address descriptor, 1-byte type not recorded
390 fn len(&self) -> u16 {
392 &NetAddress::IPv4 { .. } => { 6 },
393 &NetAddress::IPv6 { .. } => { 18 },
394 &NetAddress::OnionV2 { .. } => { 12 },
395 &NetAddress::OnionV3 { .. } => { 37 },
400 impl Writeable for NetAddress {
401 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
403 &NetAddress::IPv4 { ref addr, ref port } => {
408 &NetAddress::IPv6 { ref addr, ref port } => {
413 &NetAddress::OnionV2 { ref addr, ref port } => {
418 &NetAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
420 ed25519_pubkey.write(writer)?;
421 checksum.write(writer)?;
422 version.write(writer)?;
430 impl<R: ::std::io::Read> Readable<R> for Result<NetAddress, u8> {
431 fn read(reader: &mut R) -> Result<Result<NetAddress, u8>, DecodeError> {
432 let byte = <u8 as Readable<R>>::read(reader)?;
435 Ok(Ok(NetAddress::IPv4 {
436 addr: Readable::read(reader)?,
437 port: Readable::read(reader)?,
441 Ok(Ok(NetAddress::IPv6 {
442 addr: Readable::read(reader)?,
443 port: Readable::read(reader)?,
447 Ok(Ok(NetAddress::OnionV2 {
448 addr: Readable::read(reader)?,
449 port: Readable::read(reader)?,
453 Ok(Ok(NetAddress::OnionV3 {
454 ed25519_pubkey: Readable::read(reader)?,
455 checksum: Readable::read(reader)?,
456 version: Readable::read(reader)?,
457 port: Readable::read(reader)?,
460 _ => return Ok(Err(byte)),
465 // Only exposed as broadcast of node_announcement should be filtered by node_id
466 /// The unsigned part of a node_announcement
467 #[derive(PartialEq, Clone, Debug)]
468 pub struct UnsignedNodeAnnouncement {
469 pub(crate) features: GlobalFeatures,
470 pub(crate) timestamp: u32,
471 /// The node_id this announcement originated from (don't rebroadcast the node_announcement back
473 pub node_id: PublicKey,
474 pub(crate) rgb: [u8; 3],
475 pub(crate) alias: [u8; 32],
476 /// List of addresses on which this node is reachable. Note that you may only have up to one
477 /// address of each type, if you have more, they may be silently discarded or we may panic!
478 pub(crate) addresses: Vec<NetAddress>,
479 pub(crate) excess_address_data: Vec<u8>,
480 pub(crate) excess_data: Vec<u8>,
482 #[derive(PartialEq, Clone)]
483 /// A node_announcement message to be sent or received from a peer
484 pub struct NodeAnnouncement {
485 pub(crate) signature: Signature,
486 pub(crate) contents: UnsignedNodeAnnouncement,
489 // Only exposed as broadcast of channel_announcement should be filtered by node_id
490 /// The unsigned part of a channel_announcement
491 #[derive(PartialEq, Clone, Debug)]
492 pub struct UnsignedChannelAnnouncement {
493 pub(crate) features: GlobalFeatures,
494 pub(crate) chain_hash: Sha256dHash,
495 pub(crate) short_channel_id: u64,
496 /// One of the two node_ids which are endpoints of this channel
497 pub node_id_1: PublicKey,
498 /// The other of the two node_ids which are endpoints of this channel
499 pub node_id_2: PublicKey,
500 pub(crate) bitcoin_key_1: PublicKey,
501 pub(crate) bitcoin_key_2: PublicKey,
502 pub(crate) excess_data: Vec<u8>,
504 /// A channel_announcement message to be sent or received from a peer
505 #[derive(PartialEq, Clone, Debug)]
506 pub struct ChannelAnnouncement {
507 pub(crate) node_signature_1: Signature,
508 pub(crate) node_signature_2: Signature,
509 pub(crate) bitcoin_signature_1: Signature,
510 pub(crate) bitcoin_signature_2: Signature,
511 pub(crate) contents: UnsignedChannelAnnouncement,
514 #[derive(PartialEq, Clone, Debug)]
515 pub(crate) struct UnsignedChannelUpdate {
516 pub(crate) chain_hash: Sha256dHash,
517 pub(crate) short_channel_id: u64,
518 pub(crate) timestamp: u32,
519 pub(crate) flags: u16,
520 pub(crate) cltv_expiry_delta: u16,
521 pub(crate) htlc_minimum_msat: u64,
522 pub(crate) fee_base_msat: u32,
523 pub(crate) fee_proportional_millionths: u32,
524 pub(crate) excess_data: Vec<u8>,
526 /// A channel_update message to be sent or received from a peer
527 #[derive(PartialEq, Clone, Debug)]
528 pub struct ChannelUpdate {
529 pub(crate) signature: Signature,
530 pub(crate) contents: UnsignedChannelUpdate,
533 /// Used to put an error message in a HandleError
535 pub enum ErrorAction {
536 /// The peer took some action which made us think they were useless. Disconnect them.
538 /// An error message which we should make an effort to send before we disconnect.
539 msg: Option<ErrorMessage>
541 /// The peer did something harmless that we weren't able to process, just log and ignore
543 /// The peer did something incorrect. Tell them.
545 /// The message to send.
550 /// An Err type for failure to process messages.
551 pub struct HandleError { //TODO: rename me
552 /// A human-readable message describing the error
553 pub err: &'static str,
554 /// The action which should be taken against the offending peer.
555 pub action: Option<ErrorAction>, //TODO: Make this required
558 /// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment
559 /// transaction updates if they were pending.
560 #[derive(PartialEq, Clone)]
561 pub struct CommitmentUpdate {
562 /// update_add_htlc messages which should be sent
563 pub update_add_htlcs: Vec<UpdateAddHTLC>,
564 /// update_fulfill_htlc messages which should be sent
565 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
566 /// update_fail_htlc messages which should be sent
567 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
568 /// update_fail_malformed_htlc messages which should be sent
569 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
570 /// An update_fee message which should be sent
571 pub update_fee: Option<UpdateFee>,
572 /// Finally, the commitment_signed message which should be sent
573 pub commitment_signed: CommitmentSigned,
576 /// The information we received from a peer along the route of a payment we originated. This is
577 /// returned by ChannelMessageHandler::handle_update_fail_htlc to be passed into
578 /// RoutingMessageHandler::handle_htlc_fail_channel_update to update our network map.
580 pub enum HTLCFailChannelUpdate {
581 /// We received an error which included a full ChannelUpdate message.
582 ChannelUpdateMessage {
583 /// The unwrapped message we received
586 /// We received an error which indicated only that a channel has been closed
588 /// The short_channel_id which has now closed.
589 short_channel_id: u64,
590 /// when this true, this channel should be permanently removed from the
591 /// consideration. Otherwise, this channel can be restored as new channel_update is received
594 /// We received an error which indicated only that a node has failed
596 /// The node_id that has failed.
598 /// when this true, node should be permanently removed from the
599 /// consideration. Otherwise, the channels connected to this node can be
600 /// restored as new channel_update is received
605 /// Messages could have optional fields to use with extended features
606 /// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
607 /// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
608 /// separate enum type for them.
609 #[derive(Clone, PartialEq)]
610 pub enum OptionalField<T> {
611 /// Optional field is included in message
613 /// Optional field is absent in message
617 /// A trait to describe an object which can receive channel messages.
619 /// Messages MAY be called in parallel when they originate from different their_node_ids, however
620 /// they MUST NOT be called in parallel when the two calls have the same their_node_id.
621 pub trait ChannelMessageHandler : events::MessageSendEventsProvider + Send + Sync {
623 /// Handle an incoming open_channel message from the given peer.
624 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &OpenChannel) -> Result<(), HandleError>;
625 /// Handle an incoming accept_channel message from the given peer.
626 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &AcceptChannel) -> Result<(), HandleError>;
627 /// Handle an incoming funding_created message from the given peer.
628 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &FundingCreated) -> Result<(), HandleError>;
629 /// Handle an incoming funding_signed message from the given peer.
630 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &FundingSigned) -> Result<(), HandleError>;
631 /// Handle an incoming funding_locked message from the given peer.
632 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &FundingLocked) -> Result<(), HandleError>;
635 /// Handle an incoming shutdown message from the given peer.
636 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &Shutdown) -> Result<(), HandleError>;
637 /// Handle an incoming closing_signed message from the given peer.
638 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &ClosingSigned) -> Result<(), HandleError>;
641 /// Handle an incoming update_add_htlc message from the given peer.
642 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &UpdateAddHTLC) -> Result<(), HandleError>;
643 /// Handle an incoming update_fulfill_htlc message from the given peer.
644 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFulfillHTLC) -> Result<(), HandleError>;
645 /// Handle an incoming update_fail_htlc message from the given peer.
646 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailHTLC) -> Result<(), HandleError>;
647 /// Handle an incoming update_fail_malformed_htlc message from the given peer.
648 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &UpdateFailMalformedHTLC) -> Result<(), HandleError>;
649 /// Handle an incoming commitment_signed message from the given peer.
650 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &CommitmentSigned) -> Result<(), HandleError>;
651 /// Handle an incoming revoke_and_ack message from the given peer.
652 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &RevokeAndACK) -> Result<(), HandleError>;
654 /// Handle an incoming update_fee message from the given peer.
655 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &UpdateFee) -> Result<(), HandleError>;
657 // Channel-to-announce:
658 /// Handle an incoming announcement_signatures message from the given peer.
659 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &AnnouncementSignatures) -> Result<(), HandleError>;
661 // Connection loss/reestablish:
662 /// Indicates a connection to the peer failed/an existing connection was lost. If no connection
663 /// is believed to be possible in the future (eg they're sending us messages we don't
664 /// understand or indicate they require unknown feature bits), no_connection_possible is set
665 /// and any outstanding channels should be failed.
666 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool);
668 /// Handle a peer reconnecting, possibly generating channel_reestablish message(s).
669 fn peer_connected(&self, their_node_id: &PublicKey);
670 /// Handle an incoming channel_reestablish message from the given peer.
671 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &ChannelReestablish) -> Result<(), HandleError>;
674 /// Handle an incoming error message from the given peer.
675 fn handle_error(&self, their_node_id: &PublicKey, msg: &ErrorMessage);
678 /// A trait to describe an object which can receive routing messages.
679 pub trait RoutingMessageHandler : Send + Sync {
680 /// Handle an incoming node_announcement message, returning true if it should be forwarded on,
681 /// false or returning an Err otherwise.
682 fn handle_node_announcement(&self, msg: &NodeAnnouncement) -> Result<bool, HandleError>;
683 /// Handle a channel_announcement message, returning true if it should be forwarded on, false
684 /// or returning an Err otherwise.
685 fn handle_channel_announcement(&self, msg: &ChannelAnnouncement) -> Result<bool, HandleError>;
686 /// Handle an incoming channel_update message, returning true if it should be forwarded on,
687 /// false or returning an Err otherwise.
688 fn handle_channel_update(&self, msg: &ChannelUpdate) -> Result<bool, HandleError>;
689 /// Handle some updates to the route graph that we learned due to an outbound failed payment.
690 fn handle_htlc_fail_channel_update(&self, update: &HTLCFailChannelUpdate);
691 /// Gets a subset of the channel announcements and updates required to dump our routing table
692 /// to a remote node, starting at the short_channel_id indicated by starting_point and
693 /// including batch_amount entries.
694 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, ChannelUpdate, ChannelUpdate)>;
695 /// Gets a subset of the node announcements required to dump our routing table to a remote node,
696 /// starting at the node *after* the provided publickey and including batch_amount entries.
697 /// If None is provided for starting_point, we start at the first node.
698 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement>;
701 pub(crate) struct OnionRealm0HopData {
702 pub(crate) short_channel_id: u64,
703 pub(crate) amt_to_forward: u64,
704 pub(crate) outgoing_cltv_value: u32,
705 // 12 bytes of 0-padding
708 mod fuzzy_internal_msgs {
709 // These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
710 // them from untrusted input):
712 use super::OnionRealm0HopData;
713 pub struct OnionHopData {
714 pub(crate) realm: u8,
715 pub(crate) data: OnionRealm0HopData,
716 pub(crate) hmac: [u8; 32],
718 unsafe impl ::util::internal_traits::NoDealloc for OnionHopData{}
720 pub struct DecodedOnionErrorPacket {
721 pub(crate) hmac: [u8; 32],
722 pub(crate) failuremsg: Vec<u8>,
723 pub(crate) pad: Vec<u8>,
726 #[cfg(feature = "fuzztarget")]
727 pub use self::fuzzy_internal_msgs::*;
728 #[cfg(not(feature = "fuzztarget"))]
729 pub(crate) use self::fuzzy_internal_msgs::*;
732 pub(crate) struct OnionPacket {
733 pub(crate) version: u8,
734 /// In order to ensure we always return an error on Onion decode in compliance with BOLT 4, we
735 /// have to deserialize OnionPackets contained in UpdateAddHTLCs even if the ephemeral public
736 /// key (here) is bogus, so we hold a Result instead of a PublicKey as we'd like.
737 pub(crate) public_key: Result<PublicKey, secp256k1::Error>,
738 pub(crate) hop_data: [u8; 20*65],
739 pub(crate) hmac: [u8; 32],
742 impl PartialEq for OnionPacket {
743 fn eq(&self, other: &OnionPacket) -> bool {
744 for (i, j) in self.hop_data.iter().zip(other.hop_data.iter()) {
745 if i != j { return false; }
747 self.version == other.version &&
748 self.public_key == other.public_key &&
749 self.hmac == other.hmac
753 #[derive(Clone, PartialEq)]
754 pub(crate) struct OnionErrorPacket {
755 // This really should be a constant size slice, but the spec lets these things be up to 128KB?
756 // (TODO) We limit it in decode to much lower...
757 pub(crate) data: Vec<u8>,
760 impl Error for DecodeError {
761 fn description(&self) -> &str {
763 DecodeError::UnknownVersion => "Unknown realm byte in Onion packet",
764 DecodeError::UnknownRequiredFeature => "Unknown required feature preventing decode",
765 DecodeError::InvalidValue => "Nonsense bytes didn't map to the type they were interpreted as",
766 DecodeError::ShortRead => "Packet extended beyond the provided bytes",
767 DecodeError::ExtraAddressesPerType => "More than one address of a single type",
768 DecodeError::BadLengthDescriptor => "A length descriptor in the packet didn't describe the later data correctly",
769 DecodeError::Io(ref e) => e.description(),
773 impl fmt::Display for DecodeError {
774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
775 f.write_str(self.description())
779 impl fmt::Debug for HandleError {
780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
781 f.write_str(self.err)
785 impl From<::std::io::Error> for DecodeError {
786 fn from(e: ::std::io::Error) -> Self {
787 if e.kind() == ::std::io::ErrorKind::UnexpectedEof {
788 DecodeError::ShortRead
795 impl Writeable for OptionalField<Script> {
796 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
798 OptionalField::Present(ref script) => {
799 // Note that Writeable for script includes the 16-bit length tag for us
802 OptionalField::Absent => {}
808 impl<R: Read> Readable<R> for OptionalField<Script> {
809 fn read(r: &mut R) -> Result<Self, DecodeError> {
810 match <u16 as Readable<R>>::read(r) {
812 let mut buf = vec![0; len as usize];
813 r.read_exact(&mut buf)?;
814 Ok(OptionalField::Present(Script::from(buf)))
816 Err(DecodeError::ShortRead) => Ok(OptionalField::Absent),
822 impl_writeable_len_match!(AcceptChannel, {
823 {AcceptChannel{ shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 270 + 2 + script.len()},
826 temporary_channel_id,
828 max_htlc_value_in_flight_msat,
829 channel_reserve_satoshis,
835 revocation_basepoint,
837 delayed_payment_basepoint,
839 first_per_commitment_point,
840 shutdown_scriptpubkey
843 impl_writeable!(AnnouncementSignatures, 32+8+64*2, {
850 impl Writeable for ChannelReestablish {
851 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
852 w.size_hint(if let OptionalField::Present(..) = self.data_loss_protect { 32+2*8+33+32 } else { 32+2*8 });
853 self.channel_id.write(w)?;
854 self.next_local_commitment_number.write(w)?;
855 self.next_remote_commitment_number.write(w)?;
856 match self.data_loss_protect {
857 OptionalField::Present(ref data_loss_protect) => {
858 (*data_loss_protect).your_last_per_commitment_secret.write(w)?;
859 (*data_loss_protect).my_current_per_commitment_point.write(w)?;
861 OptionalField::Absent => {}
867 impl<R: Read> Readable<R> for ChannelReestablish{
868 fn read(r: &mut R) -> Result<Self, DecodeError> {
870 channel_id: Readable::read(r)?,
871 next_local_commitment_number: Readable::read(r)?,
872 next_remote_commitment_number: Readable::read(r)?,
874 match <[u8; 32] as Readable<R>>::read(r) {
875 Ok(your_last_per_commitment_secret) =>
876 OptionalField::Present(DataLossProtect {
877 your_last_per_commitment_secret,
878 my_current_per_commitment_point: Readable::read(r)?,
880 Err(DecodeError::ShortRead) => OptionalField::Absent,
881 Err(e) => return Err(e)
888 impl_writeable!(ClosingSigned, 32+8+64, {
894 impl_writeable_len_match!(CommitmentSigned, {
895 { CommitmentSigned { ref htlc_signatures, .. }, 32+64+2+htlc_signatures.len()*64 }
902 impl_writeable_len_match!(DecodedOnionErrorPacket, {
903 { DecodedOnionErrorPacket { ref failuremsg, ref pad, .. }, 32 + 4 + failuremsg.len() + pad.len() }
910 impl_writeable!(FundingCreated, 32+32+2+64, {
911 temporary_channel_id,
913 funding_output_index,
917 impl_writeable!(FundingSigned, 32+64, {
922 impl_writeable!(FundingLocked, 32+33, {
924 next_per_commitment_point
927 impl_writeable_len_match!(GlobalFeatures, {
928 { GlobalFeatures { ref flags }, flags.len() + 2 }
933 impl_writeable_len_match!(LocalFeatures, {
934 { LocalFeatures { ref flags }, flags.len() + 2 }
939 impl_writeable_len_match!(Init, {
940 { Init { ref global_features, ref local_features }, global_features.flags.len() + local_features.flags.len() + 4 }
946 impl_writeable_len_match!(OpenChannel, {
947 { OpenChannel { shutdown_scriptpubkey: OptionalField::Present(ref script), .. }, 319 + 2 + script.len() },
951 temporary_channel_id,
955 max_htlc_value_in_flight_msat,
956 channel_reserve_satoshis,
962 revocation_basepoint,
964 delayed_payment_basepoint,
966 first_per_commitment_point,
968 shutdown_scriptpubkey
971 impl_writeable!(RevokeAndACK, 32+32+33, {
973 per_commitment_secret,
974 next_per_commitment_point
977 impl_writeable_len_match!(Shutdown, {
978 { Shutdown { ref scriptpubkey, .. }, 32 + 2 + scriptpubkey.len() }
984 impl_writeable_len_match!(UpdateFailHTLC, {
985 { UpdateFailHTLC { ref reason, .. }, 32 + 10 + reason.data.len() }
992 impl_writeable!(UpdateFailMalformedHTLC, 32+8+32+2, {
999 impl_writeable!(UpdateFee, 32+4, {
1004 impl_writeable!(UpdateFulfillHTLC, 32+8+32, {
1010 impl_writeable_len_match!(OnionErrorPacket, {
1011 { OnionErrorPacket { ref data, .. }, 2 + data.len() }
1016 impl Writeable for OnionPacket {
1017 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1018 w.size_hint(1 + 33 + 20*65 + 32);
1019 self.version.write(w)?;
1020 match self.public_key {
1021 Ok(pubkey) => pubkey.write(w)?,
1022 Err(_) => [0u8;33].write(w)?,
1024 w.write_all(&self.hop_data)?;
1025 self.hmac.write(w)?;
1030 impl<R: Read> Readable<R> for OnionPacket {
1031 fn read(r: &mut R) -> Result<Self, DecodeError> {
1033 version: Readable::read(r)?,
1035 let mut buf = [0u8;33];
1036 r.read_exact(&mut buf)?;
1037 PublicKey::from_slice(&buf)
1039 hop_data: Readable::read(r)?,
1040 hmac: Readable::read(r)?,
1045 impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
1051 onion_routing_packet
1054 impl Writeable for OnionRealm0HopData {
1055 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1057 self.short_channel_id.write(w)?;
1058 self.amt_to_forward.write(w)?;
1059 self.outgoing_cltv_value.write(w)?;
1060 w.write_all(&[0;12])?;
1065 impl<R: Read> Readable<R> for OnionRealm0HopData {
1066 fn read(r: &mut R) -> Result<Self, DecodeError> {
1067 Ok(OnionRealm0HopData {
1068 short_channel_id: Readable::read(r)?,
1069 amt_to_forward: Readable::read(r)?,
1070 outgoing_cltv_value: {
1071 let v: u32 = Readable::read(r)?;
1072 r.read_exact(&mut [0; 12])?;
1079 impl Writeable for OnionHopData {
1080 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1082 self.realm.write(w)?;
1083 self.data.write(w)?;
1084 self.hmac.write(w)?;
1089 impl<R: Read> Readable<R> for OnionHopData {
1090 fn read(r: &mut R) -> Result<Self, DecodeError> {
1093 let r: u8 = Readable::read(r)?;
1095 return Err(DecodeError::UnknownVersion);
1099 data: Readable::read(r)?,
1100 hmac: Readable::read(r)?,
1105 impl Writeable for Ping {
1106 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1107 w.size_hint(self.byteslen as usize + 4);
1108 self.ponglen.write(w)?;
1109 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1114 impl<R: Read> Readable<R> for Ping {
1115 fn read(r: &mut R) -> Result<Self, DecodeError> {
1117 ponglen: Readable::read(r)?,
1119 let byteslen = Readable::read(r)?;
1120 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1127 impl Writeable for Pong {
1128 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1129 w.size_hint(self.byteslen as usize + 2);
1130 vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
1135 impl<R: Read> Readable<R> for Pong {
1136 fn read(r: &mut R) -> Result<Self, DecodeError> {
1139 let byteslen = Readable::read(r)?;
1140 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
1147 impl Writeable for UnsignedChannelAnnouncement {
1148 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1149 w.size_hint(2 + 2*32 + 4*33 + self.features.flags.len() + self.excess_data.len());
1150 self.features.write(w)?;
1151 self.chain_hash.write(w)?;
1152 self.short_channel_id.write(w)?;
1153 self.node_id_1.write(w)?;
1154 self.node_id_2.write(w)?;
1155 self.bitcoin_key_1.write(w)?;
1156 self.bitcoin_key_2.write(w)?;
1157 w.write_all(&self.excess_data[..])?;
1162 impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
1163 fn read(r: &mut R) -> Result<Self, DecodeError> {
1166 let f: GlobalFeatures = Readable::read(r)?;
1167 if f.requires_unknown_bits() {
1168 return Err(DecodeError::UnknownRequiredFeature);
1172 chain_hash: Readable::read(r)?,
1173 short_channel_id: Readable::read(r)?,
1174 node_id_1: Readable::read(r)?,
1175 node_id_2: Readable::read(r)?,
1176 bitcoin_key_1: Readable::read(r)?,
1177 bitcoin_key_2: Readable::read(r)?,
1179 let mut excess_data = vec![];
1180 r.read_to_end(&mut excess_data)?;
1187 impl_writeable_len_match!(ChannelAnnouncement, {
1188 { ChannelAnnouncement { contents: UnsignedChannelAnnouncement {ref features, ref excess_data, ..}, .. },
1189 2 + 2*32 + 4*33 + features.flags.len() + excess_data.len() + 4*64 }
1193 bitcoin_signature_1,
1194 bitcoin_signature_2,
1198 impl Writeable for UnsignedChannelUpdate {
1199 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1200 w.size_hint(64 + self.excess_data.len());
1201 self.chain_hash.write(w)?;
1202 self.short_channel_id.write(w)?;
1203 self.timestamp.write(w)?;
1204 self.flags.write(w)?;
1205 self.cltv_expiry_delta.write(w)?;
1206 self.htlc_minimum_msat.write(w)?;
1207 self.fee_base_msat.write(w)?;
1208 self.fee_proportional_millionths.write(w)?;
1209 w.write_all(&self.excess_data[..])?;
1214 impl<R: Read> Readable<R> for UnsignedChannelUpdate {
1215 fn read(r: &mut R) -> Result<Self, DecodeError> {
1217 chain_hash: Readable::read(r)?,
1218 short_channel_id: Readable::read(r)?,
1219 timestamp: Readable::read(r)?,
1220 flags: Readable::read(r)?,
1221 cltv_expiry_delta: Readable::read(r)?,
1222 htlc_minimum_msat: Readable::read(r)?,
1223 fee_base_msat: Readable::read(r)?,
1224 fee_proportional_millionths: Readable::read(r)?,
1226 let mut excess_data = vec![];
1227 r.read_to_end(&mut excess_data)?;
1234 impl_writeable_len_match!(ChannelUpdate, {
1235 { ChannelUpdate { contents: UnsignedChannelUpdate {ref excess_data, ..}, .. },
1236 64 + excess_data.len() + 64 }
1242 impl Writeable for ErrorMessage {
1243 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1244 w.size_hint(32 + 2 + self.data.len());
1245 self.channel_id.write(w)?;
1246 (self.data.len() as u16).write(w)?;
1247 w.write_all(self.data.as_bytes())?;
1252 impl<R: Read> Readable<R> for ErrorMessage {
1253 fn read(r: &mut R) -> Result<Self, DecodeError> {
1255 channel_id: Readable::read(r)?,
1257 let mut sz: usize = <u16 as Readable<R>>::read(r)? as usize;
1258 let mut data = vec![];
1259 let data_len = r.read_to_end(&mut data)?;
1260 sz = cmp::min(data_len, sz);
1261 match String::from_utf8(data[..sz as usize].to_vec()) {
1263 Err(_) => return Err(DecodeError::InvalidValue),
1270 impl Writeable for UnsignedNodeAnnouncement {
1271 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
1272 w.size_hint(64 + 76 + self.features.flags.len() + self.addresses.len()*38 + self.excess_address_data.len() + self.excess_data.len());
1273 self.features.write(w)?;
1274 self.timestamp.write(w)?;
1275 self.node_id.write(w)?;
1276 w.write_all(&self.rgb)?;
1277 self.alias.write(w)?;
1279 let mut addrs_to_encode = self.addresses.clone();
1280 addrs_to_encode.sort_unstable_by(|a, b| { a.get_id().cmp(&b.get_id()) });
1281 addrs_to_encode.dedup_by(|a, b| { a.get_id() == b.get_id() });
1282 let mut addr_len = 0;
1283 for addr in &addrs_to_encode {
1284 addr_len += 1 + addr.len();
1286 (addr_len + self.excess_address_data.len() as u16).write(w)?;
1287 for addr in addrs_to_encode {
1290 w.write_all(&self.excess_address_data[..])?;
1291 w.write_all(&self.excess_data[..])?;
1296 impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
1297 fn read(r: &mut R) -> Result<Self, DecodeError> {
1298 let features: GlobalFeatures = Readable::read(r)?;
1299 if features.requires_unknown_bits() {
1300 return Err(DecodeError::UnknownRequiredFeature);
1302 let timestamp: u32 = Readable::read(r)?;
1303 let node_id: PublicKey = Readable::read(r)?;
1304 let mut rgb = [0; 3];
1305 r.read_exact(&mut rgb)?;
1306 let alias: [u8; 32] = Readable::read(r)?;
1308 let addr_len: u16 = Readable::read(r)?;
1309 let mut addresses: Vec<NetAddress> = Vec::with_capacity(4);
1310 let mut addr_readpos = 0;
1311 let mut excess = false;
1312 let mut excess_byte = 0;
1314 if addr_len <= addr_readpos { break; }
1315 match Readable::read(r) {
1318 NetAddress::IPv4 { .. } => {
1319 if addresses.len() > 0 {
1320 return Err(DecodeError::ExtraAddressesPerType);
1323 NetAddress::IPv6 { .. } => {
1324 if addresses.len() > 1 || (addresses.len() == 1 && addresses[0].get_id() != 1) {
1325 return Err(DecodeError::ExtraAddressesPerType);
1328 NetAddress::OnionV2 { .. } => {
1329 if addresses.len() > 2 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 2) {
1330 return Err(DecodeError::ExtraAddressesPerType);
1333 NetAddress::OnionV3 { .. } => {
1334 if addresses.len() > 3 || (addresses.len() > 0 && addresses.last().unwrap().get_id() > 3) {
1335 return Err(DecodeError::ExtraAddressesPerType);
1339 if addr_len < addr_readpos + 1 + addr.len() {
1340 return Err(DecodeError::BadLengthDescriptor);
1342 addr_readpos += (1 + addr.len()) as u16;
1343 addresses.push(addr);
1345 Ok(Err(unknown_descriptor)) => {
1347 excess_byte = unknown_descriptor;
1350 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
1351 Err(e) => return Err(e),
1355 let mut excess_data = vec![];
1356 let excess_address_data = if addr_readpos < addr_len {
1357 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
1358 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
1360 excess_address_data[0] = excess_byte;
1365 excess_data.push(excess_byte);
1369 r.read_to_end(&mut excess_data)?;
1370 Ok(UnsignedNodeAnnouncement {
1377 excess_address_data,
1383 impl_writeable_len_match!(NodeAnnouncement, {
1384 { NodeAnnouncement { contents: UnsignedNodeAnnouncement { ref features, ref addresses, ref excess_address_data, ref excess_data, ..}, .. },
1385 64 + 76 + features.flags.len() + addresses.len()*38 + excess_address_data.len() + excess_data.len() }
1395 use ln::msgs::{GlobalFeatures, OptionalField, OnionErrorPacket};
1396 use ln::channelmanager::{PaymentPreimage, PaymentHash};
1397 use util::ser::Writeable;
1399 use bitcoin::util::hash::Sha256dHash;
1400 use bitcoin::util::address::Address;
1401 use bitcoin::network::constants::Network;
1402 use bitcoin::blockdata::script::Builder;
1403 use bitcoin::blockdata::opcodes;
1405 use secp256k1::key::{PublicKey,SecretKey};
1406 use secp256k1::{Secp256k1, Message};
1409 fn encoding_channel_reestablish_no_secret() {
1410 let cr = msgs::ChannelReestablish {
1411 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],
1412 next_local_commitment_number: 3,
1413 next_remote_commitment_number: 4,
1414 data_loss_protect: OptionalField::Absent,
1417 let encoded_value = cr.encode();
1420 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]
1425 fn encoding_channel_reestablish_with_secret() {
1427 let secp_ctx = Secp256k1::new();
1428 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
1431 let cr = msgs::ChannelReestablish {
1432 channel_id: [4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0],
1433 next_local_commitment_number: 3,
1434 next_remote_commitment_number: 4,
1435 data_loss_protect: OptionalField::Present(msgs::DataLossProtect { your_last_per_commitment_secret: [9;32], my_current_per_commitment_point: public_key}),
1438 let encoded_value = cr.encode();
1441 vec![4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 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]
1445 macro_rules! get_keys_from {
1446 ($slice: expr, $secp_ctx: expr) => {
1448 let privkey = SecretKey::from_slice(&hex::decode($slice).unwrap()[..]).unwrap();
1449 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
1455 macro_rules! get_sig_on {
1456 ($privkey: expr, $ctx: expr, $string: expr) => {
1458 let sighash = Message::from_slice(&$string.into_bytes()[..]).unwrap();
1459 $ctx.sign(&sighash, &$privkey)
1465 fn encoding_announcement_signatures() {
1466 let secp_ctx = Secp256k1::new();
1467 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1468 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
1469 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
1470 let announcement_signatures = msgs::AnnouncementSignatures {
1471 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],
1472 short_channel_id: 2316138423780173,
1473 node_signature: sig_1,
1474 bitcoin_signature: sig_2,
1477 let encoded_value = announcement_signatures.encode();
1478 assert_eq!(encoded_value, hex::decode("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
1481 fn do_encoding_channel_announcement(unknown_features_bits: bool, non_bitcoin_chain_hash: bool, excess_data: bool) {
1482 let secp_ctx = Secp256k1::new();
1483 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1484 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1485 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1486 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1487 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1488 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1489 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1490 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1491 let mut features = GlobalFeatures::new();
1492 if unknown_features_bits {
1493 features.flags = vec![0xFF, 0xFF];
1495 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
1497 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1498 short_channel_id: 2316138423780173,
1499 node_id_1: pubkey_1,
1500 node_id_2: pubkey_2,
1501 bitcoin_key_1: pubkey_3,
1502 bitcoin_key_2: pubkey_4,
1503 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
1505 let channel_announcement = msgs::ChannelAnnouncement {
1506 node_signature_1: sig_1,
1507 node_signature_2: sig_2,
1508 bitcoin_signature_1: sig_3,
1509 bitcoin_signature_2: sig_4,
1510 contents: unsigned_channel_announcement,
1512 let encoded_value = channel_announcement.encode();
1513 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
1514 if unknown_features_bits {
1515 target_value.append(&mut hex::decode("0002ffff").unwrap());
1517 target_value.append(&mut hex::decode("0000").unwrap());
1519 if non_bitcoin_chain_hash {
1520 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1522 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1524 target_value.append(&mut hex::decode("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
1526 target_value.append(&mut hex::decode("0a00001400001e000028").unwrap());
1528 assert_eq!(encoded_value, target_value);
1532 fn encoding_channel_announcement() {
1533 do_encoding_channel_announcement(false, false, false);
1534 do_encoding_channel_announcement(true, false, false);
1535 do_encoding_channel_announcement(true, true, false);
1536 do_encoding_channel_announcement(true, true, true);
1537 do_encoding_channel_announcement(false, true, true);
1538 do_encoding_channel_announcement(false, false, true);
1539 do_encoding_channel_announcement(false, true, false);
1540 do_encoding_channel_announcement(true, false, true);
1543 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, excess_address_data: bool, excess_data: bool) {
1544 let secp_ctx = Secp256k1::new();
1545 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1546 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1547 let mut features = GlobalFeatures::new();
1548 if unknown_features_bits {
1549 features.flags = vec![0xFF, 0xFF];
1551 let mut addresses = Vec::new();
1553 addresses.push(msgs::NetAddress::IPv4 {
1554 addr: [255, 254, 253, 252],
1559 addresses.push(msgs::NetAddress::IPv6 {
1560 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
1565 addresses.push(msgs::NetAddress::OnionV2 {
1566 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246],
1571 addresses.push(msgs::NetAddress::OnionV3 {
1572 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],
1578 let mut addr_len = 0;
1579 for addr in &addresses {
1580 addr_len += addr.len() + 1;
1582 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
1584 timestamp: 20190119,
1589 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() },
1590 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() },
1592 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
1593 let node_announcement = msgs::NodeAnnouncement {
1595 contents: unsigned_node_announcement,
1597 let encoded_value = node_announcement.encode();
1598 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1599 if unknown_features_bits {
1600 target_value.append(&mut hex::decode("0002ffff").unwrap());
1602 target_value.append(&mut hex::decode("0000").unwrap());
1604 target_value.append(&mut hex::decode("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
1605 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
1607 target_value.append(&mut hex::decode("01fffefdfc2607").unwrap());
1610 target_value.append(&mut hex::decode("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
1613 target_value.append(&mut hex::decode("03fffefdfcfbfaf9f8f7f62607").unwrap());
1616 target_value.append(&mut hex::decode("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
1618 if excess_address_data {
1619 target_value.append(&mut hex::decode("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
1622 target_value.append(&mut hex::decode("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1624 assert_eq!(encoded_value, target_value);
1628 fn encoding_node_announcement() {
1629 do_encoding_node_announcement(true, true, true, true, true, true, true);
1630 do_encoding_node_announcement(false, false, false, false, false, false, false);
1631 do_encoding_node_announcement(false, true, false, false, false, false, false);
1632 do_encoding_node_announcement(false, false, true, false, false, false, false);
1633 do_encoding_node_announcement(false, false, false, true, false, false, false);
1634 do_encoding_node_announcement(false, false, false, false, true, false, false);
1635 do_encoding_node_announcement(false, false, false, false, false, true, false);
1636 do_encoding_node_announcement(false, true, false, true, false, true, false);
1637 do_encoding_node_announcement(false, false, true, false, true, false, false);
1640 fn do_encoding_channel_update(non_bitcoin_chain_hash: bool, direction: bool, disable: bool, htlc_maximum_msat: bool) {
1641 let secp_ctx = Secp256k1::new();
1642 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1643 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1644 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
1645 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1646 short_channel_id: 2316138423780173,
1647 timestamp: 20190119,
1648 flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 } | if htlc_maximum_msat { 1 << 8 } else { 0 },
1649 cltv_expiry_delta: 144,
1650 htlc_minimum_msat: 1000000,
1651 fee_base_msat: 10000,
1652 fee_proportional_millionths: 20,
1653 excess_data: if htlc_maximum_msat { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
1655 let channel_update = msgs::ChannelUpdate {
1657 contents: unsigned_channel_update
1659 let encoded_value = channel_update.encode();
1660 let mut target_value = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1661 if non_bitcoin_chain_hash {
1662 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1664 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1666 target_value.append(&mut hex::decode("00083a840000034d013413a7").unwrap());
1667 if htlc_maximum_msat {
1668 target_value.append(&mut hex::decode("01").unwrap());
1670 target_value.append(&mut hex::decode("00").unwrap());
1672 target_value.append(&mut hex::decode("00").unwrap());
1674 let flag = target_value.last_mut().unwrap();
1678 let flag = target_value.last_mut().unwrap();
1679 *flag = *flag | 1 << 1;
1681 target_value.append(&mut hex::decode("009000000000000f42400000271000000014").unwrap());
1682 if htlc_maximum_msat {
1683 target_value.append(&mut hex::decode("000000003b9aca00").unwrap());
1685 assert_eq!(encoded_value, target_value);
1689 fn encoding_channel_update() {
1690 do_encoding_channel_update(false, false, false, false);
1691 do_encoding_channel_update(true, false, false, false);
1692 do_encoding_channel_update(false, true, false, false);
1693 do_encoding_channel_update(false, false, true, false);
1694 do_encoding_channel_update(false, false, false, true);
1695 do_encoding_channel_update(true, true, true, true);
1698 fn do_encoding_open_channel(non_bitcoin_chain_hash: bool, random_bit: bool, shutdown: bool) {
1699 let secp_ctx = Secp256k1::new();
1700 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1701 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1702 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1703 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1704 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1705 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1706 let open_channel = msgs::OpenChannel {
1707 chain_hash: if !non_bitcoin_chain_hash { Sha256dHash::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap() } else { Sha256dHash::from_hex("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943").unwrap() },
1708 temporary_channel_id: [2; 32],
1709 funding_satoshis: 1311768467284833366,
1710 push_msat: 2536655962884945560,
1711 dust_limit_satoshis: 3608586615801332854,
1712 max_htlc_value_in_flight_msat: 8517154655701053848,
1713 channel_reserve_satoshis: 8665828695742877976,
1714 htlc_minimum_msat: 2316138423780173,
1715 feerate_per_kw: 821716,
1716 to_self_delay: 49340,
1717 max_accepted_htlcs: 49340,
1718 funding_pubkey: pubkey_1,
1719 revocation_basepoint: pubkey_2,
1720 payment_basepoint: pubkey_3,
1721 delayed_payment_basepoint: pubkey_4,
1722 htlc_basepoint: pubkey_5,
1723 first_per_commitment_point: pubkey_6,
1724 channel_flags: if random_bit { 1 << 5 } else { 0 },
1725 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&pubkey_1, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1727 let encoded_value = open_channel.encode();
1728 let mut target_value = Vec::new();
1729 if non_bitcoin_chain_hash {
1730 target_value.append(&mut hex::decode("43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000").unwrap());
1732 target_value.append(&mut hex::decode("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f").unwrap());
1734 target_value.append(&mut hex::decode("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
1736 target_value.append(&mut hex::decode("20").unwrap());
1738 target_value.append(&mut hex::decode("00").unwrap());
1741 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1743 assert_eq!(encoded_value, target_value);
1747 fn encoding_open_channel() {
1748 do_encoding_open_channel(false, false, false);
1749 do_encoding_open_channel(true, false, false);
1750 do_encoding_open_channel(false, true, false);
1751 do_encoding_open_channel(false, false, true);
1752 do_encoding_open_channel(true, true, true);
1755 fn do_encoding_accept_channel(shutdown: bool) {
1756 let secp_ctx = Secp256k1::new();
1757 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1758 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1759 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1760 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1761 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
1762 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
1763 let accept_channel = msgs::AcceptChannel {
1764 temporary_channel_id: [2; 32],
1765 dust_limit_satoshis: 1311768467284833366,
1766 max_htlc_value_in_flight_msat: 2536655962884945560,
1767 channel_reserve_satoshis: 3608586615801332854,
1768 htlc_minimum_msat: 2316138423780173,
1769 minimum_depth: 821716,
1770 to_self_delay: 49340,
1771 max_accepted_htlcs: 49340,
1772 funding_pubkey: pubkey_1,
1773 revocation_basepoint: pubkey_2,
1774 payment_basepoint: pubkey_3,
1775 delayed_payment_basepoint: pubkey_4,
1776 htlc_basepoint: pubkey_5,
1777 first_per_commitment_point: pubkey_6,
1778 shutdown_scriptpubkey: if shutdown { OptionalField::Present(Address::p2pkh(&pubkey_1, Network::Testnet).script_pubkey()) } else { OptionalField::Absent }
1780 let encoded_value = accept_channel.encode();
1781 let mut target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
1783 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1785 assert_eq!(encoded_value, target_value);
1789 fn encoding_accept_channel() {
1790 do_encoding_accept_channel(false);
1791 do_encoding_accept_channel(true);
1795 fn encoding_funding_created() {
1796 let secp_ctx = Secp256k1::new();
1797 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1798 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1799 let funding_created = msgs::FundingCreated {
1800 temporary_channel_id: [2; 32],
1801 funding_txid: Sha256dHash::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
1802 funding_output_index: 255,
1805 let encoded_value = funding_created.encode();
1806 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1807 assert_eq!(encoded_value, target_value);
1811 fn encoding_funding_signed() {
1812 let secp_ctx = Secp256k1::new();
1813 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1814 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1815 let funding_signed = msgs::FundingSigned {
1816 channel_id: [2; 32],
1819 let encoded_value = funding_signed.encode();
1820 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1821 assert_eq!(encoded_value, target_value);
1825 fn encoding_funding_locked() {
1826 let secp_ctx = Secp256k1::new();
1827 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1828 let funding_locked = msgs::FundingLocked {
1829 channel_id: [2; 32],
1830 next_per_commitment_point: pubkey_1,
1832 let encoded_value = funding_locked.encode();
1833 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1834 assert_eq!(encoded_value, target_value);
1837 fn do_encoding_shutdown(script_type: u8) {
1838 let secp_ctx = Secp256k1::new();
1839 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1840 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1841 let shutdown = msgs::Shutdown {
1842 channel_id: [2; 32],
1843 scriptpubkey: if script_type == 1 { Address::p2pkh(&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(&pubkey_1, Network::Testnet).script_pubkey() } else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
1845 let encoded_value = shutdown.encode();
1846 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
1847 if script_type == 1 {
1848 target_value.append(&mut hex::decode("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
1849 } else if script_type == 2 {
1850 target_value.append(&mut hex::decode("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
1851 } else if script_type == 3 {
1852 target_value.append(&mut hex::decode("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
1853 } else if script_type == 4 {
1854 target_value.append(&mut hex::decode("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
1856 assert_eq!(encoded_value, target_value);
1860 fn encoding_shutdown() {
1861 do_encoding_shutdown(1);
1862 do_encoding_shutdown(2);
1863 do_encoding_shutdown(3);
1864 do_encoding_shutdown(4);
1868 fn encoding_closing_signed() {
1869 let secp_ctx = Secp256k1::new();
1870 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1871 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1872 let closing_signed = msgs::ClosingSigned {
1873 channel_id: [2; 32],
1874 fee_satoshis: 2316138423780173,
1877 let encoded_value = closing_signed.encode();
1878 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1879 assert_eq!(encoded_value, target_value);
1883 fn encoding_update_add_htlc() {
1884 let secp_ctx = Secp256k1::new();
1885 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1886 let onion_routing_packet = msgs::OnionPacket {
1888 public_key: Ok(pubkey_1),
1889 hop_data: [1; 20*65],
1892 let update_add_htlc = msgs::UpdateAddHTLC {
1893 channel_id: [2; 32],
1894 htlc_id: 2316138423780173,
1895 amount_msat: 3608586615801332854,
1896 payment_hash: PaymentHash([1; 32]),
1897 cltv_expiry: 821716,
1898 onion_routing_packet
1900 let encoded_value = update_add_htlc.encode();
1901 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
1902 assert_eq!(encoded_value, target_value);
1906 fn encoding_update_fulfill_htlc() {
1907 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
1908 channel_id: [2; 32],
1909 htlc_id: 2316138423780173,
1910 payment_preimage: PaymentPreimage([1; 32]),
1912 let encoded_value = update_fulfill_htlc.encode();
1913 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
1914 assert_eq!(encoded_value, target_value);
1918 fn encoding_update_fail_htlc() {
1919 let reason = OnionErrorPacket {
1920 data: [1; 32].to_vec(),
1922 let update_fail_htlc = msgs::UpdateFailHTLC {
1923 channel_id: [2; 32],
1924 htlc_id: 2316138423780173,
1927 let encoded_value = update_fail_htlc.encode();
1928 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
1929 assert_eq!(encoded_value, target_value);
1933 fn encoding_update_fail_malformed_htlc() {
1934 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
1935 channel_id: [2; 32],
1936 htlc_id: 2316138423780173,
1937 sha256_of_onion: [1; 32],
1940 let encoded_value = update_fail_malformed_htlc.encode();
1941 let target_value = hex::decode("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
1942 assert_eq!(encoded_value, target_value);
1945 fn do_encoding_commitment_signed(htlcs: bool) {
1946 let secp_ctx = Secp256k1::new();
1947 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1948 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
1949 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
1950 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
1951 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
1952 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
1953 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
1954 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
1955 let commitment_signed = msgs::CommitmentSigned {
1956 channel_id: [2; 32],
1958 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
1960 let encoded_value = commitment_signed.encode();
1961 let mut target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
1963 target_value.append(&mut hex::decode("00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
1965 target_value.append(&mut hex::decode("0000").unwrap());
1967 assert_eq!(encoded_value, target_value);
1971 fn encoding_commitment_signed() {
1972 do_encoding_commitment_signed(true);
1973 do_encoding_commitment_signed(false);
1977 fn encoding_revoke_and_ack() {
1978 let secp_ctx = Secp256k1::new();
1979 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
1980 let raa = msgs::RevokeAndACK {
1981 channel_id: [2; 32],
1982 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],
1983 next_per_commitment_point: pubkey_1,
1985 let encoded_value = raa.encode();
1986 let target_value = hex::decode("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
1987 assert_eq!(encoded_value, target_value);
1991 fn encoding_update_fee() {
1992 let update_fee = msgs::UpdateFee {
1993 channel_id: [2; 32],
1994 feerate_per_kw: 20190119,
1996 let encoded_value = update_fee.encode();
1997 let target_value = hex::decode("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
1998 assert_eq!(encoded_value, target_value);