1use bitcoin::constants::ChainHash;
28use bitcoin::secp256k1::PublicKey;
29use bitcoin::secp256k1::ecdsa::Signature;
30use bitcoin::{secp256k1, Witness};
31use bitcoin::script::ScriptBuf;
32use bitcoin::hash_types::Txid;
33
34use crate::blinded_path::payment::{BlindedPaymentTlvs, ForwardTlvs, ReceiveTlvs, UnauthenticatedReceiveTlvs};
35use crate::ln::channelmanager::Verification;
36use crate::ln::types::ChannelId;
37use crate::types::payment::{PaymentPreimage, PaymentHash, PaymentSecret};
38use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
39use crate::ln::onion_utils;
40use crate::onion_message;
41use crate::sign::{NodeSigner, Recipient};
42
43#[allow(unused_imports)]
44use crate::prelude::*;
45
46use core::fmt;
47use core::fmt::Debug;
48use core::ops::Deref;
49#[cfg(feature = "std")]
50use core::str::FromStr;
51#[cfg(feature = "std")]
52use std::net::SocketAddr;
53use core::fmt::Display;
54use crate::io::{self, Cursor, Read};
55use crate::io_extras::read_to_end;
56
57use crate::events::MessageSendEventsProvider;
58use crate::crypto::streams::ChaChaPolyReadAdapter;
59use crate::util::logger;
60use crate::util::ser::{BigSize, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, TransactionU16LenLimited, WithoutLength, Writeable, Writer};
61use crate::util::base32;
62
63use crate::routing::gossip::{NodeAlias, NodeId};
64
65pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
67
68#[cfg(taproot)]
69#[derive(Clone, Debug, Hash, PartialEq, Eq)]
71pub struct PartialSignatureWithNonce(pub musig2::types::PartialSignature, pub musig2::types::PublicNonce);
72
73#[derive(Clone, Debug, Hash, PartialEq, Eq)]
75pub enum DecodeError {
76 UnknownVersion,
80 UnknownRequiredFeature,
82 InvalidValue,
88 ShortRead,
90 BadLengthDescriptor,
92 Io(io::ErrorKind),
94 UnsupportedCompression,
96 DangerousValue,
106}
107
108#[derive(Clone, Debug, Hash, PartialEq, Eq)]
112pub struct Init {
113 pub features: InitFeatures,
115 pub networks: Option<Vec<ChainHash>>,
119 pub remote_network_address: Option<SocketAddress>,
126}
127
128#[derive(Clone, Debug, Hash, PartialEq, Eq)]
132pub struct ErrorMessage {
133 pub channel_id: ChannelId,
138 pub data: String,
144}
145
146#[derive(Clone, Debug, Hash, PartialEq, Eq)]
150pub struct WarningMessage {
151 pub channel_id: ChannelId,
155 pub data: String,
161}
162
163#[derive(Clone, Debug, Hash, PartialEq, Eq)]
167pub struct Ping {
168 pub ponglen: u16,
170 pub byteslen: u16,
174}
175
176#[derive(Clone, Debug, Hash, PartialEq, Eq)]
180pub struct Pong {
181 pub byteslen: u16,
185}
186
187#[derive(Clone, Debug, Hash, PartialEq, Eq)]
192pub struct CommonOpenChannelFields {
193 pub chain_hash: ChainHash,
195 pub temporary_channel_id: ChannelId,
199 pub funding_satoshis: u64,
202 pub dust_limit_satoshis: u64,
205 pub max_htlc_value_in_flight_msat: u64,
207 pub htlc_minimum_msat: u64,
209 pub commitment_feerate_sat_per_1000_weight: u32,
212 pub to_self_delay: u16,
215 pub max_accepted_htlcs: u16,
217 pub funding_pubkey: PublicKey,
219 pub revocation_basepoint: PublicKey,
221 pub payment_basepoint: PublicKey,
223 pub delayed_payment_basepoint: PublicKey,
226 pub htlc_basepoint: PublicKey,
228 pub first_per_commitment_point: PublicKey,
230 pub channel_flags: u8,
232 pub shutdown_scriptpubkey: Option<ScriptBuf>,
235 pub channel_type: Option<ChannelTypeFeatures>,
240}
241
242impl CommonOpenChannelFields {
243 pub fn channel_parameters(&self) -> ChannelParameters {
245 ChannelParameters {
246 dust_limit_satoshis: self.dust_limit_satoshis,
247 max_htlc_value_in_flight_msat: self.max_htlc_value_in_flight_msat,
248 htlc_minimum_msat: self.htlc_minimum_msat,
249 commitment_feerate_sat_per_1000_weight: self.commitment_feerate_sat_per_1000_weight,
250 to_self_delay: self.to_self_delay,
251 max_accepted_htlcs: self.max_accepted_htlcs,
252 }
253 }
254}
255
256#[derive(Clone, Debug, Hash, PartialEq, Eq)]
259pub struct ChannelParameters {
260 pub dust_limit_satoshis: u64,
263 pub max_htlc_value_in_flight_msat: u64,
265 pub htlc_minimum_msat: u64,
267 pub commitment_feerate_sat_per_1000_weight: u32,
270 pub to_self_delay: u16,
273 pub max_accepted_htlcs: u16,
275}
276
277#[derive(Clone, Debug, Hash, PartialEq, Eq)]
283pub struct OpenChannel {
284 pub common_fields: CommonOpenChannelFields,
286 pub push_msat: u64,
288 pub channel_reserve_satoshis: u64,
290}
291
292#[derive(Clone, Debug, Hash, PartialEq, Eq)]
298pub struct OpenChannelV2 {
299 pub common_fields: CommonOpenChannelFields,
301 pub funding_feerate_sat_per_1000_weight: u32,
303 pub locktime: u32,
305 pub second_per_commitment_point: PublicKey,
307 pub require_confirmed_inputs: Option<()>,
309}
310
311#[derive(Clone, Debug, Hash, PartialEq, Eq)]
316pub struct CommonAcceptChannelFields {
317 pub temporary_channel_id: ChannelId,
319 pub dust_limit_satoshis: u64,
322 pub max_htlc_value_in_flight_msat: u64,
324 pub htlc_minimum_msat: u64,
326 pub minimum_depth: u32,
328 pub to_self_delay: u16,
331 pub max_accepted_htlcs: u16,
333 pub funding_pubkey: PublicKey,
335 pub revocation_basepoint: PublicKey,
337 pub payment_basepoint: PublicKey,
339 pub delayed_payment_basepoint: PublicKey,
342 pub htlc_basepoint: PublicKey,
344 pub first_per_commitment_point: PublicKey,
346 pub shutdown_scriptpubkey: Option<ScriptBuf>,
349 pub channel_type: Option<ChannelTypeFeatures>,
356}
357
358#[derive(Clone, Debug, Hash, PartialEq, Eq)]
364pub struct AcceptChannel {
365 pub common_fields: CommonAcceptChannelFields,
367 pub channel_reserve_satoshis: u64,
369 #[cfg(taproot)]
370 pub next_local_nonce: Option<musig2::types::PublicNonce>,
372}
373
374#[derive(Clone, Debug, Hash, PartialEq, Eq)]
380pub struct AcceptChannelV2 {
381 pub common_fields: CommonAcceptChannelFields,
383 pub funding_satoshis: u64,
385 pub second_per_commitment_point: PublicKey,
387 pub require_confirmed_inputs: Option<()>,
389}
390
391#[derive(Clone, Debug, Hash, PartialEq, Eq)]
397pub struct FundingCreated {
398 pub temporary_channel_id: ChannelId,
400 pub funding_txid: Txid,
402 pub funding_output_index: u16,
404 pub signature: Signature,
406 #[cfg(taproot)]
407 pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
409 #[cfg(taproot)]
410 pub next_local_nonce: Option<musig2::types::PublicNonce>
412}
413
414#[derive(Clone, Debug, Hash, PartialEq, Eq)]
420pub struct FundingSigned {
421 pub channel_id: ChannelId,
423 pub signature: Signature,
425 #[cfg(taproot)]
426 pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
428}
429
430#[derive(Clone, Debug, Hash, PartialEq, Eq)]
434pub struct ChannelReady {
435 pub channel_id: ChannelId,
437 pub next_per_commitment_point: PublicKey,
439 pub short_channel_id_alias: Option<u64>,
444}
445
446pub type SerialId = u64;
449
450#[derive(Clone, Debug, PartialEq, Eq)]
454pub struct Stfu {
455 pub channel_id: ChannelId,
457 pub initiator: u8,
459}
460
461#[derive(Clone, Debug, PartialEq, Eq)]
465pub struct SpliceInit {
466 pub channel_id: ChannelId,
468 pub funding_contribution_satoshis: i64,
471 pub funding_feerate_perkw: u32,
473 pub locktime: u32,
475 pub funding_pubkey: PublicKey,
477 pub require_confirmed_inputs: Option<()>,
479}
480
481#[derive(Clone, Debug, PartialEq, Eq)]
485pub struct SpliceAck {
486 pub channel_id: ChannelId,
488 pub funding_contribution_satoshis: i64,
491 pub funding_pubkey: PublicKey,
493 pub require_confirmed_inputs: Option<()>,
495}
496
497#[derive(Clone, Debug, PartialEq, Eq)]
501pub struct SpliceLocked {
502 pub channel_id: ChannelId,
504 pub splice_txid: Txid,
506}
507
508#[derive(Clone, Debug, Hash, PartialEq, Eq)]
512pub struct TxAddInput {
513 pub channel_id: ChannelId,
515 pub serial_id: SerialId,
518 pub prevtx: TransactionU16LenLimited,
521 pub prevtx_out: u32,
523 pub sequence: u32,
525 pub shared_input_txid: Option<Txid>,
527}
528
529#[derive(Clone, Debug, Hash, PartialEq, Eq)]
533pub struct TxAddOutput {
534 pub channel_id: ChannelId,
536 pub serial_id: SerialId,
539 pub sats: u64,
541 pub script: ScriptBuf,
543}
544
545#[derive(Clone, Debug, Hash, PartialEq, Eq)]
549pub struct TxRemoveInput {
550 pub channel_id: ChannelId,
552 pub serial_id: SerialId,
554}
555
556#[derive(Clone, Debug, Hash, PartialEq, Eq)]
560pub struct TxRemoveOutput {
561 pub channel_id: ChannelId,
563 pub serial_id: SerialId,
565}
566
567#[derive(Clone, Debug, Hash, PartialEq, Eq)]
572pub struct TxComplete {
573 pub channel_id: ChannelId,
575}
576
577#[derive(Clone, Debug, Hash, PartialEq, Eq)]
582pub struct TxSignatures {
583 pub channel_id: ChannelId,
585 pub tx_hash: Txid,
587 pub witnesses: Vec<Witness>,
589 pub shared_input_signature: Option<Signature>,
591}
592
593#[derive(Clone, Debug, Hash, PartialEq, Eq)]
598pub struct TxInitRbf {
599 pub channel_id: ChannelId,
601 pub locktime: u32,
603 pub feerate_sat_per_1000_weight: u32,
605 pub funding_output_contribution: Option<i64>,
608}
609
610#[derive(Clone, Debug, Hash, PartialEq, Eq)]
615pub struct TxAckRbf {
616 pub channel_id: ChannelId,
618 pub funding_output_contribution: Option<i64>,
621}
622
623#[derive(Clone, Debug, Hash, PartialEq, Eq)]
627pub struct TxAbort {
628 pub channel_id: ChannelId,
630 pub data: Vec<u8>,
632}
633
634#[derive(Clone, Debug, Hash, PartialEq, Eq)]
638pub struct Shutdown {
639 pub channel_id: ChannelId,
641 pub scriptpubkey: ScriptBuf,
645}
646
647#[derive(Clone, Debug, Hash, PartialEq, Eq)]
652pub struct ClosingSignedFeeRange {
653 pub min_fee_satoshis: u64,
656 pub max_fee_satoshis: u64,
659}
660
661#[derive(Clone, Debug, Hash, PartialEq, Eq)]
665pub struct ClosingSigned {
666 pub channel_id: ChannelId,
668 pub fee_satoshis: u64,
670 pub signature: Signature,
672 pub fee_range: Option<ClosingSignedFeeRange>,
675}
676
677#[derive(Clone, Debug, Hash, PartialEq, Eq)]
681pub struct UpdateAddHTLC {
682 pub channel_id: ChannelId,
684 pub htlc_id: u64,
686 pub amount_msat: u64,
688 pub payment_hash: PaymentHash,
690 pub cltv_expiry: u32,
692 pub skimmed_fee_msat: Option<u64>,
697 pub onion_routing_packet: OnionPacket,
699 pub blinding_point: Option<PublicKey>,
702}
703
704 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
708pub struct OnionMessage {
709 pub blinding_point: PublicKey,
711 pub onion_routing_packet: onion_message::packet::Packet,
713}
714
715#[derive(Clone, Debug, Hash, PartialEq, Eq)]
719pub struct UpdateFulfillHTLC {
720 pub channel_id: ChannelId,
722 pub htlc_id: u64,
724 pub payment_preimage: PaymentPreimage,
726}
727
728#[derive(Clone, Debug, Hash, PartialEq, Eq)]
732pub struct UpdateFailHTLC {
733 pub channel_id: ChannelId,
735 pub htlc_id: u64,
737 pub(crate) reason: OnionErrorPacket,
738}
739
740#[derive(Clone, Debug, Hash, PartialEq, Eq)]
744pub struct UpdateFailMalformedHTLC {
745 pub channel_id: ChannelId,
747 pub htlc_id: u64,
749 pub(crate) sha256_of_onion: [u8; 32],
750 pub failure_code: u16,
752}
753
754#[derive(Clone, Debug, Hash, PartialEq, Eq)]
756pub struct CommitmentSignedBatch {
757 pub batch_size: u16,
759 pub funding_txid: Txid,
761}
762
763#[derive(Clone, Debug, Hash, PartialEq, Eq)]
767pub struct CommitmentSigned {
768 pub channel_id: ChannelId,
770 pub signature: Signature,
772 pub htlc_signatures: Vec<Signature>,
774 pub batch: Option<CommitmentSignedBatch>,
776 #[cfg(taproot)]
777 pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
779}
780
781#[derive(Clone, Debug, Hash, PartialEq, Eq)]
785pub struct RevokeAndACK {
786 pub channel_id: ChannelId,
788 pub per_commitment_secret: [u8; 32],
790 pub next_per_commitment_point: PublicKey,
792 #[cfg(taproot)]
793 pub next_local_nonce: Option<musig2::types::PublicNonce>
795}
796
797#[derive(Clone, Debug, Hash, PartialEq, Eq)]
801pub struct UpdateFee {
802 pub channel_id: ChannelId,
804 pub feerate_per_kw: u32,
806}
807
808#[derive(Clone, Debug, Hash, PartialEq, Eq)]
812pub struct ChannelReestablish {
813 pub channel_id: ChannelId,
815 pub next_local_commitment_number: u64,
817 pub next_remote_commitment_number: u64,
819 pub your_last_per_commitment_secret: [u8; 32],
822 pub my_current_per_commitment_point: PublicKey,
824 pub next_funding_txid: Option<Txid>,
826}
827
828#[derive(Clone, Debug, Hash, PartialEq, Eq)]
832pub struct AnnouncementSignatures {
833 pub channel_id: ChannelId,
835 pub short_channel_id: u64,
837 pub node_signature: Signature,
839 pub bitcoin_signature: Signature,
841}
842
843#[derive(Clone, Debug, Hash, PartialEq, Eq)]
845pub enum SocketAddress {
846 TcpIpV4 {
848 addr: [u8; 4],
850 port: u16,
852 },
853 TcpIpV6 {
855 addr: [u8; 16],
857 port: u16,
859 },
860 OnionV2([u8; 12]),
865 OnionV3 {
870 ed25519_pubkey: [u8; 32],
872 checksum: u16,
874 version: u8,
876 port: u16,
878 },
879 Hostname {
881 hostname: Hostname,
883 port: u16,
885 },
886}
887impl SocketAddress {
888 pub(crate) fn get_id(&self) -> u8 {
891 match self {
892 &SocketAddress::TcpIpV4 {..} => { 1 },
893 &SocketAddress::TcpIpV6 {..} => { 2 },
894 &SocketAddress::OnionV2(_) => { 3 },
895 &SocketAddress::OnionV3 {..} => { 4 },
896 &SocketAddress::Hostname {..} => { 5 },
897 }
898 }
899
900 fn len(&self) -> u16 {
902 match self {
903 &SocketAddress::TcpIpV4 { .. } => { 6 },
904 &SocketAddress::TcpIpV6 { .. } => { 18 },
905 &SocketAddress::OnionV2(_) => { 12 },
906 &SocketAddress::OnionV3 { .. } => { 37 },
907 &SocketAddress::Hostname { ref hostname, .. } => { u16::from(hostname.len()) + 3 },
909 }
910 }
911
912 pub(crate) const MAX_LEN: u16 = 258;
916
917 pub(crate) fn is_tor(&self) -> bool {
918 match self {
919 &SocketAddress::TcpIpV4 {..} => false,
920 &SocketAddress::TcpIpV6 {..} => false,
921 &SocketAddress::OnionV2(_) => true,
922 &SocketAddress::OnionV3 {..} => true,
923 &SocketAddress::Hostname {..} => false,
924 }
925 }
926}
927
928impl Writeable for SocketAddress {
929 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
930 match self {
931 &SocketAddress::TcpIpV4 { ref addr, ref port } => {
932 1u8.write(writer)?;
933 addr.write(writer)?;
934 port.write(writer)?;
935 },
936 &SocketAddress::TcpIpV6 { ref addr, ref port } => {
937 2u8.write(writer)?;
938 addr.write(writer)?;
939 port.write(writer)?;
940 },
941 &SocketAddress::OnionV2(bytes) => {
942 3u8.write(writer)?;
943 bytes.write(writer)?;
944 },
945 &SocketAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
946 4u8.write(writer)?;
947 ed25519_pubkey.write(writer)?;
948 checksum.write(writer)?;
949 version.write(writer)?;
950 port.write(writer)?;
951 },
952 &SocketAddress::Hostname { ref hostname, ref port } => {
953 5u8.write(writer)?;
954 hostname.write(writer)?;
955 port.write(writer)?;
956 },
957 }
958 Ok(())
959 }
960}
961
962impl Readable for Result<SocketAddress, u8> {
963 fn read<R: Read>(reader: &mut R) -> Result<Result<SocketAddress, u8>, DecodeError> {
964 let byte = <u8 as Readable>::read(reader)?;
965 match byte {
966 1 => {
967 Ok(Ok(SocketAddress::TcpIpV4 {
968 addr: Readable::read(reader)?,
969 port: Readable::read(reader)?,
970 }))
971 },
972 2 => {
973 Ok(Ok(SocketAddress::TcpIpV6 {
974 addr: Readable::read(reader)?,
975 port: Readable::read(reader)?,
976 }))
977 },
978 3 => Ok(Ok(SocketAddress::OnionV2(Readable::read(reader)?))),
979 4 => {
980 Ok(Ok(SocketAddress::OnionV3 {
981 ed25519_pubkey: Readable::read(reader)?,
982 checksum: Readable::read(reader)?,
983 version: Readable::read(reader)?,
984 port: Readable::read(reader)?,
985 }))
986 },
987 5 => {
988 Ok(Ok(SocketAddress::Hostname {
989 hostname: Readable::read(reader)?,
990 port: Readable::read(reader)?,
991 }))
992 },
993 _ => return Ok(Err(byte)),
994 }
995 }
996}
997
998impl Readable for SocketAddress {
999 fn read<R: Read>(reader: &mut R) -> Result<SocketAddress, DecodeError> {
1000 match Readable::read(reader) {
1001 Ok(Ok(res)) => Ok(res),
1002 Ok(Err(_)) => Err(DecodeError::UnknownVersion),
1003 Err(e) => Err(e),
1004 }
1005 }
1006}
1007
1008#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1010pub enum SocketAddressParseError {
1011 SocketAddrParse,
1013 InvalidInput,
1015 InvalidPort,
1017 InvalidOnionV3,
1019}
1020
1021impl fmt::Display for SocketAddressParseError {
1022 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1023 match self {
1024 SocketAddressParseError::SocketAddrParse => write!(f, "Socket address (IPv4/IPv6) parsing error"),
1025 SocketAddressParseError::InvalidInput => write!(f, "Invalid input format. \
1026 Expected: \"<ipv4>:<port>\", \"[<ipv6>]:<port>\", \"<onion address>.onion:<port>\" or \"<hostname>:<port>\""),
1027 SocketAddressParseError::InvalidPort => write!(f, "Invalid port"),
1028 SocketAddressParseError::InvalidOnionV3 => write!(f, "Invalid onion v3 address"),
1029 }
1030 }
1031}
1032
1033#[cfg(feature = "std")]
1034impl From<std::net::SocketAddrV4> for SocketAddress {
1035 fn from(addr: std::net::SocketAddrV4) -> Self {
1036 SocketAddress::TcpIpV4 { addr: addr.ip().octets(), port: addr.port() }
1037 }
1038}
1039
1040#[cfg(feature = "std")]
1041impl From<std::net::SocketAddrV6> for SocketAddress {
1042 fn from(addr: std::net::SocketAddrV6) -> Self {
1043 SocketAddress::TcpIpV6 { addr: addr.ip().octets(), port: addr.port() }
1044 }
1045}
1046
1047#[cfg(feature = "std")]
1048impl From<std::net::SocketAddr> for SocketAddress {
1049 fn from(addr: std::net::SocketAddr) -> Self {
1050 match addr {
1051 std::net::SocketAddr::V4(addr) => addr.into(),
1052 std::net::SocketAddr::V6(addr) => addr.into(),
1053 }
1054 }
1055}
1056
1057#[cfg(feature = "std")]
1058impl std::net::ToSocketAddrs for SocketAddress {
1059 type Iter = std::vec::IntoIter<std::net::SocketAddr>;
1060
1061 fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
1062 match self {
1063 SocketAddress::TcpIpV4 { addr, port } => {
1064 let ip_addr = std::net::Ipv4Addr::from(*addr);
1065 let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1066 Ok(vec![socket_addr].into_iter())
1067 }
1068 SocketAddress::TcpIpV6 { addr, port } => {
1069 let ip_addr = std::net::Ipv6Addr::from(*addr);
1070 let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1071 Ok(vec![socket_addr].into_iter())
1072 }
1073 SocketAddress::Hostname { ref hostname, port } => {
1074 (hostname.as_str(), *port).to_socket_addrs()
1075 }
1076 SocketAddress::OnionV2(..) => {
1077 Err(std::io::Error::new(std::io::ErrorKind::Other, "Resolution of OnionV2 \
1078 addresses is currently unsupported."))
1079 }
1080 SocketAddress::OnionV3 { .. } => {
1081 Err(std::io::Error::new(std::io::ErrorKind::Other, "Resolution of OnionV3 \
1082 addresses is currently unsupported."))
1083 }
1084 }
1085 }
1086}
1087
1088pub fn parse_onion_address(host: &str, port: u16) -> Result<SocketAddress, SocketAddressParseError> {
1092 if host.ends_with(".onion") {
1093 let domain = &host[..host.len() - ".onion".len()];
1094 if domain.len() != 56 {
1095 return Err(SocketAddressParseError::InvalidOnionV3);
1096 }
1097 let onion = base32::Alphabet::RFC4648 { padding: false }.decode(&domain).map_err(|_| SocketAddressParseError::InvalidOnionV3)?;
1098 if onion.len() != 35 {
1099 return Err(SocketAddressParseError::InvalidOnionV3);
1100 }
1101 let version = onion[0];
1102 let first_checksum_flag = onion[1];
1103 let second_checksum_flag = onion[2];
1104 let mut ed25519_pubkey = [0; 32];
1105 ed25519_pubkey.copy_from_slice(&onion[3..35]);
1106 let checksum = u16::from_be_bytes([first_checksum_flag, second_checksum_flag]);
1107 return Ok(SocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port });
1108
1109 } else {
1110 return Err(SocketAddressParseError::InvalidInput);
1111 }
1112}
1113
1114impl Display for SocketAddress {
1115 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1116 match self {
1117 SocketAddress::TcpIpV4{addr, port} => write!(
1118 f, "{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)?,
1119 SocketAddress::TcpIpV6{addr, port} => write!(
1120 f,
1121 "[{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}]:{}",
1122 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], addr[8], addr[9], addr[10], addr[11], addr[12], addr[13], addr[14], addr[15], port
1123 )?,
1124 SocketAddress::OnionV2(bytes) => write!(f, "OnionV2({:?})", bytes)?,
1125 SocketAddress::OnionV3 {
1126 ed25519_pubkey,
1127 checksum,
1128 version,
1129 port,
1130 } => {
1131 let [first_checksum_flag, second_checksum_flag] = checksum.to_be_bytes();
1132 let mut addr = vec![*version, first_checksum_flag, second_checksum_flag];
1133 addr.extend_from_slice(ed25519_pubkey);
1134 let onion = base32::Alphabet::RFC4648 { padding: false }.encode(&addr);
1135 write!(f, "{}.onion:{}", onion, port)?
1136 },
1137 SocketAddress::Hostname { hostname, port } => write!(f, "{}:{}", hostname, port)?,
1138 }
1139 Ok(())
1140 }
1141}
1142
1143#[cfg(feature = "std")]
1144impl FromStr for SocketAddress {
1145 type Err = SocketAddressParseError;
1146
1147 fn from_str(s: &str) -> Result<Self, Self::Err> {
1148 match std::net::SocketAddr::from_str(s) {
1149 Ok(addr) => Ok(addr.into()),
1150 Err(_) => {
1151 let trimmed_input = match s.rfind(":") {
1152 Some(pos) => pos,
1153 None => return Err(SocketAddressParseError::InvalidInput),
1154 };
1155 let host = &s[..trimmed_input];
1156 let port: u16 = s[trimmed_input + 1..].parse().map_err(|_| SocketAddressParseError::InvalidPort)?;
1157 if host.ends_with(".onion") {
1158 return parse_onion_address(host, port);
1159 };
1160 if let Ok(hostname) = Hostname::try_from(s[..trimmed_input].to_string()) {
1161 return Ok(SocketAddress::Hostname { hostname, port });
1162 };
1163 return Err(SocketAddressParseError::SocketAddrParse)
1164 },
1165 }
1166 }
1167}
1168
1169pub enum UnsignedGossipMessage<'a> {
1171 ChannelAnnouncement(&'a UnsignedChannelAnnouncement),
1173 ChannelUpdate(&'a UnsignedChannelUpdate),
1175 NodeAnnouncement(&'a UnsignedNodeAnnouncement)
1177}
1178
1179impl<'a> Writeable for UnsignedGossipMessage<'a> {
1180 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1181 match self {
1182 UnsignedGossipMessage::ChannelAnnouncement(ref msg) => msg.write(writer),
1183 UnsignedGossipMessage::ChannelUpdate(ref msg) => msg.write(writer),
1184 UnsignedGossipMessage::NodeAnnouncement(ref msg) => msg.write(writer),
1185 }
1186 }
1187}
1188
1189#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1193pub struct UnsignedNodeAnnouncement {
1194 pub features: NodeFeatures,
1196 pub timestamp: u32,
1198 pub node_id: NodeId,
1201 pub rgb: [u8; 3],
1203 pub alias: NodeAlias,
1207 pub addresses: Vec<SocketAddress>,
1209 pub excess_address_data: Vec<u8>,
1214 pub excess_data: Vec<u8>,
1219}
1220#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1221pub struct NodeAnnouncement {
1225 pub signature: Signature,
1227 pub contents: UnsignedNodeAnnouncement,
1229}
1230
1231#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1235pub struct UnsignedChannelAnnouncement {
1236 pub features: ChannelFeatures,
1238 pub chain_hash: ChainHash,
1240 pub short_channel_id: u64,
1242 pub node_id_1: NodeId,
1244 pub node_id_2: NodeId,
1246 pub bitcoin_key_1: NodeId,
1248 pub bitcoin_key_2: NodeId,
1250 pub excess_data: Vec<u8>,
1255}
1256#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1260pub struct ChannelAnnouncement {
1261 pub node_signature_1: Signature,
1263 pub node_signature_2: Signature,
1265 pub bitcoin_signature_1: Signature,
1267 pub bitcoin_signature_2: Signature,
1269 pub contents: UnsignedChannelAnnouncement,
1271}
1272
1273#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1277pub struct UnsignedChannelUpdate {
1278 pub chain_hash: ChainHash,
1280 pub short_channel_id: u64,
1282 pub timestamp: u32,
1284 pub message_flags: u8,
1286 pub channel_flags: u8,
1289 pub cltv_expiry_delta: u16,
1298 pub htlc_minimum_msat: u64,
1300 pub htlc_maximum_msat: u64,
1304 pub fee_base_msat: u32,
1306 pub fee_proportional_millionths: u32,
1308 pub excess_data: Vec<u8>,
1313}
1314#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1318pub struct ChannelUpdate {
1319 pub signature: Signature,
1321 pub contents: UnsignedChannelUpdate,
1323}
1324
1325#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1332pub struct QueryChannelRange {
1333 pub chain_hash: ChainHash,
1335 pub first_blocknum: u32,
1337 pub number_of_blocks: u32,
1339}
1340
1341#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1353pub struct ReplyChannelRange {
1354 pub chain_hash: ChainHash,
1356 pub first_blocknum: u32,
1358 pub number_of_blocks: u32,
1360 pub sync_complete: bool,
1362 pub short_channel_ids: Vec<u64>,
1364}
1365
1366#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1378pub struct QueryShortChannelIds {
1379 pub chain_hash: ChainHash,
1381 pub short_channel_ids: Vec<u64>,
1383}
1384
1385#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1392pub struct ReplyShortChannelIdsEnd {
1393 pub chain_hash: ChainHash,
1395 pub full_information: bool,
1398}
1399
1400#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1406pub struct GossipTimestampFilter {
1407 pub chain_hash: ChainHash,
1409 pub first_timestamp: u32,
1411 pub timestamp_range: u32,
1413}
1414
1415enum EncodingType {
1420 Uncompressed = 0x00,
1421}
1422
1423#[derive(Clone, Debug, Hash, PartialEq)]
1425pub enum ErrorAction {
1426 DisconnectPeer {
1428 msg: Option<ErrorMessage>
1430 },
1431 DisconnectPeerWithWarning {
1433 msg: WarningMessage,
1435 },
1436 IgnoreError,
1439 IgnoreAndLog(logger::Level),
1442 IgnoreDuplicateGossip,
1446 SendErrorMessage {
1448 msg: ErrorMessage,
1450 },
1451 SendWarningMessage {
1453 msg: WarningMessage,
1455 log_level: logger::Level,
1459 },
1460}
1461
1462#[derive(Clone, Debug)]
1464pub struct LightningError {
1465 pub err: String,
1467 pub action: ErrorAction,
1469}
1470
1471#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1474pub struct CommitmentUpdate {
1475 pub update_add_htlcs: Vec<UpdateAddHTLC>,
1477 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
1479 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
1481 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
1483 pub update_fee: Option<UpdateFee>,
1485 pub commitment_signed: CommitmentSigned,
1487}
1488
1489pub trait ChannelMessageHandler : MessageSendEventsProvider {
1494 fn handle_open_channel(&self, their_node_id: PublicKey, msg: &OpenChannel);
1497 fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &OpenChannelV2);
1499 fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &AcceptChannel);
1501 fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &AcceptChannelV2);
1503 fn handle_funding_created(&self, their_node_id: PublicKey, msg: &FundingCreated);
1505 fn handle_funding_signed(&self, their_node_id: PublicKey, msg: &FundingSigned);
1507 fn handle_channel_ready(&self, their_node_id: PublicKey, msg: &ChannelReady);
1509
1510 fn handle_shutdown(&self, their_node_id: PublicKey, msg: &Shutdown);
1513 fn handle_closing_signed(&self, their_node_id: PublicKey, msg: &ClosingSigned);
1515
1516 fn handle_stfu(&self, their_node_id: PublicKey, msg: &Stfu);
1519
1520 #[cfg(splicing)]
1523 fn handle_splice_init(&self, their_node_id: PublicKey, msg: &SpliceInit);
1524 #[cfg(splicing)]
1526 fn handle_splice_ack(&self, their_node_id: PublicKey, msg: &SpliceAck);
1527 #[cfg(splicing)]
1529 fn handle_splice_locked(&self, their_node_id: PublicKey, msg: &SpliceLocked);
1530
1531 fn handle_tx_add_input(&self, their_node_id: PublicKey, msg: &TxAddInput);
1534 fn handle_tx_add_output(&self, their_node_id: PublicKey, msg: &TxAddOutput);
1536 fn handle_tx_remove_input(&self, their_node_id: PublicKey, msg: &TxRemoveInput);
1538 fn handle_tx_remove_output(&self, their_node_id: PublicKey, msg: &TxRemoveOutput);
1540 fn handle_tx_complete(&self, their_node_id: PublicKey, msg: &TxComplete);
1542 fn handle_tx_signatures(&self, their_node_id: PublicKey, msg: &TxSignatures);
1544 fn handle_tx_init_rbf(&self, their_node_id: PublicKey, msg: &TxInitRbf);
1546 fn handle_tx_ack_rbf(&self, their_node_id: PublicKey, msg: &TxAckRbf);
1548 fn handle_tx_abort(&self, their_node_id: PublicKey, msg: &TxAbort);
1550
1551 fn handle_update_add_htlc(&self, their_node_id: PublicKey, msg: &UpdateAddHTLC);
1554 fn handle_update_fulfill_htlc(&self, their_node_id: PublicKey, msg: &UpdateFulfillHTLC);
1556 fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailHTLC);
1558 fn handle_update_fail_malformed_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailMalformedHTLC);
1560 fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &CommitmentSigned);
1562 fn handle_revoke_and_ack(&self, their_node_id: PublicKey, msg: &RevokeAndACK);
1564
1565 fn handle_update_fee(&self, their_node_id: PublicKey, msg: &UpdateFee);
1567
1568 fn handle_announcement_signatures(&self, their_node_id: PublicKey, msg: &AnnouncementSignatures);
1571
1572 fn peer_disconnected(&self, their_node_id: PublicKey);
1575
1576 fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool) -> Result<(), ()>;
1582 fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &ChannelReestablish);
1584
1585 fn handle_channel_update(&self, their_node_id: PublicKey, msg: &ChannelUpdate);
1587
1588 fn handle_error(&self, their_node_id: PublicKey, msg: &ErrorMessage);
1591
1592 fn provided_node_features(&self) -> NodeFeatures;
1597
1598 fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures;
1604
1605 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>>;
1610
1611 fn message_received(&self);
1618}
1619
1620pub trait RoutingMessageHandler : MessageSendEventsProvider {
1628 fn handle_node_announcement(&self, their_node_id: Option<PublicKey>, msg: &NodeAnnouncement) -> Result<bool, LightningError>;
1633 fn handle_channel_announcement(&self, their_node_id: Option<PublicKey>, msg: &ChannelAnnouncement) -> Result<bool, LightningError>;
1638 fn handle_channel_update(&self, their_node_id: Option<PublicKey>, msg: &ChannelUpdate) -> Result<bool, LightningError>;
1643 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
1647 fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement>;
1652 fn peer_connected(&self, their_node_id: PublicKey, init: &Init, inbound: bool) -> Result<(), ()>;
1660 fn handle_reply_channel_range(&self, their_node_id: PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError>;
1664 fn handle_reply_short_channel_ids_end(&self, their_node_id: PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError>;
1669 fn handle_query_channel_range(&self, their_node_id: PublicKey, msg: QueryChannelRange) -> Result<(), LightningError>;
1672 fn handle_query_short_channel_ids(&self, their_node_id: PublicKey, msg: QueryShortChannelIds) -> Result<(), LightningError>;
1675
1676 fn processing_queue_high(&self) -> bool;
1682
1683 fn provided_node_features(&self) -> NodeFeatures;
1688 fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures;
1694}
1695
1696pub trait OnionMessageHandler {
1698 fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage);
1700
1701 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage>;
1703
1704 fn peer_connected(&self, their_node_id: PublicKey, init: &Init, inbound: bool) -> Result<(), ()>;
1711
1712 fn peer_disconnected(&self, their_node_id: PublicKey);
1715
1716 fn timer_tick_occurred(&self);
1719
1720 fn provided_node_features(&self) -> NodeFeatures;
1725
1726 fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures;
1732}
1733
1734#[derive(Clone, Debug, PartialEq, Eq)]
1735pub struct FinalOnionHopData {
1738 pub payment_secret: PaymentSecret,
1742 pub total_msat: u64,
1746}
1747
1748mod fuzzy_internal_msgs {
1749 use bitcoin::secp256k1::PublicKey;
1750 use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, PaymentRelay};
1751 use crate::offers::invoice_request::InvoiceRequest;
1752 use crate::types::payment::{PaymentPreimage, PaymentSecret};
1753 use crate::types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
1754 use super::{FinalOnionHopData, TrampolineOnionPacket};
1755
1756 #[allow(unused_imports)]
1757 use crate::prelude::*;
1758
1759 pub enum InboundOnionPayload {
1763 Forward {
1764 short_channel_id: u64,
1765 amt_to_forward: u64,
1767 outgoing_cltv_value: u32,
1768 },
1769 Receive {
1770 payment_data: Option<FinalOnionHopData>,
1771 payment_metadata: Option<Vec<u8>>,
1772 keysend_preimage: Option<PaymentPreimage>,
1773 custom_tlvs: Vec<(u64, Vec<u8>)>,
1774 sender_intended_htlc_amt_msat: u64,
1775 cltv_expiry_height: u32,
1776 },
1777 BlindedForward {
1778 short_channel_id: u64,
1779 payment_relay: PaymentRelay,
1780 payment_constraints: PaymentConstraints,
1781 features: BlindedHopFeatures,
1782 intro_node_blinding_point: Option<PublicKey>,
1783 next_blinding_override: Option<PublicKey>,
1784 },
1785 BlindedReceive {
1786 sender_intended_htlc_amt_msat: u64,
1787 total_msat: u64,
1788 cltv_expiry_height: u32,
1789 payment_secret: PaymentSecret,
1790 payment_constraints: PaymentConstraints,
1791 payment_context: PaymentContext,
1792 intro_node_blinding_point: Option<PublicKey>,
1793 keysend_preimage: Option<PaymentPreimage>,
1794 custom_tlvs: Vec<(u64, Vec<u8>)>,
1795 }
1796 }
1797
1798 pub(crate) enum OutboundOnionPayload<'a> {
1799 Forward {
1800 short_channel_id: u64,
1801 amt_to_forward: u64,
1803 outgoing_cltv_value: u32,
1804 },
1805 #[allow(unused)]
1806 TrampolineEntrypoint {
1807 amt_to_forward: u64,
1808 outgoing_cltv_value: u32,
1809 multipath_trampoline_data: Option<FinalOnionHopData>,
1810 trampoline_packet: TrampolineOnionPacket,
1811 },
1812 Receive {
1813 payment_data: Option<FinalOnionHopData>,
1814 payment_metadata: Option<&'a Vec<u8>>,
1815 keysend_preimage: Option<PaymentPreimage>,
1816 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
1817 sender_intended_htlc_amt_msat: u64,
1818 cltv_expiry_height: u32,
1819 },
1820 BlindedForward {
1821 encrypted_tlvs: &'a Vec<u8>,
1822 intro_node_blinding_point: Option<PublicKey>,
1823 },
1824 BlindedReceive {
1825 sender_intended_htlc_amt_msat: u64,
1826 total_msat: u64,
1827 cltv_expiry_height: u32,
1828 encrypted_tlvs: &'a Vec<u8>,
1829 intro_node_blinding_point: Option<PublicKey>, keysend_preimage: Option<PaymentPreimage>,
1831 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
1832 invoice_request: Option<&'a InvoiceRequest>,
1833 }
1834 }
1835
1836 pub(crate) enum OutboundTrampolinePayload<'a> {
1837 #[allow(unused)]
1838 Forward {
1839 amt_to_forward: u64,
1841 outgoing_cltv_value: u32,
1842 outgoing_node_id: PublicKey,
1844 },
1845 #[allow(unused)]
1846 LegacyBlindedPathEntry {
1849 amt_to_forward: u64,
1851 outgoing_cltv_value: u32,
1852 payment_paths: Vec<BlindedPaymentPath>,
1854 invoice_features: Option<Bolt12InvoiceFeatures>,
1856 },
1857 #[allow(unused)]
1858 BlindedForward {
1859 encrypted_tlvs: &'a Vec<u8>,
1860 intro_node_blinding_point: Option<PublicKey>,
1861 },
1862 #[allow(unused)]
1863 BlindedReceive {
1864 sender_intended_htlc_amt_msat: u64,
1865 total_msat: u64,
1866 cltv_expiry_height: u32,
1867 encrypted_tlvs: &'a Vec<u8>,
1868 intro_node_blinding_point: Option<PublicKey>, keysend_preimage: Option<PaymentPreimage>,
1870 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
1871 }
1872 }
1873
1874 pub struct DecodedOnionErrorPacket {
1875 pub(crate) hmac: [u8; 32],
1876 pub(crate) failuremsg: Vec<u8>,
1877 pub(crate) pad: Vec<u8>,
1878 }
1879}
1880#[cfg(fuzzing)]
1881pub use self::fuzzy_internal_msgs::*;
1882#[cfg(not(fuzzing))]
1883pub(crate) use self::fuzzy_internal_msgs::*;
1884
1885#[derive(Clone, Hash, PartialEq, Eq)]
1887pub struct OnionPacket {
1888 pub version: u8,
1890 pub public_key: Result<PublicKey, secp256k1::Error>,
1896 pub hop_data: [u8; 20*65],
1898 pub hmac: [u8; 32],
1900}
1901
1902impl onion_utils::Packet for OnionPacket {
1903 type Data = onion_utils::FixedSizeOnionPacket;
1904 fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self {
1905 Self {
1906 version: 0,
1907 public_key: Ok(pubkey),
1908 hop_data: hop_data.0,
1909 hmac,
1910 }
1911 }
1912}
1913
1914impl fmt::Debug for OnionPacket {
1915 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1916 f.write_fmt(format_args!("OnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
1917 }
1918}
1919
1920#[derive(Clone, Hash, PartialEq, Eq)]
1922pub struct TrampolineOnionPacket {
1923 pub version: u8,
1925 pub public_key: PublicKey,
1927 pub hop_data: Vec<u8>,
1934 pub hmac: [u8; 32],
1936}
1937
1938impl onion_utils::Packet for TrampolineOnionPacket {
1939 type Data = Vec<u8>;
1940 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Self {
1941 Self {
1942 version: 0,
1943 public_key,
1944 hop_data,
1945 hmac,
1946 }
1947 }
1948}
1949
1950impl Writeable for TrampolineOnionPacket {
1951 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1952 self.version.write(w)?;
1953 self.public_key.write(w)?;
1954 w.write_all(&self.hop_data)?;
1955 self.hmac.write(w)?;
1956 Ok(())
1957 }
1958}
1959
1960impl LengthReadable for TrampolineOnionPacket {
1961 fn read<R: LengthRead>(r: &mut R) -> Result<Self, DecodeError> {
1962 let version = Readable::read(r)?;
1963 let public_key = Readable::read(r)?;
1964
1965 let hop_data_len = r.total_bytes().saturating_sub(66); let mut rd = FixedLengthReader::new(r, hop_data_len);
1967 let hop_data = WithoutLength::<Vec<u8>>::read(&mut rd)?.0;
1968
1969 let hmac = Readable::read(r)?;
1970
1971 Ok(TrampolineOnionPacket {
1972 version,
1973 public_key,
1974 hop_data,
1975 hmac,
1976 })
1977 }
1978}
1979
1980impl Debug for TrampolineOnionPacket {
1981 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1982 f.write_fmt(format_args!("TrampolineOnionPacket version {} with hmac {:?}", self.version, &self.hmac[..]))
1983 }
1984}
1985
1986#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1987pub(crate) struct OnionErrorPacket {
1988 pub(crate) data: Vec<u8>,
1991}
1992
1993impl fmt::Display for DecodeError {
1994 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1995 match *self {
1996 DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
1997 DecodeError::UnknownRequiredFeature => f.write_str("Unknown required feature preventing decode"),
1998 DecodeError::InvalidValue => f.write_str("Nonsense bytes didn't map to the type they were interpreted as"),
1999 DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
2000 DecodeError::BadLengthDescriptor => f.write_str("A length descriptor in the packet didn't describe the later data correctly"),
2001 DecodeError::Io(ref e) => fmt::Debug::fmt(e, f),
2002 DecodeError::UnsupportedCompression => f.write_str("We don't support receiving messages with zlib-compressed fields"),
2003 DecodeError::DangerousValue => f.write_str("Value would be dangerous to continue execution with"),
2004 }
2005 }
2006}
2007
2008impl From<io::Error> for DecodeError {
2009 fn from(e: io::Error) -> Self {
2010 if e.kind() == io::ErrorKind::UnexpectedEof {
2011 DecodeError::ShortRead
2012 } else {
2013 DecodeError::Io(e.kind())
2014 }
2015 }
2016}
2017
2018impl Writeable for AcceptChannel {
2019 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2020 self.common_fields.temporary_channel_id.write(w)?;
2021 self.common_fields.dust_limit_satoshis.write(w)?;
2022 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2023 self.channel_reserve_satoshis.write(w)?;
2024 self.common_fields.htlc_minimum_msat.write(w)?;
2025 self.common_fields.minimum_depth.write(w)?;
2026 self.common_fields.to_self_delay.write(w)?;
2027 self.common_fields.max_accepted_htlcs.write(w)?;
2028 self.common_fields.funding_pubkey.write(w)?;
2029 self.common_fields.revocation_basepoint.write(w)?;
2030 self.common_fields.payment_basepoint.write(w)?;
2031 self.common_fields.delayed_payment_basepoint.write(w)?;
2032 self.common_fields.htlc_basepoint.write(w)?;
2033 self.common_fields.first_per_commitment_point.write(w)?;
2034 #[cfg(not(taproot))]
2035 encode_tlv_stream!(w, {
2036 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2038 });
2039 #[cfg(taproot)]
2040 encode_tlv_stream!(w, {
2041 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2043 (4, self.next_local_nonce, option),
2044 });
2045 Ok(())
2046 }
2047}
2048
2049impl Readable for AcceptChannel {
2050 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2051 let temporary_channel_id: ChannelId = Readable::read(r)?;
2052 let dust_limit_satoshis: u64 = Readable::read(r)?;
2053 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2054 let channel_reserve_satoshis: u64 = Readable::read(r)?;
2055 let htlc_minimum_msat: u64 = Readable::read(r)?;
2056 let minimum_depth: u32 = Readable::read(r)?;
2057 let to_self_delay: u16 = Readable::read(r)?;
2058 let max_accepted_htlcs: u16 = Readable::read(r)?;
2059 let funding_pubkey: PublicKey = Readable::read(r)?;
2060 let revocation_basepoint: PublicKey = Readable::read(r)?;
2061 let payment_basepoint: PublicKey = Readable::read(r)?;
2062 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2063 let htlc_basepoint: PublicKey = Readable::read(r)?;
2064 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2065
2066 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2067 let mut channel_type: Option<ChannelTypeFeatures> = None;
2068 #[cfg(not(taproot))]
2069 decode_tlv_stream!(r, {
2070 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2071 (1, channel_type, option),
2072 });
2073 #[cfg(taproot)]
2074 let mut next_local_nonce: Option<musig2::types::PublicNonce> = None;
2075 #[cfg(taproot)]
2076 decode_tlv_stream!(r, {
2077 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2078 (1, channel_type, option),
2079 (4, next_local_nonce, option),
2080 });
2081
2082 Ok(AcceptChannel {
2083 common_fields: CommonAcceptChannelFields {
2084 temporary_channel_id,
2085 dust_limit_satoshis,
2086 max_htlc_value_in_flight_msat,
2087 htlc_minimum_msat,
2088 minimum_depth,
2089 to_self_delay,
2090 max_accepted_htlcs,
2091 funding_pubkey,
2092 revocation_basepoint,
2093 payment_basepoint,
2094 delayed_payment_basepoint,
2095 htlc_basepoint,
2096 first_per_commitment_point,
2097 shutdown_scriptpubkey,
2098 channel_type,
2099 },
2100 channel_reserve_satoshis,
2101 #[cfg(taproot)]
2102 next_local_nonce,
2103 })
2104 }
2105}
2106
2107impl Writeable for AcceptChannelV2 {
2108 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2109 self.common_fields.temporary_channel_id.write(w)?;
2110 self.funding_satoshis.write(w)?;
2111 self.common_fields.dust_limit_satoshis.write(w)?;
2112 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2113 self.common_fields.htlc_minimum_msat.write(w)?;
2114 self.common_fields.minimum_depth.write(w)?;
2115 self.common_fields.to_self_delay.write(w)?;
2116 self.common_fields.max_accepted_htlcs.write(w)?;
2117 self.common_fields.funding_pubkey.write(w)?;
2118 self.common_fields.revocation_basepoint.write(w)?;
2119 self.common_fields.payment_basepoint.write(w)?;
2120 self.common_fields.delayed_payment_basepoint.write(w)?;
2121 self.common_fields.htlc_basepoint.write(w)?;
2122 self.common_fields.first_per_commitment_point.write(w)?;
2123 self.second_per_commitment_point.write(w)?;
2124
2125 encode_tlv_stream!(w, {
2126 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2128 (2, self.require_confirmed_inputs, option),
2129 });
2130 Ok(())
2131 }
2132}
2133
2134impl Readable for AcceptChannelV2 {
2135 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2136 let temporary_channel_id: ChannelId = Readable::read(r)?;
2137 let funding_satoshis: u64 = Readable::read(r)?;
2138 let dust_limit_satoshis: u64 = Readable::read(r)?;
2139 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2140 let htlc_minimum_msat: u64 = Readable::read(r)?;
2141 let minimum_depth: u32 = Readable::read(r)?;
2142 let to_self_delay: u16 = Readable::read(r)?;
2143 let max_accepted_htlcs: u16 = Readable::read(r)?;
2144 let funding_pubkey: PublicKey = Readable::read(r)?;
2145 let revocation_basepoint: PublicKey = Readable::read(r)?;
2146 let payment_basepoint: PublicKey = Readable::read(r)?;
2147 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2148 let htlc_basepoint: PublicKey = Readable::read(r)?;
2149 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2150 let second_per_commitment_point: PublicKey = Readable::read(r)?;
2151
2152 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2153 let mut channel_type: Option<ChannelTypeFeatures> = None;
2154 let mut require_confirmed_inputs: Option<()> = None;
2155 decode_tlv_stream!(r, {
2156 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2157 (1, channel_type, option),
2158 (2, require_confirmed_inputs, option),
2159 });
2160
2161 Ok(AcceptChannelV2 {
2162 common_fields: CommonAcceptChannelFields {
2163 temporary_channel_id,
2164 dust_limit_satoshis,
2165 max_htlc_value_in_flight_msat,
2166 htlc_minimum_msat,
2167 minimum_depth,
2168 to_self_delay,
2169 max_accepted_htlcs,
2170 funding_pubkey,
2171 revocation_basepoint,
2172 payment_basepoint,
2173 delayed_payment_basepoint,
2174 htlc_basepoint,
2175 first_per_commitment_point,
2176 shutdown_scriptpubkey,
2177 channel_type,
2178 },
2179 funding_satoshis,
2180 second_per_commitment_point,
2181 require_confirmed_inputs,
2182 })
2183 }
2184}
2185
2186impl_writeable_msg!(Stfu, {
2187 channel_id,
2188 initiator,
2189}, {});
2190
2191impl_writeable_msg!(SpliceInit, {
2192 channel_id,
2193 funding_contribution_satoshis,
2194 funding_feerate_perkw,
2195 locktime,
2196 funding_pubkey,
2197}, {
2198 (2, require_confirmed_inputs, option), });
2200
2201impl_writeable_msg!(SpliceAck, {
2202 channel_id,
2203 funding_contribution_satoshis,
2204 funding_pubkey,
2205}, {
2206 (2, require_confirmed_inputs, option), });
2208
2209impl_writeable_msg!(SpliceLocked, {
2210 channel_id,
2211 splice_txid,
2212}, {});
2213
2214impl_writeable_msg!(TxAddInput, {
2215 channel_id,
2216 serial_id,
2217 prevtx,
2218 prevtx_out,
2219 sequence,
2220}, {
2221 (0, shared_input_txid, option), });
2223
2224impl_writeable_msg!(TxAddOutput, {
2225 channel_id,
2226 serial_id,
2227 sats,
2228 script,
2229}, {});
2230
2231impl_writeable_msg!(TxRemoveInput, {
2232 channel_id,
2233 serial_id,
2234}, {});
2235
2236impl_writeable_msg!(TxRemoveOutput, {
2237 channel_id,
2238 serial_id,
2239}, {});
2240
2241impl_writeable_msg!(TxComplete, {
2242 channel_id,
2243}, {});
2244
2245impl_writeable_msg!(TxSignatures, {
2246 channel_id,
2247 tx_hash,
2248 witnesses,
2249}, {
2250 (0, shared_input_signature, option), });
2252
2253impl_writeable_msg!(TxInitRbf, {
2254 channel_id,
2255 locktime,
2256 feerate_sat_per_1000_weight,
2257}, {
2258 (0, funding_output_contribution, option),
2259});
2260
2261impl_writeable_msg!(TxAckRbf, {
2262 channel_id,
2263}, {
2264 (0, funding_output_contribution, option),
2265});
2266
2267impl_writeable_msg!(TxAbort, {
2268 channel_id,
2269 data,
2270}, {});
2271
2272impl_writeable_msg!(AnnouncementSignatures, {
2273 channel_id,
2274 short_channel_id,
2275 node_signature,
2276 bitcoin_signature
2277}, {});
2278
2279impl_writeable_msg!(ChannelReestablish, {
2280 channel_id,
2281 next_local_commitment_number,
2282 next_remote_commitment_number,
2283 your_last_per_commitment_secret,
2284 my_current_per_commitment_point,
2285}, {
2286 (0, next_funding_txid, option),
2287});
2288
2289impl_writeable_msg!(ClosingSigned,
2290 { channel_id, fee_satoshis, signature },
2291 { (1, fee_range, option) }
2292);
2293
2294impl_writeable!(ClosingSignedFeeRange, {
2295 min_fee_satoshis,
2296 max_fee_satoshis
2297});
2298
2299impl_writeable_msg!(CommitmentSignedBatch, {
2300 batch_size,
2301 funding_txid,
2302}, {});
2303
2304#[cfg(not(taproot))]
2305impl_writeable_msg!(CommitmentSigned, {
2306 channel_id,
2307 signature,
2308 htlc_signatures
2309}, {
2310 (0, batch, option),
2311});
2312
2313#[cfg(taproot)]
2314impl_writeable_msg!(CommitmentSigned, {
2315 channel_id,
2316 signature,
2317 htlc_signatures
2318}, {
2319 (0, batch, option),
2320 (2, partial_signature_with_nonce, option),
2321});
2322
2323impl_writeable!(DecodedOnionErrorPacket, {
2324 hmac,
2325 failuremsg,
2326 pad
2327});
2328
2329#[cfg(not(taproot))]
2330impl_writeable_msg!(FundingCreated, {
2331 temporary_channel_id,
2332 funding_txid,
2333 funding_output_index,
2334 signature
2335}, {});
2336#[cfg(taproot)]
2337impl_writeable_msg!(FundingCreated, {
2338 temporary_channel_id,
2339 funding_txid,
2340 funding_output_index,
2341 signature
2342}, {
2343 (2, partial_signature_with_nonce, option),
2344 (4, next_local_nonce, option)
2345});
2346
2347#[cfg(not(taproot))]
2348impl_writeable_msg!(FundingSigned, {
2349 channel_id,
2350 signature
2351}, {});
2352
2353#[cfg(taproot)]
2354impl_writeable_msg!(FundingSigned, {
2355 channel_id,
2356 signature
2357}, {
2358 (2, partial_signature_with_nonce, option)
2359});
2360
2361impl_writeable_msg!(ChannelReady, {
2362 channel_id,
2363 next_per_commitment_point,
2364}, {
2365 (1, short_channel_id_alias, option),
2366});
2367
2368pub(crate) fn write_features_up_to_13<W: Writer>(w: &mut W, le_flags: &[u8]) -> Result<(), io::Error> {
2369 let len = core::cmp::min(2, le_flags.len());
2370 (len as u16).write(w)?;
2371 for i in (0..len).rev() {
2372 if i == 0 {
2373 le_flags[i].write(w)?;
2374 } else {
2375 (le_flags[i] & 0b00_11_11_11).write(w)?;
2378 }
2379 }
2380 Ok(())
2381}
2382
2383impl Writeable for Init {
2384 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2385 write_features_up_to_13(w, self.features.le_flags())?;
2388 self.features.write(w)?;
2389 encode_tlv_stream!(w, {
2390 (1, self.networks.as_ref().map(|n| WithoutLength(n)), option),
2391 (3, self.remote_network_address, option),
2392 });
2393 Ok(())
2394 }
2395}
2396
2397impl Readable for Init {
2398 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2399 let global_features: InitFeatures = Readable::read(r)?;
2400 let features: InitFeatures = Readable::read(r)?;
2401 let mut remote_network_address: Option<SocketAddress> = None;
2402 let mut networks: Option<WithoutLength<Vec<ChainHash>>> = None;
2403 decode_tlv_stream!(r, {
2404 (1, networks, option),
2405 (3, remote_network_address, option)
2406 });
2407 Ok(Init {
2408 features: features | global_features,
2409 networks: networks.map(|n| n.0),
2410 remote_network_address,
2411 })
2412 }
2413}
2414
2415impl Writeable for OpenChannel {
2416 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2417 self.common_fields.chain_hash.write(w)?;
2418 self.common_fields.temporary_channel_id.write(w)?;
2419 self.common_fields.funding_satoshis.write(w)?;
2420 self.push_msat.write(w)?;
2421 self.common_fields.dust_limit_satoshis.write(w)?;
2422 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2423 self.channel_reserve_satoshis.write(w)?;
2424 self.common_fields.htlc_minimum_msat.write(w)?;
2425 self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
2426 self.common_fields.to_self_delay.write(w)?;
2427 self.common_fields.max_accepted_htlcs.write(w)?;
2428 self.common_fields.funding_pubkey.write(w)?;
2429 self.common_fields.revocation_basepoint.write(w)?;
2430 self.common_fields.payment_basepoint.write(w)?;
2431 self.common_fields.delayed_payment_basepoint.write(w)?;
2432 self.common_fields.htlc_basepoint.write(w)?;
2433 self.common_fields.first_per_commitment_point.write(w)?;
2434 self.common_fields.channel_flags.write(w)?;
2435 encode_tlv_stream!(w, {
2436 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2438 });
2439 Ok(())
2440 }
2441}
2442
2443impl Readable for OpenChannel {
2444 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2445 let chain_hash: ChainHash = Readable::read(r)?;
2446 let temporary_channel_id: ChannelId = Readable::read(r)?;
2447 let funding_satoshis: u64 = Readable::read(r)?;
2448 let push_msat: u64 = Readable::read(r)?;
2449 let dust_limit_satoshis: u64 = Readable::read(r)?;
2450 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2451 let channel_reserve_satoshis: u64 = Readable::read(r)?;
2452 let htlc_minimum_msat: u64 = Readable::read(r)?;
2453 let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
2454 let to_self_delay: u16 = Readable::read(r)?;
2455 let max_accepted_htlcs: u16 = Readable::read(r)?;
2456 let funding_pubkey: PublicKey = Readable::read(r)?;
2457 let revocation_basepoint: PublicKey = Readable::read(r)?;
2458 let payment_basepoint: PublicKey = Readable::read(r)?;
2459 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2460 let htlc_basepoint: PublicKey = Readable::read(r)?;
2461 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2462 let channel_flags: u8 = Readable::read(r)?;
2463
2464 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2465 let mut channel_type: Option<ChannelTypeFeatures> = None;
2466 decode_tlv_stream!(r, {
2467 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2468 (1, channel_type, option),
2469 });
2470 Ok(OpenChannel {
2471 common_fields: CommonOpenChannelFields {
2472 chain_hash,
2473 temporary_channel_id,
2474 funding_satoshis,
2475 dust_limit_satoshis,
2476 max_htlc_value_in_flight_msat,
2477 htlc_minimum_msat,
2478 commitment_feerate_sat_per_1000_weight,
2479 to_self_delay,
2480 max_accepted_htlcs,
2481 funding_pubkey,
2482 revocation_basepoint,
2483 payment_basepoint,
2484 delayed_payment_basepoint,
2485 htlc_basepoint,
2486 first_per_commitment_point,
2487 channel_flags,
2488 shutdown_scriptpubkey,
2489 channel_type,
2490 },
2491 push_msat,
2492 channel_reserve_satoshis,
2493 })
2494 }
2495}
2496
2497impl Writeable for OpenChannelV2 {
2498 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2499 self.common_fields.chain_hash.write(w)?;
2500 self.common_fields.temporary_channel_id.write(w)?;
2501 self.funding_feerate_sat_per_1000_weight.write(w)?;
2502 self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
2503 self.common_fields.funding_satoshis.write(w)?;
2504 self.common_fields.dust_limit_satoshis.write(w)?;
2505 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2506 self.common_fields.htlc_minimum_msat.write(w)?;
2507 self.common_fields.to_self_delay.write(w)?;
2508 self.common_fields.max_accepted_htlcs.write(w)?;
2509 self.locktime.write(w)?;
2510 self.common_fields.funding_pubkey.write(w)?;
2511 self.common_fields.revocation_basepoint.write(w)?;
2512 self.common_fields.payment_basepoint.write(w)?;
2513 self.common_fields.delayed_payment_basepoint.write(w)?;
2514 self.common_fields.htlc_basepoint.write(w)?;
2515 self.common_fields.first_per_commitment_point.write(w)?;
2516 self.second_per_commitment_point.write(w)?;
2517 self.common_fields.channel_flags.write(w)?;
2518 encode_tlv_stream!(w, {
2519 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2521 (2, self.require_confirmed_inputs, option),
2522 });
2523 Ok(())
2524 }
2525}
2526
2527impl Readable for OpenChannelV2 {
2528 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2529 let chain_hash: ChainHash = Readable::read(r)?;
2530 let temporary_channel_id: ChannelId = Readable::read(r)?;
2531 let funding_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
2532 let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
2533 let funding_satoshis: u64 = Readable::read(r)?;
2534 let dust_limit_satoshis: u64 = Readable::read(r)?;
2535 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2536 let htlc_minimum_msat: u64 = Readable::read(r)?;
2537 let to_self_delay: u16 = Readable::read(r)?;
2538 let max_accepted_htlcs: u16 = Readable::read(r)?;
2539 let locktime: u32 = Readable::read(r)?;
2540 let funding_pubkey: PublicKey = Readable::read(r)?;
2541 let revocation_basepoint: PublicKey = Readable::read(r)?;
2542 let payment_basepoint: PublicKey = Readable::read(r)?;
2543 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2544 let htlc_basepoint: PublicKey = Readable::read(r)?;
2545 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2546 let second_per_commitment_point: PublicKey = Readable::read(r)?;
2547 let channel_flags: u8 = Readable::read(r)?;
2548
2549 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2550 let mut channel_type: Option<ChannelTypeFeatures> = None;
2551 let mut require_confirmed_inputs: Option<()> = None;
2552 decode_tlv_stream!(r, {
2553 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2554 (1, channel_type, option),
2555 (2, require_confirmed_inputs, option),
2556 });
2557 Ok(OpenChannelV2 {
2558 common_fields: CommonOpenChannelFields {
2559 chain_hash,
2560 temporary_channel_id,
2561 funding_satoshis,
2562 dust_limit_satoshis,
2563 max_htlc_value_in_flight_msat,
2564 htlc_minimum_msat,
2565 commitment_feerate_sat_per_1000_weight,
2566 to_self_delay,
2567 max_accepted_htlcs,
2568 funding_pubkey,
2569 revocation_basepoint,
2570 payment_basepoint,
2571 delayed_payment_basepoint,
2572 htlc_basepoint,
2573 first_per_commitment_point,
2574 channel_flags,
2575 shutdown_scriptpubkey,
2576 channel_type,
2577 },
2578 funding_feerate_sat_per_1000_weight,
2579 locktime,
2580 second_per_commitment_point,
2581 require_confirmed_inputs,
2582 })
2583 }
2584}
2585
2586#[cfg(not(taproot))]
2587impl_writeable_msg!(RevokeAndACK, {
2588 channel_id,
2589 per_commitment_secret,
2590 next_per_commitment_point
2591}, {});
2592
2593#[cfg(taproot)]
2594impl_writeable_msg!(RevokeAndACK, {
2595 channel_id,
2596 per_commitment_secret,
2597 next_per_commitment_point
2598}, {
2599 (4, next_local_nonce, option)
2600});
2601
2602impl_writeable_msg!(Shutdown, {
2603 channel_id,
2604 scriptpubkey
2605}, {});
2606
2607impl_writeable_msg!(UpdateFailHTLC, {
2608 channel_id,
2609 htlc_id,
2610 reason
2611}, {});
2612
2613impl_writeable_msg!(UpdateFailMalformedHTLC, {
2614 channel_id,
2615 htlc_id,
2616 sha256_of_onion,
2617 failure_code
2618}, {});
2619
2620impl_writeable_msg!(UpdateFee, {
2621 channel_id,
2622 feerate_per_kw
2623}, {});
2624
2625impl_writeable_msg!(UpdateFulfillHTLC, {
2626 channel_id,
2627 htlc_id,
2628 payment_preimage
2629}, {});
2630
2631impl_writeable!(OnionErrorPacket, {
2635 data
2636});
2637
2638impl Writeable for OnionPacket {
2642 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2643 self.version.write(w)?;
2644 match self.public_key {
2645 Ok(pubkey) => pubkey.write(w)?,
2646 Err(_) => [0u8;33].write(w)?,
2647 }
2648 w.write_all(&self.hop_data)?;
2649 self.hmac.write(w)?;
2650 Ok(())
2651 }
2652}
2653
2654impl Readable for OnionPacket {
2655 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2656 Ok(OnionPacket {
2657 version: Readable::read(r)?,
2658 public_key: {
2659 let mut buf = [0u8;33];
2660 r.read_exact(&mut buf)?;
2661 PublicKey::from_slice(&buf)
2662 },
2663 hop_data: Readable::read(r)?,
2664 hmac: Readable::read(r)?,
2665 })
2666 }
2667}
2668
2669impl_writeable_msg!(UpdateAddHTLC, {
2670 channel_id,
2671 htlc_id,
2672 amount_msat,
2673 payment_hash,
2674 cltv_expiry,
2675 onion_routing_packet,
2676}, {
2677 (0, blinding_point, option),
2678 (65537, skimmed_fee_msat, option)
2679});
2680
2681impl Readable for OnionMessage {
2682 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2683 let blinding_point: PublicKey = Readable::read(r)?;
2684 let len: u16 = Readable::read(r)?;
2685 let mut packet_reader = FixedLengthReader::new(r, len as u64);
2686 let onion_routing_packet: onion_message::packet::Packet =
2687 <onion_message::packet::Packet as LengthReadable>::read(&mut packet_reader)?;
2688 Ok(Self {
2689 blinding_point,
2690 onion_routing_packet,
2691 })
2692 }
2693}
2694
2695impl Writeable for OnionMessage {
2696 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2697 self.blinding_point.write(w)?;
2698 let onion_packet_len = self.onion_routing_packet.serialized_length();
2699 (onion_packet_len as u16).write(w)?;
2700 self.onion_routing_packet.write(w)?;
2701 Ok(())
2702 }
2703}
2704
2705impl Writeable for FinalOnionHopData {
2706 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2707 self.payment_secret.0.write(w)?;
2708 HighZeroBytesDroppedBigSize(self.total_msat).write(w)
2709 }
2710}
2711
2712impl Readable for FinalOnionHopData {
2713 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2714 let secret: [u8; 32] = Readable::read(r)?;
2715 let amt: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
2716 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
2717 }
2718}
2719
2720impl<'a> Writeable for OutboundOnionPayload<'a> {
2721 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2722 match self {
2723 Self::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } => {
2724 _encode_varint_length_prefixed_tlv!(w, {
2725 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
2726 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2727 (6, short_channel_id, required)
2728 });
2729 },
2730 Self::TrampolineEntrypoint {
2731 amt_to_forward, outgoing_cltv_value, ref multipath_trampoline_data,
2732 ref trampoline_packet
2733 } => {
2734 _encode_varint_length_prefixed_tlv!(w, {
2735 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
2736 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2737 (8, multipath_trampoline_data, option),
2738 (20, trampoline_packet, required)
2739 });
2740 },
2741 Self::Receive {
2742 ref payment_data, ref payment_metadata, ref keysend_preimage, sender_intended_htlc_amt_msat,
2743 cltv_expiry_height, ref custom_tlvs,
2744 } => {
2745 let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
2749 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> = custom_tlvs.iter().chain(keysend_tlv.iter()).collect();
2750 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
2751 _encode_varint_length_prefixed_tlv!(w, {
2752 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
2753 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
2754 (8, payment_data, option),
2755 (16, payment_metadata.map(|m| WithoutLength(m)), option)
2756 }, custom_tlvs.iter());
2757 },
2758 Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
2759 _encode_varint_length_prefixed_tlv!(w, {
2760 (10, **encrypted_tlvs, required_vec),
2761 (12, intro_node_blinding_point, option)
2762 });
2763 },
2764 Self::BlindedReceive {
2765 sender_intended_htlc_amt_msat, total_msat, cltv_expiry_height, encrypted_tlvs,
2766 intro_node_blinding_point, keysend_preimage, ref invoice_request, ref custom_tlvs,
2767 } => {
2768 let invoice_request_tlv = invoice_request.map(|invreq| (77_777, invreq.encode())); let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
2773 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> = custom_tlvs.iter()
2774 .chain(invoice_request_tlv.iter())
2775 .chain(keysend_tlv.iter())
2776 .collect();
2777 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
2778 _encode_varint_length_prefixed_tlv!(w, {
2779 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
2780 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
2781 (10, **encrypted_tlvs, required_vec),
2782 (12, intro_node_blinding_point, option),
2783 (18, HighZeroBytesDroppedBigSize(*total_msat), required)
2784 }, custom_tlvs.iter());
2785 },
2786 }
2787 Ok(())
2788 }
2789}
2790
2791impl<'a> Writeable for OutboundTrampolinePayload<'a> {
2792 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2793 match self {
2794 Self::Forward { amt_to_forward, outgoing_cltv_value, outgoing_node_id } => {
2795 _encode_varint_length_prefixed_tlv!(w, {
2796 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
2797 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2798 (14, outgoing_node_id, required)
2799 });
2800 },
2801 Self::LegacyBlindedPathEntry { amt_to_forward, outgoing_cltv_value, payment_paths, invoice_features } => {
2802 let mut blinded_path_serialization = [0u8; 2048]; let serialization_length = {
2804 let buffer_size = blinded_path_serialization.len();
2805 let mut blinded_path_slice = &mut blinded_path_serialization[..];
2806 for current_payment_path in payment_paths {
2807 current_payment_path.inner_blinded_path().write(&mut blinded_path_slice)?;
2808 current_payment_path.payinfo.write(&mut blinded_path_slice)?;
2809 }
2810 buffer_size - blinded_path_slice.len()
2811 };
2812 let blinded_path_serialization = &blinded_path_serialization[..serialization_length];
2813 _encode_varint_length_prefixed_tlv!(w, {
2814 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
2815 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
2816 (21, invoice_features.as_ref().map(|m| WithoutLength(m)), option),
2817 (22, WithoutLength(blinded_path_serialization), required)
2818 });
2819 },
2820 Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point} => {
2821 _encode_varint_length_prefixed_tlv!(w, {
2822 (10, **encrypted_tlvs, required_vec),
2823 (12, intro_node_blinding_point, option)
2824 });
2825 },
2826 Self::BlindedReceive { sender_intended_htlc_amt_msat, total_msat, cltv_expiry_height, encrypted_tlvs, intro_node_blinding_point, keysend_preimage, custom_tlvs } => {
2827 _encode_varint_length_prefixed_tlv!(w, {
2828 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
2829 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
2830 (10, **encrypted_tlvs, required_vec),
2831 (12, intro_node_blinding_point, option),
2832 (18, HighZeroBytesDroppedBigSize(*total_msat), required),
2833 (20, keysend_preimage, option)
2834 }, custom_tlvs.iter());
2835 }
2836 }
2837 Ok(())
2838 }
2839}
2840
2841
2842impl<NS: Deref> ReadableArgs<(Option<PublicKey>, NS)> for InboundOnionPayload where NS::Target: NodeSigner {
2843 fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
2844 let (update_add_blinding_point, node_signer) = args;
2845
2846 let mut amt = None;
2847 let mut cltv_value = None;
2848 let mut short_id: Option<u64> = None;
2849 let mut payment_data: Option<FinalOnionHopData> = None;
2850 let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
2851 let mut intro_node_blinding_point = None;
2852 let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
2853 let mut total_msat = None;
2854 let mut keysend_preimage: Option<PaymentPreimage> = None;
2855 let mut custom_tlvs = Vec::new();
2856
2857 let tlv_len = BigSize::read(r)?;
2858 let mut rd = FixedLengthReader::new(r, tlv_len.0);
2859 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
2860 (2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
2861 (4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
2862 (6, short_id, option),
2863 (8, payment_data, option),
2864 (10, encrypted_tlvs_opt, option),
2865 (12, intro_node_blinding_point, option),
2866 (16, payment_metadata, option),
2867 (18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
2868 (5482373484, keysend_preimage, option)
2870 }, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
2871 if msg_type < 1 << 16 { return Ok(false) }
2872 let mut value = Vec::new();
2873 msg_reader.read_to_limit(&mut value, u64::MAX)?;
2874 custom_tlvs.push((msg_type, value));
2875 Ok(true)
2876 });
2877
2878 if amt.unwrap_or(0) > MAX_VALUE_MSAT { return Err(DecodeError::InvalidValue) }
2879 if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
2880 return Err(DecodeError::InvalidValue)
2881 }
2882
2883 if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
2884 if short_id.is_some() || payment_data.is_some() || payment_metadata.is_some() {
2885 return Err(DecodeError::InvalidValue)
2886 }
2887 let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
2888 let enc_tlvs_ss = node_signer.ecdh(Recipient::Node, &blinding_point, None)
2889 .map_err(|_| DecodeError::InvalidValue)?;
2890 let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
2891 let mut s = Cursor::new(&enc_tlvs);
2892 let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
2893 match ChaChaPolyReadAdapter::read(&mut reader, rho)? {
2894 ChaChaPolyReadAdapter { readable: BlindedPaymentTlvs::Forward(ForwardTlvs {
2895 short_channel_id, payment_relay, payment_constraints, features, next_blinding_override
2896 })} => {
2897 if amt.is_some() || cltv_value.is_some() || total_msat.is_some() ||
2898 keysend_preimage.is_some()
2899 {
2900 return Err(DecodeError::InvalidValue)
2901 }
2902 Ok(Self::BlindedForward {
2903 short_channel_id,
2904 payment_relay,
2905 payment_constraints,
2906 features,
2907 intro_node_blinding_point,
2908 next_blinding_override,
2909 })
2910 },
2911 ChaChaPolyReadAdapter { readable: BlindedPaymentTlvs::Receive(receive_tlvs) } => {
2912 let ReceiveTlvs { tlvs, authentication: (hmac, nonce) } = receive_tlvs;
2913 let expanded_key = node_signer.get_inbound_payment_key();
2914 if tlvs.verify_for_offer_payment(hmac, nonce, &expanded_key).is_err() {
2915 return Err(DecodeError::InvalidValue);
2916 }
2917
2918 let UnauthenticatedReceiveTlvs {
2919 payment_secret, payment_constraints, payment_context,
2920 } = tlvs;
2921 if total_msat.unwrap_or(0) > MAX_VALUE_MSAT { return Err(DecodeError::InvalidValue) }
2922 Ok(Self::BlindedReceive {
2923 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
2924 total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
2925 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
2926 payment_secret,
2927 payment_constraints,
2928 payment_context,
2929 intro_node_blinding_point,
2930 keysend_preimage,
2931 custom_tlvs,
2932 })
2933 },
2934 }
2935 } else if let Some(short_channel_id) = short_id {
2936 if payment_data.is_some() || payment_metadata.is_some() || encrypted_tlvs_opt.is_some() ||
2937 total_msat.is_some()
2938 { return Err(DecodeError::InvalidValue) }
2939 Ok(Self::Forward {
2940 short_channel_id,
2941 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
2942 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
2943 })
2944 } else {
2945 if encrypted_tlvs_opt.is_some() || total_msat.is_some() {
2946 return Err(DecodeError::InvalidValue)
2947 }
2948 if let Some(data) = &payment_data {
2949 if data.total_msat > MAX_VALUE_MSAT {
2950 return Err(DecodeError::InvalidValue);
2951 }
2952 }
2953 Ok(Self::Receive {
2954 payment_data,
2955 payment_metadata: payment_metadata.map(|w| w.0),
2956 keysend_preimage,
2957 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
2958 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
2959 custom_tlvs,
2960 })
2961 }
2962 }
2963}
2964
2965impl Writeable for Ping {
2966 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2967 self.ponglen.write(w)?;
2968 vec![0u8; self.byteslen as usize].write(w)?; Ok(())
2970 }
2971}
2972
2973impl Readable for Ping {
2974 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2975 Ok(Ping {
2976 ponglen: Readable::read(r)?,
2977 byteslen: {
2978 let byteslen = Readable::read(r)?;
2979 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
2980 byteslen
2981 }
2982 })
2983 }
2984}
2985
2986impl Writeable for Pong {
2987 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2988 vec![0u8; self.byteslen as usize].write(w)?; Ok(())
2990 }
2991}
2992
2993impl Readable for Pong {
2994 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
2995 Ok(Pong {
2996 byteslen: {
2997 let byteslen = Readable::read(r)?;
2998 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
2999 byteslen
3000 }
3001 })
3002 }
3003}
3004
3005impl Writeable for UnsignedChannelAnnouncement {
3006 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3007 self.features.write(w)?;
3008 self.chain_hash.write(w)?;
3009 self.short_channel_id.write(w)?;
3010 self.node_id_1.write(w)?;
3011 self.node_id_2.write(w)?;
3012 self.bitcoin_key_1.write(w)?;
3013 self.bitcoin_key_2.write(w)?;
3014 w.write_all(&self.excess_data[..])?;
3015 Ok(())
3016 }
3017}
3018
3019impl Readable for UnsignedChannelAnnouncement {
3020 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3021 Ok(Self {
3022 features: Readable::read(r)?,
3023 chain_hash: Readable::read(r)?,
3024 short_channel_id: Readable::read(r)?,
3025 node_id_1: Readable::read(r)?,
3026 node_id_2: Readable::read(r)?,
3027 bitcoin_key_1: Readable::read(r)?,
3028 bitcoin_key_2: Readable::read(r)?,
3029 excess_data: read_to_end(r)?,
3030 })
3031 }
3032}
3033
3034impl_writeable!(ChannelAnnouncement, {
3035 node_signature_1,
3036 node_signature_2,
3037 bitcoin_signature_1,
3038 bitcoin_signature_2,
3039 contents
3040});
3041
3042impl Writeable for UnsignedChannelUpdate {
3043 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3044 self.chain_hash.write(w)?;
3045 self.short_channel_id.write(w)?;
3046 self.timestamp.write(w)?;
3047 (self.message_flags | 1).write(w)?;
3050 self.channel_flags.write(w)?;
3051 self.cltv_expiry_delta.write(w)?;
3052 self.htlc_minimum_msat.write(w)?;
3053 self.fee_base_msat.write(w)?;
3054 self.fee_proportional_millionths.write(w)?;
3055 self.htlc_maximum_msat.write(w)?;
3056 w.write_all(&self.excess_data[..])?;
3057 Ok(())
3058 }
3059}
3060
3061impl Readable for UnsignedChannelUpdate {
3062 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3063 let res = Self {
3064 chain_hash: Readable::read(r)?,
3065 short_channel_id: Readable::read(r)?,
3066 timestamp: Readable::read(r)?,
3067 message_flags: Readable::read(r)?,
3068 channel_flags: Readable::read(r)?,
3069 cltv_expiry_delta: Readable::read(r)?,
3070 htlc_minimum_msat: Readable::read(r)?,
3071 fee_base_msat: Readable::read(r)?,
3072 fee_proportional_millionths: Readable::read(r)?,
3073 htlc_maximum_msat: Readable::read(r)?,
3074 excess_data: read_to_end(r)?,
3075 };
3076 if res.message_flags & 1 != 1 {
3077 Err(DecodeError::InvalidValue)
3080 } else {
3081 Ok(res)
3082 }
3083 }
3084}
3085
3086impl_writeable!(ChannelUpdate, {
3087 signature,
3088 contents
3089});
3090
3091impl Writeable for ErrorMessage {
3092 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3093 self.channel_id.write(w)?;
3094 (self.data.len() as u16).write(w)?;
3095 w.write_all(self.data.as_bytes())?;
3096 Ok(())
3097 }
3098}
3099
3100impl Readable for ErrorMessage {
3101 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3102 Ok(Self {
3103 channel_id: Readable::read(r)?,
3104 data: {
3105 let sz: usize = <u16 as Readable>::read(r)? as usize;
3106 let mut data = Vec::with_capacity(sz);
3107 data.resize(sz, 0);
3108 r.read_exact(&mut data)?;
3109 match String::from_utf8(data) {
3110 Ok(s) => s,
3111 Err(_) => return Err(DecodeError::InvalidValue),
3112 }
3113 }
3114 })
3115 }
3116}
3117
3118impl Writeable for WarningMessage {
3119 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3120 self.channel_id.write(w)?;
3121 (self.data.len() as u16).write(w)?;
3122 w.write_all(self.data.as_bytes())?;
3123 Ok(())
3124 }
3125}
3126
3127impl Readable for WarningMessage {
3128 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3129 Ok(Self {
3130 channel_id: Readable::read(r)?,
3131 data: {
3132 let sz: usize = <u16 as Readable>::read(r)? as usize;
3133 let mut data = Vec::with_capacity(sz);
3134 data.resize(sz, 0);
3135 r.read_exact(&mut data)?;
3136 match String::from_utf8(data) {
3137 Ok(s) => s,
3138 Err(_) => return Err(DecodeError::InvalidValue),
3139 }
3140 }
3141 })
3142 }
3143}
3144
3145impl Writeable for UnsignedNodeAnnouncement {
3146 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3147 self.features.write(w)?;
3148 self.timestamp.write(w)?;
3149 self.node_id.write(w)?;
3150 w.write_all(&self.rgb)?;
3151 self.alias.write(w)?;
3152
3153 let mut addr_len = 0;
3154 for addr in self.addresses.iter() {
3155 addr_len += 1 + addr.len();
3156 }
3157 (addr_len + self.excess_address_data.len() as u16).write(w)?;
3158 for addr in self.addresses.iter() {
3159 addr.write(w)?;
3160 }
3161 w.write_all(&self.excess_address_data[..])?;
3162 w.write_all(&self.excess_data[..])?;
3163 Ok(())
3164 }
3165}
3166
3167impl Readable for UnsignedNodeAnnouncement {
3168 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3169 let features: NodeFeatures = Readable::read(r)?;
3170 let timestamp: u32 = Readable::read(r)?;
3171 let node_id: NodeId = Readable::read(r)?;
3172 let mut rgb = [0; 3];
3173 r.read_exact(&mut rgb)?;
3174 let alias: NodeAlias = Readable::read(r)?;
3175
3176 let addr_len: u16 = Readable::read(r)?;
3177 let mut addresses: Vec<SocketAddress> = Vec::new();
3178 let mut addr_readpos = 0;
3179 let mut excess = false;
3180 let mut excess_byte = 0;
3181 loop {
3182 if addr_len <= addr_readpos { break; }
3183 match Readable::read(r) {
3184 Ok(Ok(addr)) => {
3185 if addr_len < addr_readpos + 1 + addr.len() {
3186 return Err(DecodeError::BadLengthDescriptor);
3187 }
3188 addr_readpos += (1 + addr.len()) as u16;
3189 addresses.push(addr);
3190 },
3191 Ok(Err(unknown_descriptor)) => {
3192 excess = true;
3193 excess_byte = unknown_descriptor;
3194 break;
3195 },
3196 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
3197 Err(e) => return Err(e),
3198 }
3199 }
3200
3201 let mut excess_data = vec![];
3202 let excess_address_data = if addr_readpos < addr_len {
3203 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
3204 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
3205 if excess {
3206 excess_address_data[0] = excess_byte;
3207 }
3208 excess_address_data
3209 } else {
3210 if excess {
3211 excess_data.push(excess_byte);
3212 }
3213 Vec::new()
3214 };
3215 excess_data.extend(read_to_end(r)?.iter());
3216 Ok(UnsignedNodeAnnouncement {
3217 features,
3218 timestamp,
3219 node_id,
3220 rgb,
3221 alias,
3222 addresses,
3223 excess_address_data,
3224 excess_data,
3225 })
3226 }
3227}
3228
3229impl_writeable!(NodeAnnouncement, {
3230 signature,
3231 contents
3232});
3233
3234impl Readable for QueryShortChannelIds {
3235 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3236 let chain_hash: ChainHash = Readable::read(r)?;
3237
3238 let encoding_len: u16 = Readable::read(r)?;
3239 let encoding_type: u8 = Readable::read(r)?;
3240
3241 if encoding_type != EncodingType::Uncompressed as u8 {
3244 return Err(DecodeError::UnsupportedCompression);
3245 }
3246
3247 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
3250 return Err(DecodeError::InvalidValue);
3251 }
3252
3253 let short_channel_id_count: u16 = (encoding_len - 1)/8;
3256 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
3257 for _ in 0..short_channel_id_count {
3258 short_channel_ids.push(Readable::read(r)?);
3259 }
3260
3261 Ok(QueryShortChannelIds {
3262 chain_hash,
3263 short_channel_ids,
3264 })
3265 }
3266}
3267
3268impl Writeable for QueryShortChannelIds {
3269 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3270 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
3272
3273 self.chain_hash.write(w)?;
3274 encoding_len.write(w)?;
3275
3276 (EncodingType::Uncompressed as u8).write(w)?;
3278
3279 for scid in self.short_channel_ids.iter() {
3280 scid.write(w)?;
3281 }
3282
3283 Ok(())
3284 }
3285}
3286
3287impl_writeable_msg!(ReplyShortChannelIdsEnd, {
3288 chain_hash,
3289 full_information,
3290}, {});
3291
3292impl QueryChannelRange {
3293 pub fn end_blocknum(&self) -> u32 {
3297 match self.first_blocknum.checked_add(self.number_of_blocks) {
3298 Some(block) => block,
3299 None => u32::max_value(),
3300 }
3301 }
3302}
3303
3304impl_writeable_msg!(QueryChannelRange, {
3305 chain_hash,
3306 first_blocknum,
3307 number_of_blocks
3308}, {});
3309
3310impl Readable for ReplyChannelRange {
3311 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3312 let chain_hash: ChainHash = Readable::read(r)?;
3313 let first_blocknum: u32 = Readable::read(r)?;
3314 let number_of_blocks: u32 = Readable::read(r)?;
3315 let sync_complete: bool = Readable::read(r)?;
3316
3317 let encoding_len: u16 = Readable::read(r)?;
3318 let encoding_type: u8 = Readable::read(r)?;
3319
3320 if encoding_type != EncodingType::Uncompressed as u8 {
3323 return Err(DecodeError::UnsupportedCompression);
3324 }
3325
3326 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
3329 return Err(DecodeError::InvalidValue);
3330 }
3331
3332 let short_channel_id_count: u16 = (encoding_len - 1)/8;
3335 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
3336 for _ in 0..short_channel_id_count {
3337 short_channel_ids.push(Readable::read(r)?);
3338 }
3339
3340 Ok(ReplyChannelRange {
3341 chain_hash,
3342 first_blocknum,
3343 number_of_blocks,
3344 sync_complete,
3345 short_channel_ids
3346 })
3347 }
3348}
3349
3350impl Writeable for ReplyChannelRange {
3351 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3352 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
3353 self.chain_hash.write(w)?;
3354 self.first_blocknum.write(w)?;
3355 self.number_of_blocks.write(w)?;
3356 self.sync_complete.write(w)?;
3357
3358 encoding_len.write(w)?;
3359 (EncodingType::Uncompressed as u8).write(w)?;
3360 for scid in self.short_channel_ids.iter() {
3361 scid.write(w)?;
3362 }
3363
3364 Ok(())
3365 }
3366}
3367
3368impl_writeable_msg!(GossipTimestampFilter, {
3369 chain_hash,
3370 first_timestamp,
3371 timestamp_range,
3372}, {});
3373
3374#[cfg(test)]
3375mod tests {
3376 use bitcoin::{Amount, Transaction, TxIn, ScriptBuf, Sequence, Witness, TxOut};
3377 use bitcoin::hex::DisplayHex;
3378 use crate::ln::types::ChannelId;
3379 use crate::types::payment::{PaymentPreimage, PaymentHash, PaymentSecret};
3380 use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
3381 use crate::ln::msgs::{self, FinalOnionHopData, OnionErrorPacket, CommonOpenChannelFields, CommonAcceptChannelFields, OutboundTrampolinePayload, TrampolineOnionPacket};
3382 use crate::ln::msgs::SocketAddress;
3383 use crate::routing::gossip::{NodeAlias, NodeId};
3384 use crate::util::ser::{BigSize, FixedLengthReader, Hostname, LengthReadable, Readable, ReadableArgs, TransactionU16LenLimited, Writeable};
3385 use crate::util::test_utils;
3386
3387 use bitcoin::hex::FromHex;
3388 use bitcoin::address::Address;
3389 use bitcoin::network::Network;
3390 use bitcoin::constants::ChainHash;
3391 use bitcoin::script::Builder;
3392 use bitcoin::opcodes;
3393 use bitcoin::hash_types::Txid;
3394 use bitcoin::locktime::absolute::LockTime;
3395 use bitcoin::transaction::Version;
3396
3397 use bitcoin::secp256k1::{PublicKey,SecretKey};
3398 use bitcoin::secp256k1::{Secp256k1, Message};
3399
3400 use crate::io::{self, Cursor};
3401 use crate::prelude::*;
3402 use core::str::FromStr;
3403 use crate::chain::transaction::OutPoint;
3404
3405 #[cfg(feature = "std")]
3406 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
3407 use types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
3408 use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
3409 #[cfg(feature = "std")]
3410 use crate::ln::msgs::SocketAddressParseError;
3411
3412 #[test]
3413 fn encoding_channel_reestablish() {
3414 let public_key = {
3415 let secp_ctx = Secp256k1::new();
3416 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
3417 };
3418
3419 let cr = msgs::ChannelReestablish {
3420 channel_id: ChannelId::from_bytes([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]),
3421 next_local_commitment_number: 3,
3422 next_remote_commitment_number: 4,
3423 your_last_per_commitment_secret: [9;32],
3424 my_current_per_commitment_point: public_key,
3425 next_funding_txid: None,
3426 };
3427
3428 let encoded_value = cr.encode();
3429 assert_eq!(
3430 encoded_value,
3431 vec![
3432 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, ]
3438 );
3439 }
3440
3441 #[test]
3442 fn encoding_channel_reestablish_with_next_funding_txid() {
3443 let public_key = {
3444 let secp_ctx = Secp256k1::new();
3445 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap())
3446 };
3447
3448 let cr = msgs::ChannelReestablish {
3449 channel_id: ChannelId::from_bytes([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]),
3450 next_local_commitment_number: 3,
3451 next_remote_commitment_number: 4,
3452 your_last_per_commitment_secret: [9;32],
3453 my_current_per_commitment_point: public_key,
3454 next_funding_txid: Some(Txid::from_raw_hash(bitcoin::hashes::Hash::from_slice(&[
3455 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
3456 ]).unwrap())),
3457 };
3458
3459 let encoded_value = cr.encode();
3460 assert_eq!(
3461 encoded_value,
3462 vec![
3463 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, 0, 32, 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, ]
3472 );
3473 }
3474
3475 macro_rules! get_keys_from {
3476 ($slice: expr, $secp_ctx: expr) => {
3477 {
3478 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex($slice).unwrap()[..]).unwrap();
3479 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
3480 (privkey, pubkey)
3481 }
3482 }
3483 }
3484
3485 macro_rules! get_sig_on {
3486 ($privkey: expr, $ctx: expr, $string: expr) => {
3487 {
3488 let sighash = Message::from_digest_slice(&$string.into_bytes()[..]).unwrap();
3489 $ctx.sign_ecdsa(&sighash, &$privkey)
3490 }
3491 }
3492 }
3493
3494 #[test]
3495 fn encoding_announcement_signatures() {
3496 let secp_ctx = Secp256k1::new();
3497 let (privkey, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3498 let sig_1 = get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
3499 let sig_2 = get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
3500 let announcement_signatures = msgs::AnnouncementSignatures {
3501 channel_id: ChannelId::from_bytes([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]),
3502 short_channel_id: 2316138423780173,
3503 node_signature: sig_1,
3504 bitcoin_signature: sig_2,
3505 };
3506
3507 let encoded_value = announcement_signatures.encode();
3508 assert_eq!(encoded_value, <Vec<u8>>::from_hex("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
3509 }
3510
3511 fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
3512 let secp_ctx = Secp256k1::new();
3513 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3514 let (privkey_2, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3515 let (privkey_3, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3516 let (privkey_4, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3517 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3518 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
3519 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
3520 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
3521 let mut features = ChannelFeatures::empty();
3522 if unknown_features_bits {
3523 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
3524 }
3525 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
3526 features,
3527 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3528 short_channel_id: 2316138423780173,
3529 node_id_1: NodeId::from_pubkey(&pubkey_1),
3530 node_id_2: NodeId::from_pubkey(&pubkey_2),
3531 bitcoin_key_1: NodeId::from_pubkey(&pubkey_3),
3532 bitcoin_key_2: NodeId::from_pubkey(&pubkey_4),
3533 excess_data: if excess_data { vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40] } else { Vec::new() },
3534 };
3535 let channel_announcement = msgs::ChannelAnnouncement {
3536 node_signature_1: sig_1,
3537 node_signature_2: sig_2,
3538 bitcoin_signature_1: sig_3,
3539 bitcoin_signature_2: sig_4,
3540 contents: unsigned_channel_announcement,
3541 };
3542 let encoded_value = channel_announcement.encode();
3543 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
3544 if unknown_features_bits {
3545 target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
3546 } else {
3547 target_value.append(&mut <Vec<u8>>::from_hex("0000").unwrap());
3548 }
3549 target_value.append(&mut <Vec<u8>>::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
3550 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
3551 if excess_data {
3552 target_value.append(&mut <Vec<u8>>::from_hex("0a00001400001e000028").unwrap());
3553 }
3554 assert_eq!(encoded_value, target_value);
3555 }
3556
3557 #[test]
3558 fn encoding_channel_announcement() {
3559 do_encoding_channel_announcement(true, false);
3560 do_encoding_channel_announcement(false, true);
3561 do_encoding_channel_announcement(false, false);
3562 do_encoding_channel_announcement(true, true);
3563 }
3564
3565 fn do_encoding_node_announcement(unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool, hostname: bool, excess_address_data: bool, excess_data: bool) {
3566 let secp_ctx = Secp256k1::new();
3567 let (privkey_1, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3568 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3569 let features = if unknown_features_bits {
3570 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
3571 } else {
3572 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
3574 };
3575 let mut addresses = Vec::new();
3576 if ipv4 {
3577 addresses.push(SocketAddress::TcpIpV4 {
3578 addr: [255, 254, 253, 252],
3579 port: 9735
3580 });
3581 }
3582 if ipv6 {
3583 addresses.push(SocketAddress::TcpIpV6 {
3584 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3585 port: 9735
3586 });
3587 }
3588 if onionv2 {
3589 addresses.push(msgs::SocketAddress::OnionV2(
3590 [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]
3591 ));
3592 }
3593 if onionv3 {
3594 addresses.push(msgs::SocketAddress::OnionV3 {
3595 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],
3596 checksum: 32,
3597 version: 16,
3598 port: 9735
3599 });
3600 }
3601 if hostname {
3602 addresses.push(SocketAddress::Hostname {
3603 hostname: Hostname::try_from(String::from("host")).unwrap(),
3604 port: 9735,
3605 });
3606 }
3607 let mut addr_len = 0;
3608 for addr in &addresses {
3609 addr_len += addr.len() + 1;
3610 }
3611 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
3612 features,
3613 timestamp: 20190119,
3614 node_id: NodeId::from_pubkey(&pubkey_1),
3615 rgb: [32; 3],
3616 alias: NodeAlias([16;32]),
3617 addresses,
3618 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() },
3619 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() },
3620 };
3621 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
3622 let node_announcement = msgs::NodeAnnouncement {
3623 signature: sig_1,
3624 contents: unsigned_node_announcement,
3625 };
3626 let encoded_value = node_announcement.encode();
3627 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
3628 if unknown_features_bits {
3629 target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
3630 } else {
3631 target_value.append(&mut <Vec<u8>>::from_hex("000122").unwrap());
3632 }
3633 target_value.append(&mut <Vec<u8>>::from_hex("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
3634 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
3635 if ipv4 {
3636 target_value.append(&mut <Vec<u8>>::from_hex("01fffefdfc2607").unwrap());
3637 }
3638 if ipv6 {
3639 target_value.append(&mut <Vec<u8>>::from_hex("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap());
3640 }
3641 if onionv2 {
3642 target_value.append(&mut <Vec<u8>>::from_hex("03fffefdfcfbfaf9f8f7f62607").unwrap());
3643 }
3644 if onionv3 {
3645 target_value.append(&mut <Vec<u8>>::from_hex("04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607").unwrap());
3646 }
3647 if hostname {
3648 target_value.append(&mut <Vec<u8>>::from_hex("0504686f73742607").unwrap());
3649 }
3650 if excess_address_data {
3651 target_value.append(&mut <Vec<u8>>::from_hex("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
3652 }
3653 if excess_data {
3654 target_value.append(&mut <Vec<u8>>::from_hex("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
3655 }
3656 assert_eq!(encoded_value, target_value);
3657 }
3658
3659 #[test]
3660 fn encoding_node_announcement() {
3661 do_encoding_node_announcement(true, true, true, true, true, true, true, true);
3662 do_encoding_node_announcement(false, false, false, false, false, false, false, false);
3663 do_encoding_node_announcement(false, true, false, false, false, false, false, false);
3664 do_encoding_node_announcement(false, false, true, false, false, false, false, false);
3665 do_encoding_node_announcement(false, false, false, true, false, false, false, false);
3666 do_encoding_node_announcement(false, false, false, false, true, false, false, false);
3667 do_encoding_node_announcement(false, false, false, false, false, true, false, false);
3668 do_encoding_node_announcement(false, false, false, false, false, false, true, false);
3669 do_encoding_node_announcement(false, true, false, true, false, false, true, false);
3670 do_encoding_node_announcement(false, false, true, false, true, false, false, false);
3671 }
3672
3673 fn do_encoding_channel_update(direction: bool, disable: bool, excess_data: bool) {
3674 let secp_ctx = Secp256k1::new();
3675 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3676 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3677 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
3678 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3679 short_channel_id: 2316138423780173,
3680 timestamp: 20190119,
3681 message_flags: 1, channel_flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
3683 cltv_expiry_delta: 144,
3684 htlc_minimum_msat: 1000000,
3685 htlc_maximum_msat: 131355275467161,
3686 fee_base_msat: 10000,
3687 fee_proportional_millionths: 20,
3688 excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() }
3689 };
3690 let channel_update = msgs::ChannelUpdate {
3691 signature: sig_1,
3692 contents: unsigned_channel_update
3693 };
3694 let encoded_value = channel_update.encode();
3695 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
3696 target_value.append(&mut <Vec<u8>>::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
3697 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d013413a7").unwrap());
3698 target_value.append(&mut <Vec<u8>>::from_hex("01").unwrap());
3699 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
3700 if direction {
3701 let flag = target_value.last_mut().unwrap();
3702 *flag = 1;
3703 }
3704 if disable {
3705 let flag = target_value.last_mut().unwrap();
3706 *flag = *flag | 1 << 1;
3707 }
3708 target_value.append(&mut <Vec<u8>>::from_hex("009000000000000f42400000271000000014").unwrap());
3709 target_value.append(&mut <Vec<u8>>::from_hex("0000777788889999").unwrap());
3710 if excess_data {
3711 target_value.append(&mut <Vec<u8>>::from_hex("000000003b9aca00").unwrap());
3712 }
3713 assert_eq!(encoded_value, target_value);
3714 }
3715
3716 #[test]
3717 fn encoding_channel_update() {
3718 do_encoding_channel_update(false, false, false);
3719 do_encoding_channel_update(false, false, true);
3720 do_encoding_channel_update(true, false, false);
3721 do_encoding_channel_update(true, false, true);
3722 do_encoding_channel_update(false, true, false);
3723 do_encoding_channel_update(false, true, true);
3724 do_encoding_channel_update(true, true, false);
3725 do_encoding_channel_update(true, true, true);
3726 }
3727
3728 fn do_encoding_open_channel(random_bit: bool, shutdown: bool, incl_chan_type: bool) {
3729 let secp_ctx = Secp256k1::new();
3730 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3731 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3732 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3733 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3734 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3735 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3736 let open_channel = msgs::OpenChannel {
3737 common_fields: CommonOpenChannelFields {
3738 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3739 temporary_channel_id: ChannelId::from_bytes([2; 32]),
3740 funding_satoshis: 1311768467284833366,
3741 dust_limit_satoshis: 3608586615801332854,
3742 max_htlc_value_in_flight_msat: 8517154655701053848,
3743 htlc_minimum_msat: 2316138423780173,
3744 commitment_feerate_sat_per_1000_weight: 821716,
3745 to_self_delay: 49340,
3746 max_accepted_htlcs: 49340,
3747 funding_pubkey: pubkey_1,
3748 revocation_basepoint: pubkey_2,
3749 payment_basepoint: pubkey_3,
3750 delayed_payment_basepoint: pubkey_4,
3751 htlc_basepoint: pubkey_5,
3752 first_per_commitment_point: pubkey_6,
3753 channel_flags: if random_bit { 1 << 5 } else { 0 },
3754 shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3755 channel_type: if incl_chan_type { Some(ChannelTypeFeatures::empty()) } else { None },
3756 },
3757 push_msat: 2536655962884945560,
3758 channel_reserve_satoshis: 8665828695742877976,
3759 };
3760 let encoded_value = open_channel.encode();
3761 let mut target_value = Vec::new();
3762 target_value.append(&mut <Vec<u8>>::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
3763 target_value.append(&mut <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
3764 if random_bit {
3765 target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
3766 } else {
3767 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
3768 }
3769 if shutdown {
3770 target_value.append(&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3771 }
3772 if incl_chan_type {
3773 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
3774 }
3775 assert_eq!(encoded_value, target_value);
3776 }
3777
3778 #[test]
3779 fn encoding_open_channel() {
3780 do_encoding_open_channel(false, false, false);
3781 do_encoding_open_channel(false, false, true);
3782 do_encoding_open_channel(false, true, false);
3783 do_encoding_open_channel(false, true, true);
3784 do_encoding_open_channel(true, false, false);
3785 do_encoding_open_channel(true, false, true);
3786 do_encoding_open_channel(true, true, false);
3787 do_encoding_open_channel(true, true, true);
3788 }
3789
3790 fn do_encoding_open_channelv2(random_bit: bool, shutdown: bool, incl_chan_type: bool, require_confirmed_inputs: bool) {
3791 let secp_ctx = Secp256k1::new();
3792 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3793 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3794 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3795 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3796 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3797 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3798 let (_, pubkey_7) = get_keys_from!("0707070707070707070707070707070707070707070707070707070707070707", secp_ctx);
3799 let open_channelv2 = msgs::OpenChannelV2 {
3800 common_fields: CommonOpenChannelFields {
3801 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3802 temporary_channel_id: ChannelId::from_bytes([2; 32]),
3803 commitment_feerate_sat_per_1000_weight: 821716,
3804 funding_satoshis: 1311768467284833366,
3805 dust_limit_satoshis: 3608586615801332854,
3806 max_htlc_value_in_flight_msat: 8517154655701053848,
3807 htlc_minimum_msat: 2316138423780173,
3808 to_self_delay: 49340,
3809 max_accepted_htlcs: 49340,
3810 funding_pubkey: pubkey_1,
3811 revocation_basepoint: pubkey_2,
3812 payment_basepoint: pubkey_3,
3813 delayed_payment_basepoint: pubkey_4,
3814 htlc_basepoint: pubkey_5,
3815 first_per_commitment_point: pubkey_6,
3816 channel_flags: if random_bit { 1 << 5 } else { 0 },
3817 shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3818 channel_type: if incl_chan_type { Some(ChannelTypeFeatures::empty()) } else { None },
3819 },
3820 funding_feerate_sat_per_1000_weight: 821716,
3821 locktime: 305419896,
3822 second_per_commitment_point: pubkey_7,
3823 require_confirmed_inputs: if require_confirmed_inputs { Some(()) } else { None },
3824 };
3825 let encoded_value = open_channelv2.encode();
3826 let mut target_value = Vec::new();
3827 target_value.append(&mut <Vec<u8>>::from_hex("6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
3828 target_value.append(&mut <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap());
3829 target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
3830 target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
3831 target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap());
3832 target_value.append(&mut <Vec<u8>>::from_hex("3214466870114476").unwrap());
3833 target_value.append(&mut <Vec<u8>>::from_hex("7633030896203198").unwrap());
3834 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d").unwrap());
3835 target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
3836 target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
3837 target_value.append(&mut <Vec<u8>>::from_hex("12345678").unwrap());
3838 target_value.append(&mut <Vec<u8>>::from_hex("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap());
3839 target_value.append(&mut <Vec<u8>>::from_hex("024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766").unwrap());
3840 target_value.append(&mut <Vec<u8>>::from_hex("02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337").unwrap());
3841 target_value.append(&mut <Vec<u8>>::from_hex("03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
3842 target_value.append(&mut <Vec<u8>>::from_hex("0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7").unwrap());
3843 target_value.append(&mut <Vec<u8>>::from_hex("03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
3844 target_value.append(&mut <Vec<u8>>::from_hex("02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f").unwrap());
3845
3846 if random_bit {
3847 target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
3848 } else {
3849 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
3850 }
3851 if shutdown {
3852 target_value.append(&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3853 }
3854 if incl_chan_type {
3855 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
3856 }
3857 if require_confirmed_inputs {
3858 target_value.append(&mut <Vec<u8>>::from_hex("0200").unwrap());
3859 }
3860 assert_eq!(encoded_value, target_value);
3861 }
3862
3863 #[test]
3864 fn encoding_open_channelv2() {
3865 do_encoding_open_channelv2(false, false, false, false);
3866 do_encoding_open_channelv2(false, false, false, true);
3867 do_encoding_open_channelv2(false, false, true, false);
3868 do_encoding_open_channelv2(false, false, true, true);
3869 do_encoding_open_channelv2(false, true, false, false);
3870 do_encoding_open_channelv2(false, true, false, true);
3871 do_encoding_open_channelv2(false, true, true, false);
3872 do_encoding_open_channelv2(false, true, true, true);
3873 do_encoding_open_channelv2(true, false, false, false);
3874 do_encoding_open_channelv2(true, false, false, true);
3875 do_encoding_open_channelv2(true, false, true, false);
3876 do_encoding_open_channelv2(true, false, true, true);
3877 do_encoding_open_channelv2(true, true, false, false);
3878 do_encoding_open_channelv2(true, true, false, true);
3879 do_encoding_open_channelv2(true, true, true, false);
3880 do_encoding_open_channelv2(true, true, true, true);
3881 }
3882
3883 fn do_encoding_accept_channel(shutdown: bool) {
3884 let secp_ctx = Secp256k1::new();
3885 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3886 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3887 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3888 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3889 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3890 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3891 let accept_channel = msgs::AcceptChannel {
3892 common_fields: CommonAcceptChannelFields {
3893 temporary_channel_id: ChannelId::from_bytes([2; 32]),
3894 dust_limit_satoshis: 1311768467284833366,
3895 max_htlc_value_in_flight_msat: 2536655962884945560,
3896 htlc_minimum_msat: 2316138423780173,
3897 minimum_depth: 821716,
3898 to_self_delay: 49340,
3899 max_accepted_htlcs: 49340,
3900 funding_pubkey: pubkey_1,
3901 revocation_basepoint: pubkey_2,
3902 payment_basepoint: pubkey_3,
3903 delayed_payment_basepoint: pubkey_4,
3904 htlc_basepoint: pubkey_5,
3905 first_per_commitment_point: pubkey_6,
3906 shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3907 channel_type: None,
3908 },
3909 channel_reserve_satoshis: 3608586615801332854,
3910 #[cfg(taproot)]
3911 next_local_nonce: None,
3912 };
3913 let encoded_value = accept_channel.encode();
3914 let mut target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
3915 if shutdown {
3916 target_value.append(&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3917 }
3918 assert_eq!(encoded_value, target_value);
3919 }
3920
3921 #[test]
3922 fn encoding_accept_channel() {
3923 do_encoding_accept_channel(false);
3924 do_encoding_accept_channel(true);
3925 }
3926
3927 fn do_encoding_accept_channelv2(shutdown: bool) {
3928 let secp_ctx = Secp256k1::new();
3929 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3930 let (_, pubkey_2) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
3931 let (_, pubkey_3) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
3932 let (_, pubkey_4) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
3933 let (_, pubkey_5) = get_keys_from!("0505050505050505050505050505050505050505050505050505050505050505", secp_ctx);
3934 let (_, pubkey_6) = get_keys_from!("0606060606060606060606060606060606060606060606060606060606060606", secp_ctx);
3935 let (_, pubkey_7) = get_keys_from!("0707070707070707070707070707070707070707070707070707070707070707", secp_ctx);
3936 let accept_channelv2 = msgs::AcceptChannelV2 {
3937 common_fields: CommonAcceptChannelFields {
3938 temporary_channel_id: ChannelId::from_bytes([2; 32]),
3939 dust_limit_satoshis: 1311768467284833366,
3940 max_htlc_value_in_flight_msat: 2536655962884945560,
3941 htlc_minimum_msat: 2316138423780173,
3942 minimum_depth: 821716,
3943 to_self_delay: 49340,
3944 max_accepted_htlcs: 49340,
3945 funding_pubkey: pubkey_1,
3946 revocation_basepoint: pubkey_2,
3947 payment_basepoint: pubkey_3,
3948 delayed_payment_basepoint: pubkey_4,
3949 htlc_basepoint: pubkey_5,
3950 first_per_commitment_point: pubkey_6,
3951 shutdown_scriptpubkey: if shutdown { Some(Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey()) } else { None },
3952 channel_type: None,
3953 },
3954 funding_satoshis: 1311768467284833366,
3955 second_per_commitment_point: pubkey_7,
3956 require_confirmed_inputs: None,
3957 };
3958 let encoded_value = accept_channelv2.encode();
3959 let mut target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("2334032891223698").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f").unwrap()); if shutdown {
3975 target_value.append(&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
3976 }
3977 assert_eq!(encoded_value, target_value);
3978 }
3979
3980 #[test]
3981 fn encoding_accept_channelv2() {
3982 do_encoding_accept_channelv2(false);
3983 do_encoding_accept_channelv2(true);
3984 }
3985
3986 #[test]
3987 fn encoding_funding_created() {
3988 let secp_ctx = Secp256k1::new();
3989 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
3990 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
3991 let funding_created = msgs::FundingCreated {
3992 temporary_channel_id: ChannelId::from_bytes([2; 32]),
3993 funding_txid: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
3994 funding_output_index: 255,
3995 signature: sig_1,
3996 #[cfg(taproot)]
3997 partial_signature_with_nonce: None,
3998 #[cfg(taproot)]
3999 next_local_nonce: None,
4000 };
4001 let encoded_value = funding_created.encode();
4002 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4003 assert_eq!(encoded_value, target_value);
4004 }
4005
4006 #[test]
4007 fn encoding_funding_signed() {
4008 let secp_ctx = Secp256k1::new();
4009 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4010 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4011 let funding_signed = msgs::FundingSigned {
4012 channel_id: ChannelId::from_bytes([2; 32]),
4013 signature: sig_1,
4014 #[cfg(taproot)]
4015 partial_signature_with_nonce: None,
4016 };
4017 let encoded_value = funding_signed.encode();
4018 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4019 assert_eq!(encoded_value, target_value);
4020 }
4021
4022 #[test]
4023 fn encoding_channel_ready() {
4024 let secp_ctx = Secp256k1::new();
4025 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4026 let channel_ready = msgs::ChannelReady {
4027 channel_id: ChannelId::from_bytes([2; 32]),
4028 next_per_commitment_point: pubkey_1,
4029 short_channel_id_alias: None,
4030 };
4031 let encoded_value = channel_ready.encode();
4032 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
4033 assert_eq!(encoded_value, target_value);
4034 }
4035
4036 #[test]
4037 fn encoding_splice_init() {
4038 let secp_ctx = Secp256k1::new();
4039 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4040 let splice_init = msgs::SpliceInit {
4041 channel_id: ChannelId::from_bytes([2; 32]),
4042 funding_contribution_satoshis: -123456,
4043 funding_feerate_perkw: 2000,
4044 locktime: 0,
4045 funding_pubkey: pubkey_1,
4046 require_confirmed_inputs: Some(()),
4047 };
4048 let encoded_value = splice_init.encode();
4049 assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
4050 }
4051
4052 #[test]
4053 fn encoding_stfu() {
4054 let stfu = msgs::Stfu {
4055 channel_id: ChannelId::from_bytes([2; 32]),
4056 initiator: 1,
4057 };
4058 let encoded_value = stfu.encode();
4059 assert_eq!(encoded_value.as_hex().to_string(), "020202020202020202020202020202020202020202020202020202020202020201");
4060 }
4061
4062 #[test]
4063 fn encoding_splice_ack() {
4064 let secp_ctx = Secp256k1::new();
4065 let (_, pubkey_1,) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4066 let splice_ack = msgs::SpliceAck {
4067 channel_id: ChannelId::from_bytes([2; 32]),
4068 funding_contribution_satoshis: -123456,
4069 funding_pubkey: pubkey_1,
4070 require_confirmed_inputs: Some(()),
4071 };
4072 let encoded_value = splice_ack.encode();
4073 assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
4074 }
4075
4076 #[test]
4077 fn encoding_splice_locked() {
4078 let splice_locked = msgs::SpliceLocked {
4079 channel_id: ChannelId::from_bytes([2; 32]),
4080 splice_txid: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
4081 };
4082 let encoded_value = splice_locked.encode();
4083 assert_eq!(encoded_value.as_hex().to_string(), "02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2");
4084 }
4085
4086 #[test]
4087 fn encoding_tx_add_input() {
4088 let tx_add_input = msgs::TxAddInput {
4089 channel_id: ChannelId::from_bytes([2; 32]),
4090 serial_id: 4886718345,
4091 prevtx: TransactionU16LenLimited::new(Transaction {
4092 version: Version::TWO,
4093 lock_time: LockTime::ZERO,
4094 input: vec![TxIn {
4095 previous_output: OutPoint { txid: Txid::from_str("305bab643ee297b8b6b76b320792c8223d55082122cb606bf89382146ced9c77").unwrap(), index: 2 }.into_bitcoin_outpoint(),
4096 script_sig: ScriptBuf::new(),
4097 sequence: Sequence(0xfffffffd),
4098 witness: Witness::from_slice(&vec![
4099 <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
4100 <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
4101 }],
4102 output: vec![
4103 TxOut {
4104 value: Amount::from_sat(12704566),
4105 script_pubkey: Address::from_str("bc1qzlffunw52jav8vwdu5x3jfk6sr8u22rmq3xzw2").unwrap().assume_checked().script_pubkey(),
4106 },
4107 TxOut {
4108 value: Amount::from_sat(245148),
4109 script_pubkey: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().assume_checked().script_pubkey(),
4110 },
4111 ],
4112 }).unwrap(),
4113 prevtx_out: 305419896,
4114 sequence: 305419896,
4115 shared_input_txid: Some(Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap()),
4116 };
4117 let encoded_value = tx_add_input.encode();
4118 let target_value = "0202020202020202020202020202020202020202020202020202020202020202000000012345678900de02000000000101779ced6c148293f86b60cb222108553d22c89207326bb7b6b897e23e64ab5b300200000000fdffffff0236dbc1000000000016001417d29e4dd454bac3b1cde50d1926da80cfc5287b9cbd03000000000016001436ec78d514df462da95e6a00c24daa8915362d420247304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701210301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd694400000000123456781234567800206e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2";
4119 assert_eq!(encoded_value.as_hex().to_string(), target_value);
4120 }
4121
4122 #[test]
4123 fn encoding_tx_add_output() {
4124 let tx_add_output = msgs::TxAddOutput {
4125 channel_id: ChannelId::from_bytes([2; 32]),
4126 serial_id: 4886718345,
4127 sats: 4886718345,
4128 script: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().assume_checked().script_pubkey(),
4129 };
4130 let encoded_value = tx_add_output.encode();
4131 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000000012345678900000001234567890016001436ec78d514df462da95e6a00c24daa8915362d42").unwrap();
4132 assert_eq!(encoded_value, target_value);
4133 }
4134
4135 #[test]
4136 fn encoding_tx_remove_input() {
4137 let tx_remove_input = msgs::TxRemoveInput {
4138 channel_id: ChannelId::from_bytes([2; 32]),
4139 serial_id: 4886718345,
4140 };
4141 let encoded_value = tx_remove_input.encode();
4142 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202020000000123456789").unwrap();
4143 assert_eq!(encoded_value, target_value);
4144 }
4145
4146 #[test]
4147 fn encoding_tx_remove_output() {
4148 let tx_remove_output = msgs::TxRemoveOutput {
4149 channel_id: ChannelId::from_bytes([2; 32]),
4150 serial_id: 4886718345,
4151 };
4152 let encoded_value = tx_remove_output.encode();
4153 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202020000000123456789").unwrap();
4154 assert_eq!(encoded_value, target_value);
4155 }
4156
4157 #[test]
4158 fn encoding_tx_complete() {
4159 let tx_complete = msgs::TxComplete {
4160 channel_id: ChannelId::from_bytes([2; 32]),
4161 };
4162 let encoded_value = tx_complete.encode();
4163 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
4164 assert_eq!(encoded_value, target_value);
4165 }
4166
4167 #[test]
4168 fn encoding_tx_signatures() {
4169 let secp_ctx = Secp256k1::new();
4170 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4171 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4172
4173 let tx_signatures = msgs::TxSignatures {
4174 channel_id: ChannelId::from_bytes([2; 32]),
4175 tx_hash: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
4176 witnesses: vec![
4177 Witness::from_slice(&vec![
4178 <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
4179 <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
4180 Witness::from_slice(&vec![
4181 <Vec<u8>>::from_hex("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap(),
4182 <Vec<u8>>::from_hex("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap()]),
4183 ],
4184 shared_input_signature: Some(sig_1),
4185 };
4186 let encoded_value = tx_signatures.encode();
4187 let mut target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); target_value.append(&mut <Vec<u8>>::from_hex("6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("0002").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("006b").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("02").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("47").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap());
4195 target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap());
4197 target_value.append(&mut <Vec<u8>>::from_hex("006c").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("02").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("48").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap());
4202 target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap());
4204 target_value.append(&mut <Vec<u8>>::from_hex("0040").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap());
4206 assert_eq!(encoded_value, target_value);
4207 }
4208
4209 fn do_encoding_tx_init_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
4210 let tx_init_rbf = msgs::TxInitRbf {
4211 channel_id: ChannelId::from_bytes([2; 32]),
4212 locktime: 305419896,
4213 feerate_sat_per_1000_weight: 20190119,
4214 funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target { Some(value) } else { None },
4215 };
4216 let encoded_value = tx_init_rbf.encode();
4217 let mut target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); target_value.append(&mut <Vec<u8>>::from_hex("12345678").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("013413a7").unwrap()); if let Some((_, target)) = funding_value_with_hex_target {
4221 target_value.push(0x00); target_value.push(target.len() as u8 / 2); target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); }
4225 assert_eq!(encoded_value, target_value);
4226 }
4227
4228 #[test]
4229 fn encoding_tx_init_rbf() {
4230 do_encoding_tx_init_rbf(Some((1311768467284833366, "1234567890123456")));
4231 do_encoding_tx_init_rbf(Some((13117684672, "000000030DDFFBC0")));
4232 do_encoding_tx_init_rbf(None);
4233 }
4234
4235 fn do_encoding_tx_ack_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
4236 let tx_ack_rbf = msgs::TxAckRbf {
4237 channel_id: ChannelId::from_bytes([2; 32]),
4238 funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target { Some(value) } else { None },
4239 };
4240 let encoded_value = tx_ack_rbf.encode();
4241 let mut target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
4242 if let Some((_, target)) = funding_value_with_hex_target {
4243 target_value.push(0x00); target_value.push(target.len() as u8 / 2); target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); }
4247 assert_eq!(encoded_value, target_value);
4248 }
4249
4250 #[test]
4251 fn encoding_tx_ack_rbf() {
4252 do_encoding_tx_ack_rbf(Some((1311768467284833366, "1234567890123456")));
4253 do_encoding_tx_ack_rbf(Some((13117684672, "000000030DDFFBC0")));
4254 do_encoding_tx_ack_rbf(None);
4255 }
4256
4257 #[test]
4258 fn encoding_tx_abort() {
4259 let tx_abort = msgs::TxAbort {
4260 channel_id: ChannelId::from_bytes([2; 32]),
4261 data: <Vec<u8>>::from_hex("54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(),
4262 };
4263 let encoded_value = tx_abort.encode();
4264 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202002C54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap();
4265 assert_eq!(encoded_value, target_value);
4266 }
4267
4268 fn do_encoding_shutdown(script_type: u8) {
4269 let secp_ctx = Secp256k1::new();
4270 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4271 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
4272 let shutdown = msgs::Shutdown {
4273 channel_id: ChannelId::from_bytes([2; 32]),
4274 scriptpubkey:
4275 if script_type == 1 { Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: pubkey_1}, Network::Testnet).script_pubkey() }
4276 else if script_type == 2 { Address::p2sh(&script, Network::Testnet).unwrap().script_pubkey() }
4277 else if script_type == 3 { Address::p2wpkh(&::bitcoin::CompressedPublicKey(pubkey_1), Network::Testnet).script_pubkey() }
4278 else { Address::p2wsh(&script, Network::Testnet).script_pubkey() },
4279 };
4280 let encoded_value = shutdown.encode();
4281 let mut target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap();
4282 if script_type == 1 {
4283 target_value.append(&mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac").unwrap());
4284 } else if script_type == 2 {
4285 target_value.append(&mut <Vec<u8>>::from_hex("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87").unwrap());
4286 } else if script_type == 3 {
4287 target_value.append(&mut <Vec<u8>>::from_hex("0016001479b000887626b294a914501a4cd226b58b235983").unwrap());
4288 } else if script_type == 4 {
4289 target_value.append(&mut <Vec<u8>>::from_hex("002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260").unwrap());
4290 }
4291 assert_eq!(encoded_value, target_value);
4292 }
4293
4294 #[test]
4295 fn encoding_shutdown() {
4296 do_encoding_shutdown(1);
4297 do_encoding_shutdown(2);
4298 do_encoding_shutdown(3);
4299 do_encoding_shutdown(4);
4300 }
4301
4302 #[test]
4303 fn encoding_closing_signed() {
4304 let secp_ctx = Secp256k1::new();
4305 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4306 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4307 let closing_signed = msgs::ClosingSigned {
4308 channel_id: ChannelId::from_bytes([2; 32]),
4309 fee_satoshis: 2316138423780173,
4310 signature: sig_1,
4311 fee_range: None,
4312 };
4313 let encoded_value = closing_signed.encode();
4314 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4315 assert_eq!(encoded_value, target_value);
4316 assert_eq!(msgs::ClosingSigned::read(&mut Cursor::new(&target_value)).unwrap(), closing_signed);
4317
4318 let closing_signed_with_range = msgs::ClosingSigned {
4319 channel_id: ChannelId::from_bytes([2; 32]),
4320 fee_satoshis: 2316138423780173,
4321 signature: sig_1,
4322 fee_range: Some(msgs::ClosingSignedFeeRange {
4323 min_fee_satoshis: 0xdeadbeef,
4324 max_fee_satoshis: 0x1badcafe01234567,
4325 }),
4326 };
4327 let encoded_value_with_range = closing_signed_with_range.encode();
4328 let target_value_with_range = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a011000000000deadbeef1badcafe01234567").unwrap();
4329 assert_eq!(encoded_value_with_range, target_value_with_range);
4330 assert_eq!(msgs::ClosingSigned::read(&mut Cursor::new(&target_value_with_range)).unwrap(),
4331 closing_signed_with_range);
4332 }
4333
4334 #[test]
4335 fn encoding_update_add_htlc() {
4336 let secp_ctx = Secp256k1::new();
4337 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4338 let onion_routing_packet = msgs::OnionPacket {
4339 version: 255,
4340 public_key: Ok(pubkey_1),
4341 hop_data: [1; 20*65],
4342 hmac: [2; 32]
4343 };
4344 let update_add_htlc = msgs::UpdateAddHTLC {
4345 channel_id: ChannelId::from_bytes([2; 32]),
4346 htlc_id: 2316138423780173,
4347 amount_msat: 3608586615801332854,
4348 payment_hash: PaymentHash([1; 32]),
4349 cltv_expiry: 821716,
4350 onion_routing_packet,
4351 skimmed_fee_msat: None,
4352 blinding_point: None,
4353 };
4354 let encoded_value = update_add_htlc.encode();
4355 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
4356 assert_eq!(encoded_value, target_value);
4357 }
4358
4359 #[test]
4360 fn encoding_update_fulfill_htlc() {
4361 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
4362 channel_id: ChannelId::from_bytes([2; 32]),
4363 htlc_id: 2316138423780173,
4364 payment_preimage: PaymentPreimage([1; 32]),
4365 };
4366 let encoded_value = update_fulfill_htlc.encode();
4367 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
4368 assert_eq!(encoded_value, target_value);
4369 }
4370
4371 #[test]
4372 fn encoding_update_fail_htlc() {
4373 let reason = OnionErrorPacket {
4374 data: [1; 32].to_vec(),
4375 };
4376 let update_fail_htlc = msgs::UpdateFailHTLC {
4377 channel_id: ChannelId::from_bytes([2; 32]),
4378 htlc_id: 2316138423780173,
4379 reason
4380 };
4381 let encoded_value = update_fail_htlc.encode();
4382 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d00200101010101010101010101010101010101010101010101010101010101010101").unwrap();
4383 assert_eq!(encoded_value, target_value);
4384 }
4385
4386 #[test]
4387 fn encoding_update_fail_malformed_htlc() {
4388 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
4389 channel_id: ChannelId::from_bytes([2; 32]),
4390 htlc_id: 2316138423780173,
4391 sha256_of_onion: [1; 32],
4392 failure_code: 255
4393 };
4394 let encoded_value = update_fail_malformed_htlc.encode();
4395 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
4396 assert_eq!(encoded_value, target_value);
4397 }
4398
4399 fn do_encoding_commitment_signed(htlcs: bool) {
4400 let secp_ctx = Secp256k1::new();
4401 let (privkey_1, _) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4402 let (privkey_2, _) = get_keys_from!("0202020202020202020202020202020202020202020202020202020202020202", secp_ctx);
4403 let (privkey_3, _) = get_keys_from!("0303030303030303030303030303030303030303030303030303030303030303", secp_ctx);
4404 let (privkey_4, _) = get_keys_from!("0404040404040404040404040404040404040404040404040404040404040404", secp_ctx);
4405 let sig_1 = get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4406 let sig_2 = get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
4407 let sig_3 = get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
4408 let sig_4 = get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
4409 let commitment_signed = msgs::CommitmentSigned {
4410 channel_id: ChannelId::from_bytes([2; 32]),
4411 signature: sig_1,
4412 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
4413 batch: Some(msgs::CommitmentSignedBatch { batch_size: 3, funding_txid: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap() }),
4414 #[cfg(taproot)]
4415 partial_signature_with_nonce: None,
4416 };
4417 let encoded_value = commitment_signed.encode();
4418 let mut target_value = "0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a".to_string();
4419 if htlcs {
4420 target_value += "00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd";
4421 } else {
4422 target_value += "0000";
4423 }
4424 target_value += "002200036e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2"; assert_eq!(encoded_value.as_hex().to_string(), target_value);
4426 }
4427
4428 #[test]
4429 fn encoding_commitment_signed() {
4430 do_encoding_commitment_signed(true);
4431 do_encoding_commitment_signed(false);
4432 }
4433
4434 #[test]
4435 fn encoding_revoke_and_ack() {
4436 let secp_ctx = Secp256k1::new();
4437 let (_, pubkey_1) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4438 let raa = msgs::RevokeAndACK {
4439 channel_id: ChannelId::from_bytes([2; 32]),
4440 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],
4441 next_per_commitment_point: pubkey_1,
4442 #[cfg(taproot)]
4443 next_local_nonce: None,
4444 };
4445 let encoded_value = raa.encode();
4446 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
4447 assert_eq!(encoded_value, target_value);
4448 }
4449
4450 #[test]
4451 fn encoding_update_fee() {
4452 let update_fee = msgs::UpdateFee {
4453 channel_id: ChannelId::from_bytes([2; 32]),
4454 feerate_per_kw: 20190119,
4455 };
4456 let encoded_value = update_fee.encode();
4457 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202013413a7").unwrap();
4458 assert_eq!(encoded_value, target_value);
4459 }
4460
4461 #[test]
4462 fn encoding_init() {
4463 let mainnet_hash = ChainHash::using_genesis_block(Network::Bitcoin);
4464 assert_eq!(msgs::Init {
4465 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
4466 networks: Some(vec![mainnet_hash]),
4467 remote_network_address: None,
4468 }.encode(), <Vec<u8>>::from_hex("00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
4469 assert_eq!(msgs::Init {
4470 features: InitFeatures::from_le_bytes(vec![0xFF]),
4471 networks: None,
4472 remote_network_address: None,
4473 }.encode(), <Vec<u8>>::from_hex("0001ff0001ff").unwrap());
4474 assert_eq!(msgs::Init {
4475 features: InitFeatures::from_le_bytes(vec![]),
4476 networks: Some(vec![mainnet_hash]),
4477 remote_network_address: None,
4478 }.encode(), <Vec<u8>>::from_hex("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
4479 assert_eq!(msgs::Init {
4480 features: InitFeatures::from_le_bytes(vec![]),
4481 networks: Some(vec![ChainHash::from(&[1; 32]), ChainHash::from(&[2; 32])]),
4482 remote_network_address: None,
4483 }.encode(), <Vec<u8>>::from_hex("00000000014001010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap());
4484 let init_msg = msgs::Init { features: InitFeatures::from_le_bytes(vec![]),
4485 networks: Some(vec![mainnet_hash]),
4486 remote_network_address: Some(SocketAddress::TcpIpV4 {
4487 addr: [127, 0, 0, 1],
4488 port: 1000,
4489 }),
4490 };
4491 let encoded_value = init_msg.encode();
4492 let target_value = <Vec<u8>>::from_hex("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8").unwrap();
4493 assert_eq!(encoded_value, target_value);
4494 assert_eq!(msgs::Init::read(&mut Cursor::new(&target_value)).unwrap(), init_msg);
4495 }
4496
4497 #[test]
4498 fn encoding_error() {
4499 let error = msgs::ErrorMessage {
4500 channel_id: ChannelId::from_bytes([2; 32]),
4501 data: String::from("rust-lightning"),
4502 };
4503 let encoded_value = error.encode();
4504 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
4505 assert_eq!(encoded_value, target_value);
4506 }
4507
4508 #[test]
4509 fn encoding_warning() {
4510 let error = msgs::WarningMessage {
4511 channel_id: ChannelId::from_bytes([2; 32]),
4512 data: String::from("rust-lightning"),
4513 };
4514 let encoded_value = error.encode();
4515 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
4516 assert_eq!(encoded_value, target_value);
4517 }
4518
4519 #[test]
4520 fn encoding_ping() {
4521 let ping = msgs::Ping {
4522 ponglen: 64,
4523 byteslen: 64
4524 };
4525 let encoded_value = ping.encode();
4526 let target_value = <Vec<u8>>::from_hex("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
4527 assert_eq!(encoded_value, target_value);
4528 }
4529
4530 #[test]
4531 fn encoding_pong() {
4532 let pong = msgs::Pong {
4533 byteslen: 64
4534 };
4535 let encoded_value = pong.encode();
4536 let target_value = <Vec<u8>>::from_hex("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
4537 assert_eq!(encoded_value, target_value);
4538 }
4539
4540 #[test]
4541 fn encoding_nonfinal_onion_hop_data() {
4542 let outbound_msg = msgs::OutboundOnionPayload::Forward {
4543 short_channel_id: 0xdeadbeef1bad1dea,
4544 amt_to_forward: 0x0badf00d01020304,
4545 outgoing_cltv_value: 0xffffffff,
4546 };
4547 let encoded_value = outbound_msg.encode();
4548 let target_value = <Vec<u8>>::from_hex("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
4549 assert_eq!(encoded_value, target_value);
4550
4551 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
4552 let inbound_msg = ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
4553 if let msgs::InboundOnionPayload::Forward {
4554 short_channel_id, amt_to_forward, outgoing_cltv_value
4555 } = inbound_msg {
4556 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
4557 assert_eq!(amt_to_forward, 0x0badf00d01020304);
4558 assert_eq!(outgoing_cltv_value, 0xffffffff);
4559 } else { panic!(); }
4560 }
4561
4562 #[test]
4563 fn encoding_final_onion_hop_data() {
4564 let outbound_msg = msgs::OutboundOnionPayload::Receive {
4565 payment_data: None,
4566 payment_metadata: None,
4567 keysend_preimage: None,
4568 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
4569 cltv_expiry_height: 0xffffffff,
4570 custom_tlvs: &vec![],
4571 };
4572 let encoded_value = outbound_msg.encode();
4573 let target_value = <Vec<u8>>::from_hex("1002080badf00d010203040404ffffffff").unwrap();
4574 assert_eq!(encoded_value, target_value);
4575
4576 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
4577 let inbound_msg = ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
4578 if let msgs::InboundOnionPayload::Receive {
4579 payment_data: None, sender_intended_htlc_amt_msat, cltv_expiry_height, ..
4580 } = inbound_msg {
4581 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
4582 assert_eq!(cltv_expiry_height, 0xffffffff);
4583 } else { panic!(); }
4584 }
4585
4586 #[test]
4587 fn encoding_final_onion_hop_data_with_secret() {
4588 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
4589 let outbound_msg = msgs::OutboundOnionPayload::Receive {
4590 payment_data: Some(FinalOnionHopData {
4591 payment_secret: expected_payment_secret,
4592 total_msat: 0x1badca1f
4593 }),
4594 payment_metadata: None,
4595 keysend_preimage: None,
4596 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
4597 cltv_expiry_height: 0xffffffff,
4598 custom_tlvs: &vec![],
4599 };
4600 let encoded_value = outbound_msg.encode();
4601 let target_value = <Vec<u8>>::from_hex("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
4602 assert_eq!(encoded_value, target_value);
4603
4604 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
4605 let inbound_msg = ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
4606 if let msgs::InboundOnionPayload::Receive {
4607 payment_data: Some(FinalOnionHopData {
4608 payment_secret,
4609 total_msat: 0x1badca1f
4610 }),
4611 sender_intended_htlc_amt_msat, cltv_expiry_height,
4612 payment_metadata: None,
4613 keysend_preimage: None,
4614 custom_tlvs,
4615 } = inbound_msg {
4616 assert_eq!(payment_secret, expected_payment_secret);
4617 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
4618 assert_eq!(cltv_expiry_height, 0xffffffff);
4619 assert_eq!(custom_tlvs, vec![]);
4620 } else { panic!(); }
4621 }
4622
4623 #[test]
4624 fn encoding_final_onion_hop_data_with_bad_custom_tlvs() {
4625 let bad_type_range_tlvs = vec![
4628 ((1 << 16) - 4, vec![42]),
4629 ((1 << 16) - 2, vec![42; 32]),
4630 ];
4631 let mut msg = msgs::OutboundOnionPayload::Receive {
4632 payment_data: None,
4633 payment_metadata: None,
4634 keysend_preimage: None,
4635 custom_tlvs: &bad_type_range_tlvs,
4636 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
4637 cltv_expiry_height: 0xffffffff,
4638 };
4639 let encoded_value = msg.encode();
4640 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
4641 assert!(msgs::InboundOnionPayload::read(&mut Cursor::new(&encoded_value[..]), (None, &node_signer)).is_err());
4642 let good_type_range_tlvs = vec![
4643 ((1 << 16) - 3, vec![42]),
4644 ((1 << 16) - 1, vec![42; 32]),
4645 ];
4646 if let msgs::OutboundOnionPayload::Receive { ref mut custom_tlvs, .. } = msg {
4647 *custom_tlvs = &good_type_range_tlvs;
4648 }
4649 let encoded_value = msg.encode();
4650 let inbound_msg = ReadableArgs::read(&mut Cursor::new(&encoded_value[..]), (None, &node_signer)).unwrap();
4651 match inbound_msg {
4652 msgs::InboundOnionPayload::Receive { custom_tlvs, .. } => assert!(custom_tlvs.is_empty()),
4653 _ => panic!(),
4654 }
4655 }
4656
4657 #[test]
4658 fn encoding_final_onion_hop_data_with_custom_tlvs() {
4659 let expected_custom_tlvs = vec![
4660 (5482373483, vec![0x12, 0x34]),
4661 (5482373487, vec![0x42u8; 8]),
4662 ];
4663 let msg = msgs::OutboundOnionPayload::Receive {
4664 payment_data: None,
4665 payment_metadata: None,
4666 keysend_preimage: None,
4667 custom_tlvs: &expected_custom_tlvs,
4668 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
4669 cltv_expiry_height: 0xffffffff,
4670 };
4671 let encoded_value = msg.encode();
4672 let target_value = <Vec<u8>>::from_hex("2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242").unwrap();
4673 assert_eq!(encoded_value, target_value);
4674 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
4675 let inbound_msg: msgs::InboundOnionPayload = ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
4676 if let msgs::InboundOnionPayload::Receive {
4677 payment_data: None,
4678 payment_metadata: None,
4679 keysend_preimage: None,
4680 custom_tlvs,
4681 sender_intended_htlc_amt_msat,
4682 cltv_expiry_height: outgoing_cltv_value,
4683 ..
4684 } = inbound_msg {
4685 assert_eq!(custom_tlvs, expected_custom_tlvs);
4686 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
4687 assert_eq!(outgoing_cltv_value, 0xffffffff);
4688 } else { panic!(); }
4689 }
4690
4691 #[test]
4692 fn encoding_final_onion_hop_data_with_trampoline_packet() {
4693 let secp_ctx = Secp256k1::new();
4694 let (_private_key, public_key) = get_keys_from!("0101010101010101010101010101010101010101010101010101010101010101", secp_ctx);
4695
4696 let compressed_public_key = public_key.serialize();
4697 assert_eq!(compressed_public_key.len(), 33);
4698
4699 let trampoline_packet = TrampolineOnionPacket {
4700 version: 0,
4701 public_key,
4702 hop_data: vec![1; 650], hmac: [2; 32],
4704 };
4705 let encoded_trampoline_packet = trampoline_packet.encode();
4706 assert_eq!(encoded_trampoline_packet.len(), 716);
4707
4708 { let mut reader = Cursor::new(&encoded_trampoline_packet);
4710 let mut trampoline_packet_reader = FixedLengthReader::new(&mut reader, encoded_trampoline_packet.len() as u64);
4711 let decoded_trampoline_packet: TrampolineOnionPacket = <TrampolineOnionPacket as LengthReadable>::read(&mut trampoline_packet_reader).unwrap();
4712 assert_eq!(decoded_trampoline_packet.encode(), encoded_trampoline_packet);
4713 }
4714
4715 let msg = msgs::OutboundOnionPayload::TrampolineEntrypoint {
4716 multipath_trampoline_data: None,
4717 amt_to_forward: 0x0badf00d01020304,
4718 outgoing_cltv_value: 0xffffffff,
4719 trampoline_packet,
4720 };
4721 let encoded_payload = msg.encode();
4722
4723 let trampoline_type_bytes = &encoded_payload[19..=19];
4724 let mut trampoline_type_cursor = Cursor::new(trampoline_type_bytes);
4725 let trampoline_type_big_size: BigSize = Readable::read(&mut trampoline_type_cursor).unwrap();
4726 assert_eq!(trampoline_type_big_size.0, 20);
4727
4728 let trampoline_length_bytes = &encoded_payload[20..=22];
4729 let mut trampoline_length_cursor = Cursor::new(trampoline_length_bytes);
4730 let trampoline_length_big_size: BigSize = Readable::read(&mut trampoline_length_cursor).unwrap();
4731 assert_eq!(trampoline_length_big_size.0, encoded_trampoline_packet.len() as u64);
4732 }
4733
4734 #[test]
4735 fn encoding_final_onion_hop_data_with_eclair_trampoline_packet() {
4736 let public_key = PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()).unwrap();
4737 let hop_data = <Vec<u8>>::from_hex("cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4c").unwrap();
4738 let hmac_vector = <Vec<u8>>::from_hex("bb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c").unwrap();
4739 let mut hmac = [0; 32];
4740 hmac.copy_from_slice(&hmac_vector);
4741
4742 let compressed_public_key = public_key.serialize();
4743 assert_eq!(compressed_public_key.len(), 33);
4744
4745 let trampoline_packet = TrampolineOnionPacket {
4746 version: 0,
4747 public_key,
4748 hop_data,
4749 hmac,
4750 };
4751 let encoded_trampoline_packet = trampoline_packet.encode();
4752 let expected_eclair_trampoline_packet = <Vec<u8>>::from_hex("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4cbb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c").unwrap();
4753 assert_eq!(encoded_trampoline_packet, expected_eclair_trampoline_packet);
4754 }
4755
4756 #[test]
4757 fn encoding_outbound_trampoline_payload() {
4758 let mut trampoline_features = Bolt12InvoiceFeatures::empty();
4759 trampoline_features.set_basic_mpp_optional();
4760 let introduction_node = PublicKey::from_slice(&<Vec<u8>>::from_hex("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()).unwrap();
4761 let blinding_point = PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()).unwrap();
4762 let trampoline_payload = OutboundTrampolinePayload::LegacyBlindedPathEntry {
4763 amt_to_forward: 150_000_000,
4764 outgoing_cltv_value: 800_000,
4765 payment_paths: vec![
4766 BlindedPaymentPath::from_raw(
4767 introduction_node,
4768 blinding_point,
4769 vec![],
4770 BlindedPayInfo{
4771 fee_base_msat: 500,
4772 fee_proportional_millionths: 1_000,
4773 cltv_expiry_delta: 36,
4774 htlc_minimum_msat: 1,
4775 htlc_maximum_msat: 500_000_000,
4776 features: BlindedHopFeatures::empty(),
4777 }
4778 )
4779 ],
4780 invoice_features: Some(trampoline_features),
4781 };
4782 let serialized_payload = trampoline_payload.encode().to_lower_hex_string();
4783 assert_eq!(serialized_payload, "71020408f0d18004030c35001503020000165f032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e66868099102eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661900000001f4000003e800240000000000000001000000001dcd65000000");
4784 }
4785
4786 #[test]
4787 fn encode_trampoline_blinded_path_payload() {
4788 let trampoline_payload_eve = OutboundTrampolinePayload::BlindedReceive {
4789 sender_intended_htlc_amt_msat: 150_000_000,
4790 total_msat: 150_000_000,
4791 cltv_expiry_height: 800_000,
4792 encrypted_tlvs: &<Vec<u8>>::from_hex("bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c").unwrap(),
4793 intro_node_blinding_point: None,
4794 keysend_preimage: None,
4795 custom_tlvs: &vec![],
4796 };
4797 let eve_payload = trampoline_payload_eve.encode().to_lower_hex_string();
4798 assert_eq!(eve_payload, "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180");
4799
4800 let trampoline_payload_dave = OutboundTrampolinePayload::BlindedForward {
4801 encrypted_tlvs: &<Vec<u8>>::from_hex("0ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a").unwrap(),
4802 intro_node_blinding_point: Some(PublicKey::from_slice(&<Vec<u8>>::from_hex("02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e").unwrap()).unwrap()),
4803 };
4804 let dave_payload = trampoline_payload_dave.encode().to_lower_hex_string();
4805 assert_eq!(dave_payload, "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e")
4806 }
4807
4808 #[test]
4809 fn query_channel_range_end_blocknum() {
4810 let tests: Vec<(u32, u32, u32)> = vec![
4811 (10000, 1500, 11500),
4812 (0, 0xffffffff, 0xffffffff),
4813 (1, 0xffffffff, 0xffffffff),
4814 ];
4815
4816 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
4817 let sut = msgs::QueryChannelRange {
4818 chain_hash: ChainHash::using_genesis_block(Network::Regtest),
4819 first_blocknum,
4820 number_of_blocks,
4821 };
4822 assert_eq!(sut.end_blocknum(), expected);
4823 }
4824 }
4825
4826 #[test]
4827 fn encoding_query_channel_range() {
4828 let mut query_channel_range = msgs::QueryChannelRange {
4829 chain_hash: ChainHash::using_genesis_block(Network::Regtest),
4830 first_blocknum: 100000,
4831 number_of_blocks: 1500,
4832 };
4833 let encoded_value = query_channel_range.encode();
4834 let target_value = <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000186a0000005dc").unwrap();
4835 assert_eq!(encoded_value, target_value);
4836
4837 query_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
4838 assert_eq!(query_channel_range.first_blocknum, 100000);
4839 assert_eq!(query_channel_range.number_of_blocks, 1500);
4840 }
4841
4842 #[test]
4843 fn encoding_reply_channel_range() {
4844 do_encoding_reply_channel_range(0);
4845 do_encoding_reply_channel_range(1);
4846 }
4847
4848 fn do_encoding_reply_channel_range(encoding_type: u8) {
4849 let mut target_value = <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000b8a06000005dc01").unwrap();
4850 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
4851 let mut reply_channel_range = msgs::ReplyChannelRange {
4852 chain_hash: expected_chain_hash,
4853 first_blocknum: 756230,
4854 number_of_blocks: 1500,
4855 sync_complete: true,
4856 short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
4857 };
4858
4859 if encoding_type == 0 {
4860 target_value.append(&mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
4861 let encoded_value = reply_channel_range.encode();
4862 assert_eq!(encoded_value, target_value);
4863
4864 reply_channel_range = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
4865 assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
4866 assert_eq!(reply_channel_range.first_blocknum, 756230);
4867 assert_eq!(reply_channel_range.number_of_blocks, 1500);
4868 assert_eq!(reply_channel_range.sync_complete, true);
4869 assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
4870 assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
4871 assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
4872 } else {
4873 target_value.append(&mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a").unwrap());
4874 let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
4875 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
4876 }
4877 }
4878
4879 #[test]
4880 fn encoding_query_short_channel_ids() {
4881 do_encoding_query_short_channel_ids(0);
4882 do_encoding_query_short_channel_ids(1);
4883 }
4884
4885 fn do_encoding_query_short_channel_ids(encoding_type: u8) {
4886 let mut target_value = <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f").unwrap();
4887 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
4888 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
4889 chain_hash: expected_chain_hash,
4890 short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
4891 };
4892
4893 if encoding_type == 0 {
4894 target_value.append(&mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4").unwrap());
4895 let encoded_value = query_short_channel_ids.encode();
4896 assert_eq!(encoded_value, target_value);
4897
4898 query_short_channel_ids = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
4899 assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
4900 assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
4901 assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
4902 assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
4903 } else {
4904 target_value.append(&mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a").unwrap());
4905 let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> = Readable::read(&mut Cursor::new(&target_value[..]));
4906 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
4907 }
4908 }
4909
4910 #[test]
4911 fn encoding_reply_short_channel_ids_end() {
4912 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
4913 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
4914 chain_hash: expected_chain_hash,
4915 full_information: true,
4916 };
4917 let encoded_value = reply_short_channel_ids_end.encode();
4918 let target_value = <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f01").unwrap();
4919 assert_eq!(encoded_value, target_value);
4920
4921 reply_short_channel_ids_end = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
4922 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
4923 assert_eq!(reply_short_channel_ids_end.full_information, true);
4924 }
4925
4926 #[test]
4927 fn encoding_gossip_timestamp_filter(){
4928 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
4929 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
4930 chain_hash: expected_chain_hash,
4931 first_timestamp: 1590000000,
4932 timestamp_range: 0xffff_ffff,
4933 };
4934 let encoded_value = gossip_timestamp_filter.encode();
4935 let target_value = <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f5ec57980ffffffff").unwrap();
4936 assert_eq!(encoded_value, target_value);
4937
4938 gossip_timestamp_filter = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
4939 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
4940 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
4941 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);
4942 }
4943
4944 #[test]
4945 fn decode_onion_hop_data_len_as_bigsize() {
4946 let big_payload = encode_big_payload().unwrap();
4954 let mut rd = Cursor::new(&big_payload[..]);
4955
4956 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
4957 <msgs::InboundOnionPayload as ReadableArgs<(Option<PublicKey>, &test_utils::TestKeysInterface)>>
4958 ::read(&mut rd, (None, &&node_signer)).unwrap();
4959 }
4960 fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
4962 use crate::util::ser::HighZeroBytesDroppedBigSize;
4963 let payload = msgs::OutboundOnionPayload::Forward {
4964 short_channel_id: 0xdeadbeef1bad1dea,
4965 amt_to_forward: 1000,
4966 outgoing_cltv_value: 0xffffffff,
4967 };
4968 let mut encoded_payload = Vec::new();
4969 let test_bytes = vec![42u8; 1000];
4970 if let msgs::OutboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } = payload {
4971 _encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
4972 (1, test_bytes, required_vec),
4973 (2, HighZeroBytesDroppedBigSize(amt_to_forward), required),
4974 (4, HighZeroBytesDroppedBigSize(outgoing_cltv_value), required),
4975 (6, short_channel_id, required)
4976 });
4977 }
4978 Ok(encoded_payload)
4979 }
4980
4981 #[test]
4982 #[cfg(feature = "std")]
4983 fn test_socket_address_from_str() {
4984 let tcpip_v4 = SocketAddress::TcpIpV4 {
4985 addr: Ipv4Addr::new(127, 0, 0, 1).octets(),
4986 port: 1234,
4987 };
4988 assert_eq!(tcpip_v4, SocketAddress::from_str("127.0.0.1:1234").unwrap());
4989 assert_eq!(tcpip_v4, SocketAddress::from_str(&tcpip_v4.to_string()).unwrap());
4990
4991 let tcpip_v6 = SocketAddress::TcpIpV6 {
4992 addr: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).octets(),
4993 port: 1234,
4994 };
4995 assert_eq!(tcpip_v6, SocketAddress::from_str("[0:0:0:0:0:0:0:1]:1234").unwrap());
4996 assert_eq!(tcpip_v6, SocketAddress::from_str(&tcpip_v6.to_string()).unwrap());
4997
4998 let hostname = SocketAddress::Hostname {
4999 hostname: Hostname::try_from("lightning-node.mydomain.com".to_string()).unwrap(),
5000 port: 1234,
5001 };
5002 assert_eq!(hostname, SocketAddress::from_str("lightning-node.mydomain.com:1234").unwrap());
5003 assert_eq!(hostname, SocketAddress::from_str(&hostname.to_string()).unwrap());
5004
5005 let onion_v2 = SocketAddress::OnionV2 ([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7],);
5006 assert_eq!("OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7])", &onion_v2.to_string());
5007 assert_eq!(Err(SocketAddressParseError::InvalidOnionV3), SocketAddress::from_str("FACEBOOKCOREWWWI.onion:9735"));
5008
5009 let onion_v3 = SocketAddress::OnionV3 {
5010 ed25519_pubkey: [37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85,
5011 111, 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3],
5012 checksum: 48326,
5013 version: 121,
5014 port: 1234
5015 };
5016 assert_eq!(onion_v3, SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:1234").unwrap());
5017 assert_eq!(onion_v3, SocketAddress::from_str(&onion_v3.to_string()).unwrap());
5018
5019 assert_eq!(Err(SocketAddressParseError::InvalidOnionV3), SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6.onion:1234"));
5020 assert_eq!(Err(SocketAddressParseError::InvalidInput), SocketAddress::from_str("127.0.0.1@1234"));
5021 assert_eq!(Err(SocketAddressParseError::InvalidInput), "".parse::<SocketAddress>());
5022 assert!(SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94").is_err());
5023 assert!(SocketAddress::from_str("wrong$%#.com:1234").is_err());
5024 assert_eq!(Err(SocketAddressParseError::InvalidPort), SocketAddress::from_str("example.com:wrong"));
5025 assert!("localhost".parse::<SocketAddress>().is_err());
5026 assert!("localhost:invalid-port".parse::<SocketAddress>().is_err());
5027 assert!( "invalid-onion-v3-hostname.onion:8080".parse::<SocketAddress>().is_err());
5028 assert!("b32.example.onion:invalid-port".parse::<SocketAddress>().is_err());
5029 assert!("invalid-address".parse::<SocketAddress>().is_err());
5030 assert!(SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234").is_err());
5031 }
5032
5033 #[test]
5034 #[cfg(feature = "std")]
5035 fn test_socket_address_to_socket_addrs() {
5036 assert_eq!(SocketAddress::TcpIpV4 {addr:[0u8; 4], port: 1337,}.to_socket_addrs().unwrap().next().unwrap(),
5037 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0,0,0,0), 1337)));
5038 assert_eq!(SocketAddress::TcpIpV6 {addr:[0u8; 16], port: 1337,}.to_socket_addrs().unwrap().next().unwrap(),
5039 SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from([0u8; 16]), 1337, 0, 0)));
5040 assert_eq!(SocketAddress::Hostname { hostname: Hostname::try_from("0.0.0.0".to_string()).unwrap(), port: 0 }
5041 .to_socket_addrs().unwrap().next().unwrap(), SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from([0u8; 4]),0)));
5042 assert!(SocketAddress::OnionV2([0u8; 12]).to_socket_addrs().is_err());
5043 assert!(SocketAddress::OnionV3{ ed25519_pubkey: [37, 24, 75, 5, 25, 73, 117, 194, 139, 102,
5044 182, 107, 4, 105, 247, 246, 85, 111, 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31,
5045 33, 71, 3],
5046 checksum: 48326,
5047 version: 121,
5048 port: 1234 }.to_socket_addrs().is_err());
5049 }
5050}