1use bitcoin::constants::ChainHash;
28use bitcoin::hash_types::Txid;
29use bitcoin::script::ScriptBuf;
30use bitcoin::secp256k1::ecdsa::Signature;
31use bitcoin::secp256k1::PublicKey;
32use bitcoin::{secp256k1, Transaction, Witness};
33
34use crate::blinded_path::message::BlindedMessagePath;
35use crate::blinded_path::payment::{
36 BlindedPaymentTlvs, ForwardTlvs, ReceiveTlvs, UnauthenticatedReceiveTlvs,
37};
38use crate::blinded_path::payment::{BlindedTrampolineTlvs, TrampolineForwardTlvs};
39use crate::ln::channelmanager::Verification;
40use crate::ln::onion_utils;
41use crate::ln::types::ChannelId;
42use crate::offers::invoice_request::InvoiceRequest;
43use crate::onion_message;
44use crate::sign::{NodeSigner, Recipient};
45use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
46use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
47
48#[allow(unused_imports)]
49use crate::prelude::*;
50
51use crate::io::{self, Cursor, Read};
52use crate::io_extras::read_to_end;
53use core::fmt;
54use core::fmt::Debug;
55use core::fmt::Display;
56use core::ops::Deref;
57#[cfg(feature = "std")]
58use core::str::FromStr;
59#[cfg(feature = "std")]
60use std::net::SocketAddr;
61
62use crate::crypto::streams::ChaChaPolyReadAdapter;
63use crate::util::base32;
64use crate::util::logger;
65use crate::util::ser::{
66 BigSize, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname, LengthLimitedRead,
67 LengthReadable, LengthReadableArgs, Readable, ReadableArgs, WithoutLength, Writeable, Writer,
68};
69
70use crate::routing::gossip::{NodeAlias, NodeId};
71
72pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
74
75#[cfg(taproot)]
76#[derive(Clone, Debug, Hash, PartialEq, Eq)]
78pub struct PartialSignatureWithNonce(
79 pub musig2::types::PartialSignature,
80 pub musig2::types::PublicNonce,
81);
82
83#[derive(Clone, Debug, Hash, PartialEq, Eq)]
85pub enum DecodeError {
86 UnknownVersion,
90 UnknownRequiredFeature,
92 InvalidValue,
98 ShortRead,
100 BadLengthDescriptor,
102 Io(io::ErrorKind),
104 UnsupportedCompression,
106 DangerousValue,
116}
117
118#[derive(Clone, Debug, Hash, PartialEq, Eq)]
122pub struct Init {
123 pub features: InitFeatures,
125 pub networks: Option<Vec<ChainHash>>,
129 pub remote_network_address: Option<SocketAddress>,
136}
137
138#[derive(Clone, Debug, Hash, PartialEq, Eq)]
142pub struct ErrorMessage {
143 pub channel_id: ChannelId,
148 pub data: String,
154}
155
156#[derive(Clone, Debug, Hash, PartialEq, Eq)]
160pub struct WarningMessage {
161 pub channel_id: ChannelId,
165 pub data: String,
171}
172
173#[derive(Clone, Debug, Hash, PartialEq, Eq)]
177pub struct Ping {
178 pub ponglen: u16,
180 pub byteslen: u16,
184}
185
186#[derive(Clone, Debug, Hash, PartialEq, Eq)]
190pub struct Pong {
191 pub byteslen: u16,
195}
196
197#[derive(Clone, Debug, Hash, PartialEq, Eq)]
202pub struct CommonOpenChannelFields {
203 pub chain_hash: ChainHash,
205 pub temporary_channel_id: ChannelId,
209 pub funding_satoshis: u64,
212 pub dust_limit_satoshis: u64,
215 pub max_htlc_value_in_flight_msat: u64,
217 pub htlc_minimum_msat: u64,
219 pub commitment_feerate_sat_per_1000_weight: u32,
222 pub to_self_delay: u16,
225 pub max_accepted_htlcs: u16,
227 pub funding_pubkey: PublicKey,
229 pub revocation_basepoint: PublicKey,
231 pub payment_basepoint: PublicKey,
233 pub delayed_payment_basepoint: PublicKey,
236 pub htlc_basepoint: PublicKey,
238 pub first_per_commitment_point: PublicKey,
240 pub channel_flags: u8,
242 pub shutdown_scriptpubkey: Option<ScriptBuf>,
245 pub channel_type: Option<ChannelTypeFeatures>,
248}
249
250impl CommonOpenChannelFields {
251 pub fn channel_parameters(&self) -> ChannelParameters {
253 ChannelParameters {
254 dust_limit_satoshis: self.dust_limit_satoshis,
255 max_htlc_value_in_flight_msat: self.max_htlc_value_in_flight_msat,
256 htlc_minimum_msat: self.htlc_minimum_msat,
257 commitment_feerate_sat_per_1000_weight: self.commitment_feerate_sat_per_1000_weight,
258 to_self_delay: self.to_self_delay,
259 max_accepted_htlcs: self.max_accepted_htlcs,
260 }
261 }
262}
263
264#[derive(Clone, Debug, Hash, PartialEq, Eq)]
267pub struct ChannelParameters {
268 pub dust_limit_satoshis: u64,
271 pub max_htlc_value_in_flight_msat: u64,
273 pub htlc_minimum_msat: u64,
275 pub commitment_feerate_sat_per_1000_weight: u32,
278 pub to_self_delay: u16,
281 pub max_accepted_htlcs: u16,
283}
284
285#[derive(Clone, Debug, Hash, PartialEq, Eq)]
291pub struct OpenChannel {
292 pub common_fields: CommonOpenChannelFields,
294 pub push_msat: u64,
296 pub channel_reserve_satoshis: u64,
298}
299
300#[derive(Clone, Debug, Hash, PartialEq, Eq)]
306pub struct OpenChannelV2 {
307 pub common_fields: CommonOpenChannelFields,
309 pub funding_feerate_sat_per_1000_weight: u32,
311 pub locktime: u32,
313 pub second_per_commitment_point: PublicKey,
315 pub require_confirmed_inputs: Option<()>,
317}
318
319#[derive(Clone, Debug, Hash, PartialEq, Eq)]
324pub struct CommonAcceptChannelFields {
325 pub temporary_channel_id: ChannelId,
327 pub dust_limit_satoshis: u64,
330 pub max_htlc_value_in_flight_msat: u64,
332 pub htlc_minimum_msat: u64,
334 pub minimum_depth: u32,
336 pub to_self_delay: u16,
339 pub max_accepted_htlcs: u16,
341 pub funding_pubkey: PublicKey,
343 pub revocation_basepoint: PublicKey,
345 pub payment_basepoint: PublicKey,
347 pub delayed_payment_basepoint: PublicKey,
350 pub htlc_basepoint: PublicKey,
352 pub first_per_commitment_point: PublicKey,
354 pub shutdown_scriptpubkey: Option<ScriptBuf>,
357 pub channel_type: Option<ChannelTypeFeatures>,
363}
364
365#[derive(Clone, Debug, Hash, PartialEq, Eq)]
371pub struct AcceptChannel {
372 pub common_fields: CommonAcceptChannelFields,
374 pub channel_reserve_satoshis: u64,
376 #[cfg(taproot)]
377 pub next_local_nonce: Option<musig2::types::PublicNonce>,
379}
380
381#[derive(Clone, Debug, Hash, PartialEq, Eq)]
387pub struct AcceptChannelV2 {
388 pub common_fields: CommonAcceptChannelFields,
390 pub funding_satoshis: u64,
392 pub second_per_commitment_point: PublicKey,
394 pub require_confirmed_inputs: Option<()>,
396}
397
398#[derive(Clone, Debug, Hash, PartialEq, Eq)]
404pub struct FundingCreated {
405 pub temporary_channel_id: ChannelId,
407 pub funding_txid: Txid,
409 pub funding_output_index: u16,
411 pub signature: Signature,
413 #[cfg(taproot)]
414 pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
416 #[cfg(taproot)]
417 pub next_local_nonce: Option<musig2::types::PublicNonce>,
419}
420
421#[derive(Clone, Debug, Hash, PartialEq, Eq)]
427pub struct FundingSigned {
428 pub channel_id: ChannelId,
430 pub signature: Signature,
432 #[cfg(taproot)]
433 pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
435}
436
437#[derive(Clone, Debug, Hash, PartialEq, Eq)]
441pub struct ChannelReady {
442 pub channel_id: ChannelId,
444 pub next_per_commitment_point: PublicKey,
446 pub short_channel_id_alias: Option<u64>,
451}
452
453pub type SerialId = u64;
456
457#[derive(Clone, Debug, PartialEq, Eq)]
461pub struct Stfu {
462 pub channel_id: ChannelId,
464 pub initiator: bool,
466}
467
468#[derive(Clone, Debug, PartialEq, Eq)]
472pub struct SpliceInit {
473 pub channel_id: ChannelId,
475 pub funding_contribution_satoshis: i64,
478 pub funding_feerate_per_kw: u32,
480 pub locktime: u32,
482 pub funding_pubkey: PublicKey,
484 pub require_confirmed_inputs: Option<()>,
486}
487
488#[derive(Clone, Debug, PartialEq, Eq)]
492pub struct SpliceAck {
493 pub channel_id: ChannelId,
495 pub funding_contribution_satoshis: i64,
498 pub funding_pubkey: PublicKey,
500 pub require_confirmed_inputs: Option<()>,
502}
503
504#[derive(Clone, Debug, PartialEq, Eq)]
508pub struct SpliceLocked {
509 pub channel_id: ChannelId,
511 pub splice_txid: Txid,
513}
514
515#[derive(Clone, Debug, Hash, PartialEq, Eq)]
519pub struct TxAddInput {
520 pub channel_id: ChannelId,
522 pub serial_id: SerialId,
525 pub prevtx: Option<Transaction>,
528 pub prevtx_out: u32,
530 pub sequence: u32,
532 pub shared_input_txid: Option<Txid>,
534}
535
536#[derive(Clone, Debug, Hash, PartialEq, Eq)]
540pub struct TxAddOutput {
541 pub channel_id: ChannelId,
543 pub serial_id: SerialId,
546 pub sats: u64,
548 pub script: ScriptBuf,
550}
551
552#[derive(Clone, Debug, Hash, PartialEq, Eq)]
556pub struct TxRemoveInput {
557 pub channel_id: ChannelId,
559 pub serial_id: SerialId,
561}
562
563#[derive(Clone, Debug, Hash, PartialEq, Eq)]
567pub struct TxRemoveOutput {
568 pub channel_id: ChannelId,
570 pub serial_id: SerialId,
572}
573
574#[derive(Clone, Debug, Hash, PartialEq, Eq)]
579pub struct TxComplete {
580 pub channel_id: ChannelId,
582}
583
584#[derive(Clone, Debug, Hash, PartialEq, Eq)]
589pub struct TxSignatures {
590 pub channel_id: ChannelId,
592 pub tx_hash: Txid,
594 pub witnesses: Vec<Witness>,
596 pub shared_input_signature: Option<Signature>,
598}
599
600#[derive(Clone, Debug, Hash, PartialEq, Eq)]
605pub struct TxInitRbf {
606 pub channel_id: ChannelId,
608 pub locktime: u32,
610 pub feerate_sat_per_1000_weight: u32,
612 pub funding_output_contribution: Option<i64>,
615}
616
617#[derive(Clone, Debug, Hash, PartialEq, Eq)]
622pub struct TxAckRbf {
623 pub channel_id: ChannelId,
625 pub funding_output_contribution: Option<i64>,
628}
629
630#[derive(Clone, Debug, Hash, PartialEq, Eq)]
634pub struct TxAbort {
635 pub channel_id: ChannelId,
637 pub data: Vec<u8>,
639}
640
641#[derive(Clone, Debug, Hash, PartialEq, Eq)]
645pub struct Shutdown {
646 pub channel_id: ChannelId,
648 pub scriptpubkey: ScriptBuf,
652}
653
654#[derive(Clone, Debug, Hash, PartialEq, Eq)]
659pub struct ClosingSignedFeeRange {
660 pub min_fee_satoshis: u64,
663 pub max_fee_satoshis: u64,
666}
667
668#[derive(Clone, Debug, Hash, PartialEq, Eq)]
672pub struct ClosingSigned {
673 pub channel_id: ChannelId,
675 pub fee_satoshis: u64,
677 pub signature: Signature,
679 pub fee_range: Option<ClosingSignedFeeRange>,
682}
683
684#[derive(Clone, Debug, Hash, PartialEq, Eq)]
688pub struct ClosingComplete {
689 pub channel_id: ChannelId,
691 pub closer_scriptpubkey: ScriptBuf,
693 pub closee_scriptpubkey: ScriptBuf,
695 pub fee_satoshis: u64,
697 pub locktime: u32,
699 pub closer_output_only: Option<Signature>,
701 pub closee_output_only: Option<Signature>,
703 pub closer_and_closee_outputs: Option<Signature>,
705}
706
707#[derive(Clone, Debug, Hash, PartialEq, Eq)]
711pub struct ClosingSig {
712 pub channel_id: ChannelId,
714 pub closer_scriptpubkey: ScriptBuf,
716 pub closee_scriptpubkey: ScriptBuf,
718 pub fee_satoshis: u64,
720 pub locktime: u32,
722 pub closer_output_only: Option<Signature>,
724 pub closee_output_only: Option<Signature>,
726 pub closer_and_closee_outputs: Option<Signature>,
728}
729
730#[derive(Clone, Debug, Hash, PartialEq, Eq)]
735pub struct StartBatch {
736 pub channel_id: ChannelId,
738 pub batch_size: u16,
740 pub message_type: Option<u16>,
742}
743
744#[derive(Clone, Debug, Hash, PartialEq, Eq)]
748pub struct UpdateAddHTLC {
749 pub channel_id: ChannelId,
751 pub htlc_id: u64,
753 pub amount_msat: u64,
755 pub payment_hash: PaymentHash,
757 pub cltv_expiry: u32,
759 pub skimmed_fee_msat: Option<u64>,
764 pub onion_routing_packet: OnionPacket,
766 pub blinding_point: Option<PublicKey>,
769 pub hold_htlc: Option<()>,
774}
775
776#[derive(Clone, Debug, Hash, PartialEq, Eq)]
780pub struct OnionMessage {
781 pub blinding_point: PublicKey,
783 pub onion_routing_packet: onion_message::packet::Packet,
785}
786
787#[derive(Clone, Debug, Hash, PartialEq, Eq)]
791pub struct UpdateFulfillHTLC {
792 pub channel_id: ChannelId,
794 pub htlc_id: u64,
796 pub payment_preimage: PaymentPreimage,
798 pub attribution_data: Option<AttributionData>,
800}
801
802#[derive(Clone, Debug, Hash, PartialEq, Eq)]
812pub struct PeerStorage {
813 pub data: Vec<u8>,
815}
816
817#[derive(Clone, Debug, Hash, PartialEq, Eq)]
827pub struct PeerStorageRetrieval {
828 pub data: Vec<u8>,
830}
831
832#[derive(Clone, Debug, Hash, PartialEq, Eq)]
836pub struct UpdateFailHTLC {
837 pub channel_id: ChannelId,
839 pub htlc_id: u64,
841 pub(crate) reason: Vec<u8>,
842
843 pub attribution_data: Option<AttributionData>,
845}
846#[derive(Clone, Debug, Hash, PartialEq, Eq)]
850pub struct UpdateFailMalformedHTLC {
851 pub channel_id: ChannelId,
853 pub htlc_id: u64,
855 pub(crate) sha256_of_onion: [u8; 32],
856 pub failure_code: u16,
858}
859
860#[derive(Clone, Debug, Hash, PartialEq, Eq)]
864pub struct CommitmentSigned {
865 pub channel_id: ChannelId,
867 pub signature: Signature,
869 pub htlc_signatures: Vec<Signature>,
871 pub funding_txid: Option<Txid>,
873 #[cfg(taproot)]
874 pub partial_signature_with_nonce: Option<PartialSignatureWithNonce>,
876}
877
878#[derive(Clone, Debug, Hash, PartialEq, Eq)]
882pub struct RevokeAndACK {
883 pub channel_id: ChannelId,
885 pub per_commitment_secret: [u8; 32],
887 pub next_per_commitment_point: PublicKey,
889 #[cfg(taproot)]
890 pub next_local_nonce: Option<musig2::types::PublicNonce>,
892 pub release_htlc_message_paths: Vec<(u64, BlindedMessagePath)>,
899}
900
901#[derive(Clone, Debug, Hash, PartialEq, Eq)]
905pub struct UpdateFee {
906 pub channel_id: ChannelId,
908 pub feerate_per_kw: u32,
910}
911
912#[derive(Clone, Debug, Hash, PartialEq, Eq)]
916pub struct ChannelReestablish {
917 pub channel_id: ChannelId,
919 pub next_local_commitment_number: u64,
921 pub next_remote_commitment_number: u64,
923 pub your_last_per_commitment_secret: [u8; 32],
926 pub my_current_per_commitment_point: PublicKey,
928 pub next_funding: Option<NextFunding>,
942 pub my_current_funding_locked: Option<FundingLocked>,
949}
950
951#[derive(Clone, Debug, Hash, PartialEq, Eq)]
954pub struct NextFunding {
955 pub txid: Txid,
957
958 pub retransmit_flags: u8,
962}
963
964impl NextFunding {
965 pub fn retransmit(&mut self, flag: NextFundingFlag) {
967 self.retransmit_flags |= 1 << flag as u8;
968 }
969
970 pub fn should_retransmit(&self, flag: NextFundingFlag) -> bool {
972 self.retransmit_flags & (1 << flag as u8) != 0
973 }
974}
975
976#[repr(u8)]
978pub enum NextFundingFlag {
979 CommitmentSigned = 0,
981}
982
983#[derive(Clone, Debug, Hash, PartialEq, Eq)]
985pub struct FundingLocked {
986 pub txid: Txid,
989
990 pub retransmit_flags: u8,
994}
995
996impl FundingLocked {
997 pub fn retransmit(&mut self, flag: FundingLockedFlags) {
999 self.retransmit_flags |= 1 << flag as u8;
1000 }
1001
1002 pub fn should_retransmit(&self, flag: FundingLockedFlags) -> bool {
1004 self.retransmit_flags & (1 << flag as u8) != 0
1005 }
1006}
1007
1008#[repr(u8)]
1010pub enum FundingLockedFlags {
1011 AnnouncementSignatures = 0,
1013}
1014
1015#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1019pub struct AnnouncementSignatures {
1020 pub channel_id: ChannelId,
1022 pub short_channel_id: u64,
1024 pub node_signature: Signature,
1026 pub bitcoin_signature: Signature,
1028}
1029
1030#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1032pub enum SocketAddress {
1033 TcpIpV4 {
1035 addr: [u8; 4],
1037 port: u16,
1039 },
1040 TcpIpV6 {
1042 addr: [u8; 16],
1044 port: u16,
1046 },
1047 OnionV2([u8; 12]),
1052 OnionV3 {
1057 ed25519_pubkey: [u8; 32],
1059 checksum: u16,
1061 version: u8,
1063 port: u16,
1065 },
1066 Hostname {
1068 hostname: Hostname,
1070 port: u16,
1072 },
1073}
1074impl SocketAddress {
1075 pub(crate) fn get_id(&self) -> u8 {
1078 match self {
1079 &SocketAddress::TcpIpV4 { .. } => 1,
1080 &SocketAddress::TcpIpV6 { .. } => 2,
1081 &SocketAddress::OnionV2(_) => 3,
1082 &SocketAddress::OnionV3 { .. } => 4,
1083 &SocketAddress::Hostname { .. } => 5,
1084 }
1085 }
1086
1087 fn len(&self) -> u16 {
1089 match self {
1090 &SocketAddress::TcpIpV4 { .. } => 6,
1091 &SocketAddress::TcpIpV6 { .. } => 18,
1092 &SocketAddress::OnionV2(_) => 12,
1093 &SocketAddress::OnionV3 { .. } => 37,
1094 &SocketAddress::Hostname { ref hostname, .. } => u16::from(hostname.len()) + 3,
1096 }
1097 }
1098
1099 pub(crate) const MAX_LEN: u16 = 258;
1103
1104 pub(crate) fn is_tor(&self) -> bool {
1105 match self {
1106 &SocketAddress::TcpIpV4 { .. } => false,
1107 &SocketAddress::TcpIpV6 { .. } => false,
1108 &SocketAddress::OnionV2(_) => true,
1109 &SocketAddress::OnionV3 { .. } => true,
1110 &SocketAddress::Hostname { .. } => false,
1111 }
1112 }
1113}
1114
1115impl Writeable for SocketAddress {
1116 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1117 match self {
1118 &SocketAddress::TcpIpV4 { ref addr, ref port } => {
1119 1u8.write(writer)?;
1120 addr.write(writer)?;
1121 port.write(writer)?;
1122 },
1123 &SocketAddress::TcpIpV6 { ref addr, ref port } => {
1124 2u8.write(writer)?;
1125 addr.write(writer)?;
1126 port.write(writer)?;
1127 },
1128 &SocketAddress::OnionV2(bytes) => {
1129 3u8.write(writer)?;
1130 bytes.write(writer)?;
1131 },
1132 &SocketAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
1133 4u8.write(writer)?;
1134 ed25519_pubkey.write(writer)?;
1135 checksum.write(writer)?;
1136 version.write(writer)?;
1137 port.write(writer)?;
1138 },
1139 &SocketAddress::Hostname { ref hostname, ref port } => {
1140 5u8.write(writer)?;
1141 hostname.write(writer)?;
1142 port.write(writer)?;
1143 },
1144 }
1145 Ok(())
1146 }
1147}
1148
1149impl Readable for Result<SocketAddress, u8> {
1150 fn read<R: Read>(reader: &mut R) -> Result<Result<SocketAddress, u8>, DecodeError> {
1151 let byte = <u8 as Readable>::read(reader)?;
1152 match byte {
1153 1 => Ok(Ok(SocketAddress::TcpIpV4 {
1154 addr: Readable::read(reader)?,
1155 port: Readable::read(reader)?,
1156 })),
1157 2 => Ok(Ok(SocketAddress::TcpIpV6 {
1158 addr: Readable::read(reader)?,
1159 port: Readable::read(reader)?,
1160 })),
1161 3 => Ok(Ok(SocketAddress::OnionV2(Readable::read(reader)?))),
1162 4 => Ok(Ok(SocketAddress::OnionV3 {
1163 ed25519_pubkey: Readable::read(reader)?,
1164 checksum: Readable::read(reader)?,
1165 version: Readable::read(reader)?,
1166 port: Readable::read(reader)?,
1167 })),
1168 5 => Ok(Ok(SocketAddress::Hostname {
1169 hostname: Readable::read(reader)?,
1170 port: Readable::read(reader)?,
1171 })),
1172 _ => return Ok(Err(byte)),
1173 }
1174 }
1175}
1176
1177impl Readable for SocketAddress {
1178 fn read<R: Read>(reader: &mut R) -> Result<SocketAddress, DecodeError> {
1179 match Readable::read(reader) {
1180 Ok(Ok(res)) => Ok(res),
1181 Ok(Err(_)) => Err(DecodeError::UnknownVersion),
1182 Err(e) => Err(e),
1183 }
1184 }
1185}
1186
1187#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1189pub enum SocketAddressParseError {
1190 SocketAddrParse,
1192 InvalidInput,
1194 InvalidPort,
1196 InvalidOnionV3,
1198}
1199
1200impl fmt::Display for SocketAddressParseError {
1201 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1202 match self {
1203 SocketAddressParseError::SocketAddrParse => write!(f, "Socket address (IPv4/IPv6) parsing error"),
1204 SocketAddressParseError::InvalidInput => write!(f, "Invalid input format. \
1205 Expected: \"<ipv4>:<port>\", \"[<ipv6>]:<port>\", \"<onion address>.onion:<port>\" or \"<hostname>:<port>\""),
1206 SocketAddressParseError::InvalidPort => write!(f, "Invalid port"),
1207 SocketAddressParseError::InvalidOnionV3 => write!(f, "Invalid onion v3 address"),
1208 }
1209 }
1210}
1211
1212#[cfg(feature = "std")]
1213impl std::error::Error for SocketAddressParseError {}
1214
1215#[cfg(feature = "std")]
1216impl From<std::net::SocketAddrV4> for SocketAddress {
1217 fn from(addr: std::net::SocketAddrV4) -> Self {
1218 SocketAddress::TcpIpV4 { addr: addr.ip().octets(), port: addr.port() }
1219 }
1220}
1221
1222#[cfg(feature = "std")]
1223impl From<std::net::SocketAddrV6> for SocketAddress {
1224 fn from(addr: std::net::SocketAddrV6) -> Self {
1225 SocketAddress::TcpIpV6 { addr: addr.ip().octets(), port: addr.port() }
1226 }
1227}
1228
1229#[cfg(feature = "std")]
1230impl From<std::net::SocketAddr> for SocketAddress {
1231 fn from(addr: std::net::SocketAddr) -> Self {
1232 match addr {
1233 std::net::SocketAddr::V4(addr) => addr.into(),
1234 std::net::SocketAddr::V6(addr) => addr.into(),
1235 }
1236 }
1237}
1238
1239#[cfg(feature = "std")]
1240impl std::net::ToSocketAddrs for SocketAddress {
1241 type Iter = std::vec::IntoIter<std::net::SocketAddr>;
1242
1243 fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
1244 match self {
1245 SocketAddress::TcpIpV4 { addr, port } => {
1246 let ip_addr = std::net::Ipv4Addr::from(*addr);
1247 let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1248 Ok(vec![socket_addr].into_iter())
1249 },
1250 SocketAddress::TcpIpV6 { addr, port } => {
1251 let ip_addr = std::net::Ipv6Addr::from(*addr);
1252 let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1253 Ok(vec![socket_addr].into_iter())
1254 },
1255 SocketAddress::Hostname { ref hostname, port } => {
1256 (hostname.as_str(), *port).to_socket_addrs()
1257 },
1258 SocketAddress::OnionV2(..) => Err(std::io::Error::new(
1259 std::io::ErrorKind::Other,
1260 "Resolution of OnionV2 addresses is currently unsupported.",
1261 )),
1262 SocketAddress::OnionV3 { .. } => Err(std::io::Error::new(
1263 std::io::ErrorKind::Other,
1264 "Resolution of OnionV3 addresses is currently unsupported.",
1265 )),
1266 }
1267 }
1268}
1269
1270pub fn parse_onion_address(
1274 host: &str, port: u16,
1275) -> Result<SocketAddress, SocketAddressParseError> {
1276 if !host.ends_with(".onion") {
1277 return Err(SocketAddressParseError::InvalidInput);
1278 }
1279 let domain = &host[..host.len() - ".onion".len()];
1280 if domain.len() != 56 {
1281 return Err(SocketAddressParseError::InvalidOnionV3);
1282 }
1283 let onion = base32::Alphabet::RFC4648 { padding: false }
1284 .decode(domain)
1285 .map_err(|_| SocketAddressParseError::InvalidOnionV3)?;
1286 if onion.len() != 35 {
1287 return Err(SocketAddressParseError::InvalidOnionV3);
1288 }
1289
1290 let mut ed25519_pubkey = [0u8; 32];
1291 ed25519_pubkey.copy_from_slice(&onion[0..32]);
1292
1293 let checksum = u16::from_be_bytes([onion[32], onion[33]]);
1294 let version = onion[34];
1295
1296 Ok(SocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port })
1297}
1298
1299impl Display for SocketAddress {
1300 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1301 match self {
1302 SocketAddress::TcpIpV4{addr, port} => write!(
1303 f, "{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)?,
1304 SocketAddress::TcpIpV6{addr, port} => write!(
1305 f,
1306 "[{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}]:{}",
1307 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
1308 )?,
1309 SocketAddress::OnionV2(bytes) => write!(f, "OnionV2({:?})", bytes)?,
1310 SocketAddress::OnionV3 {
1311 ed25519_pubkey,
1312 checksum,
1313 version,
1314 port,
1315 } => {
1316 let mut addr = Vec::with_capacity(35);
1317 addr.extend_from_slice(ed25519_pubkey);
1318 let [c0, c1] = checksum.to_be_bytes();
1319 addr.push(c0);
1320 addr.push(c1);
1321 addr.push(*version);
1322 let onion = base32::Alphabet::RFC4648 { padding: false }.encode(&addr).to_lowercase();
1323 write!(f, "{}.onion:{}", onion, port)?
1324 },
1325 SocketAddress::Hostname { hostname, port } => write!(f, "{}:{}", hostname, port)?,
1326 }
1327 Ok(())
1328 }
1329}
1330
1331#[cfg(feature = "std")]
1332impl FromStr for SocketAddress {
1333 type Err = SocketAddressParseError;
1334
1335 fn from_str(s: &str) -> Result<Self, Self::Err> {
1336 match std::net::SocketAddr::from_str(s) {
1337 Ok(addr) => Ok(addr.into()),
1338 Err(_) => {
1339 let trimmed_input = match s.rfind(":") {
1340 Some(pos) => pos,
1341 None => return Err(SocketAddressParseError::InvalidInput),
1342 };
1343 let host = &s[..trimmed_input];
1344 let port: u16 = s[trimmed_input + 1..]
1345 .parse()
1346 .map_err(|_| SocketAddressParseError::InvalidPort)?;
1347 if host.ends_with(".onion") {
1348 return parse_onion_address(host, port);
1349 };
1350 if let Ok(hostname) = Hostname::try_from(s[..trimmed_input].to_string()) {
1351 return Ok(SocketAddress::Hostname { hostname, port });
1352 };
1353 return Err(SocketAddressParseError::SocketAddrParse);
1354 },
1355 }
1356 }
1357}
1358
1359pub enum UnsignedGossipMessage<'a> {
1361 ChannelAnnouncement(&'a UnsignedChannelAnnouncement),
1363 ChannelUpdate(&'a UnsignedChannelUpdate),
1365 NodeAnnouncement(&'a UnsignedNodeAnnouncement),
1367}
1368
1369impl<'a> Writeable for UnsignedGossipMessage<'a> {
1370 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1371 match self {
1372 UnsignedGossipMessage::ChannelAnnouncement(ref msg) => msg.write(writer),
1373 UnsignedGossipMessage::ChannelUpdate(ref msg) => msg.write(writer),
1374 UnsignedGossipMessage::NodeAnnouncement(ref msg) => msg.write(writer),
1375 }
1376 }
1377}
1378
1379#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1383pub struct UnsignedNodeAnnouncement {
1384 pub features: NodeFeatures,
1386 pub timestamp: u32,
1388 pub node_id: NodeId,
1391 pub rgb: [u8; 3],
1393 pub alias: NodeAlias,
1397 pub addresses: Vec<SocketAddress>,
1399 pub excess_address_data: Vec<u8>,
1404 pub excess_data: Vec<u8>,
1409}
1410#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1411pub struct NodeAnnouncement {
1415 pub signature: Signature,
1417 pub contents: UnsignedNodeAnnouncement,
1419}
1420
1421#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1425pub struct UnsignedChannelAnnouncement {
1426 pub features: ChannelFeatures,
1428 pub chain_hash: ChainHash,
1430 pub short_channel_id: u64,
1432 pub node_id_1: NodeId,
1434 pub node_id_2: NodeId,
1436 pub bitcoin_key_1: NodeId,
1438 pub bitcoin_key_2: NodeId,
1440 pub excess_data: Vec<u8>,
1445}
1446#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1450pub struct ChannelAnnouncement {
1451 pub node_signature_1: Signature,
1453 pub node_signature_2: Signature,
1455 pub bitcoin_signature_1: Signature,
1457 pub bitcoin_signature_2: Signature,
1459 pub contents: UnsignedChannelAnnouncement,
1461}
1462
1463#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1467pub struct UnsignedChannelUpdate {
1468 pub chain_hash: ChainHash,
1470 pub short_channel_id: u64,
1472 pub timestamp: u32,
1474 pub message_flags: u8,
1476 pub channel_flags: u8,
1479 pub cltv_expiry_delta: u16,
1488 pub htlc_minimum_msat: u64,
1490 pub htlc_maximum_msat: u64,
1494 pub fee_base_msat: u32,
1496 pub fee_proportional_millionths: u32,
1498 pub excess_data: Vec<u8>,
1503}
1504#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1508pub struct ChannelUpdate {
1509 pub signature: Signature,
1511 pub contents: UnsignedChannelUpdate,
1513}
1514
1515#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1522pub struct QueryChannelRange {
1523 pub chain_hash: ChainHash,
1525 pub first_blocknum: u32,
1527 pub number_of_blocks: u32,
1529}
1530
1531#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1543pub struct ReplyChannelRange {
1544 pub chain_hash: ChainHash,
1546 pub first_blocknum: u32,
1548 pub number_of_blocks: u32,
1550 pub sync_complete: bool,
1552 pub short_channel_ids: Vec<u64>,
1554}
1555
1556#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1568pub struct QueryShortChannelIds {
1569 pub chain_hash: ChainHash,
1571 pub short_channel_ids: Vec<u64>,
1573}
1574
1575#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1582pub struct ReplyShortChannelIdsEnd {
1583 pub chain_hash: ChainHash,
1585 pub full_information: bool,
1588}
1589
1590#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1596pub struct GossipTimestampFilter {
1597 pub chain_hash: ChainHash,
1599 pub first_timestamp: u32,
1601 pub timestamp_range: u32,
1603}
1604
1605enum EncodingType {
1610 Uncompressed = 0x00,
1611}
1612
1613#[derive(Clone, Debug, Hash, PartialEq)]
1615pub enum ErrorAction {
1616 DisconnectPeer {
1618 msg: Option<ErrorMessage>,
1620 },
1621 DisconnectPeerWithWarning {
1623 msg: WarningMessage,
1625 },
1626 IgnoreError,
1629 IgnoreAndLog(logger::Level),
1632 IgnoreDuplicateGossip,
1636 SendErrorMessage {
1638 msg: ErrorMessage,
1640 },
1641 SendWarningMessage {
1643 msg: WarningMessage,
1645 log_level: logger::Level,
1649 },
1650}
1651
1652#[derive(Clone, Debug)]
1654pub struct LightningError {
1655 pub err: String,
1657 pub action: ErrorAction,
1659}
1660
1661#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1664pub struct CommitmentUpdate {
1665 pub update_add_htlcs: Vec<UpdateAddHTLC>,
1667 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
1669 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
1671 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
1673 pub update_fee: Option<UpdateFee>,
1675 pub commitment_signed: Vec<CommitmentSigned>,
1677}
1678
1679#[derive(Clone, Debug)]
1687#[cfg_attr(any(test, feature = "_test_utils"), derive(PartialEq))]
1688pub enum MessageSendEvent {
1689 SendAcceptChannel {
1692 node_id: PublicKey,
1694 msg: AcceptChannel,
1696 },
1697 SendAcceptChannelV2 {
1700 node_id: PublicKey,
1702 msg: AcceptChannelV2,
1704 },
1705 SendOpenChannel {
1708 node_id: PublicKey,
1710 msg: OpenChannel,
1712 },
1713 SendOpenChannelV2 {
1716 node_id: PublicKey,
1718 msg: OpenChannelV2,
1720 },
1721 SendFundingCreated {
1723 node_id: PublicKey,
1725 msg: FundingCreated,
1727 },
1728 SendFundingSigned {
1730 node_id: PublicKey,
1732 msg: FundingSigned,
1734 },
1735 SendStfu {
1737 node_id: PublicKey,
1739 msg: Stfu,
1741 },
1742 SendSpliceInit {
1744 node_id: PublicKey,
1746 msg: SpliceInit,
1748 },
1749 SendSpliceAck {
1751 node_id: PublicKey,
1753 msg: SpliceAck,
1755 },
1756 SendSpliceLocked {
1758 node_id: PublicKey,
1760 msg: SpliceLocked,
1762 },
1763 SendTxAddInput {
1765 node_id: PublicKey,
1767 msg: TxAddInput,
1769 },
1770 SendTxAddOutput {
1772 node_id: PublicKey,
1774 msg: TxAddOutput,
1776 },
1777 SendTxRemoveInput {
1779 node_id: PublicKey,
1781 msg: TxRemoveInput,
1783 },
1784 SendTxRemoveOutput {
1786 node_id: PublicKey,
1788 msg: TxRemoveOutput,
1790 },
1791 SendTxComplete {
1793 node_id: PublicKey,
1795 msg: TxComplete,
1797 },
1798 SendTxSignatures {
1800 node_id: PublicKey,
1802 msg: TxSignatures,
1804 },
1805 SendTxInitRbf {
1807 node_id: PublicKey,
1809 msg: TxInitRbf,
1811 },
1812 SendTxAckRbf {
1814 node_id: PublicKey,
1816 msg: TxAckRbf,
1818 },
1819 SendTxAbort {
1821 node_id: PublicKey,
1823 msg: TxAbort,
1825 },
1826 SendChannelReady {
1828 node_id: PublicKey,
1830 msg: ChannelReady,
1832 },
1833 SendAnnouncementSignatures {
1835 node_id: PublicKey,
1837 msg: AnnouncementSignatures,
1839 },
1840 UpdateHTLCs {
1843 node_id: PublicKey,
1845 channel_id: ChannelId,
1847 updates: CommitmentUpdate,
1849 },
1850 SendRevokeAndACK {
1852 node_id: PublicKey,
1854 msg: RevokeAndACK,
1856 },
1857 SendClosingSigned {
1859 node_id: PublicKey,
1861 msg: ClosingSigned,
1863 },
1864 SendClosingComplete {
1866 node_id: PublicKey,
1868 msg: ClosingComplete,
1870 },
1871 SendClosingSig {
1873 node_id: PublicKey,
1875 msg: ClosingSig,
1877 },
1878 SendShutdown {
1880 node_id: PublicKey,
1882 msg: Shutdown,
1884 },
1885 SendChannelReestablish {
1887 node_id: PublicKey,
1889 msg: ChannelReestablish,
1891 },
1892 SendChannelAnnouncement {
1895 node_id: PublicKey,
1897 msg: ChannelAnnouncement,
1899 update_msg: ChannelUpdate,
1901 },
1902 BroadcastChannelAnnouncement {
1913 msg: ChannelAnnouncement,
1915 update_msg: Option<ChannelUpdate>,
1917 },
1918 BroadcastChannelUpdate {
1920 msg: ChannelUpdate,
1922 },
1923 BroadcastNodeAnnouncement {
1925 msg: NodeAnnouncement,
1927 },
1928 SendChannelUpdate {
1932 node_id: PublicKey,
1934 msg: ChannelUpdate,
1936 },
1937 HandleError {
1939 node_id: PublicKey,
1941 action: ErrorAction,
1943 },
1944 SendChannelRangeQuery {
1946 node_id: PublicKey,
1948 msg: QueryChannelRange,
1950 },
1951 SendShortIdsQuery {
1954 node_id: PublicKey,
1956 msg: QueryShortChannelIds,
1958 },
1959 SendReplyChannelRange {
1962 node_id: PublicKey,
1964 msg: ReplyChannelRange,
1966 },
1967 SendGossipTimestampFilter {
1970 node_id: PublicKey,
1972 msg: GossipTimestampFilter,
1974 },
1975 SendPeerStorage {
1979 node_id: PublicKey,
1981 msg: PeerStorage,
1983 },
1984 SendPeerStorageRetrieval {
1987 node_id: PublicKey,
1989 msg: PeerStorageRetrieval,
1991 },
1992}
1993
1994pub trait BaseMessageHandler {
2000 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2003
2004 fn peer_disconnected(&self, their_node_id: PublicKey);
2006
2007 fn provided_node_features(&self) -> NodeFeatures;
2011
2012 fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures;
2018
2019 fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool)
2029 -> Result<(), ()>;
2030}
2031
2032pub trait ChannelMessageHandler: BaseMessageHandler {
2037 fn handle_open_channel(&self, their_node_id: PublicKey, msg: &OpenChannel);
2040 fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &OpenChannelV2);
2042 fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &AcceptChannel);
2044 fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &AcceptChannelV2);
2046 fn handle_funding_created(&self, their_node_id: PublicKey, msg: &FundingCreated);
2048 fn handle_funding_signed(&self, their_node_id: PublicKey, msg: &FundingSigned);
2050 fn handle_channel_ready(&self, their_node_id: PublicKey, msg: &ChannelReady);
2052
2053 fn handle_peer_storage(&self, their_node_id: PublicKey, msg: PeerStorage);
2056 fn handle_peer_storage_retrieval(&self, their_node_id: PublicKey, msg: PeerStorageRetrieval);
2058
2059 fn handle_shutdown(&self, their_node_id: PublicKey, msg: &Shutdown);
2062 fn handle_closing_signed(&self, their_node_id: PublicKey, msg: &ClosingSigned);
2064 #[cfg(simple_close)]
2066 fn handle_closing_complete(&self, their_node_id: PublicKey, msg: ClosingComplete);
2067 #[cfg(simple_close)]
2069 fn handle_closing_sig(&self, their_node_id: PublicKey, msg: ClosingSig);
2070
2071 fn handle_stfu(&self, their_node_id: PublicKey, msg: &Stfu);
2074
2075 fn handle_splice_init(&self, their_node_id: PublicKey, msg: &SpliceInit);
2078 fn handle_splice_ack(&self, their_node_id: PublicKey, msg: &SpliceAck);
2080 fn handle_splice_locked(&self, their_node_id: PublicKey, msg: &SpliceLocked);
2082
2083 fn handle_tx_add_input(&self, their_node_id: PublicKey, msg: &TxAddInput);
2086 fn handle_tx_add_output(&self, their_node_id: PublicKey, msg: &TxAddOutput);
2088 fn handle_tx_remove_input(&self, their_node_id: PublicKey, msg: &TxRemoveInput);
2090 fn handle_tx_remove_output(&self, their_node_id: PublicKey, msg: &TxRemoveOutput);
2092 fn handle_tx_complete(&self, their_node_id: PublicKey, msg: &TxComplete);
2094 fn handle_tx_signatures(&self, their_node_id: PublicKey, msg: &TxSignatures);
2096 fn handle_tx_init_rbf(&self, their_node_id: PublicKey, msg: &TxInitRbf);
2098 fn handle_tx_ack_rbf(&self, their_node_id: PublicKey, msg: &TxAckRbf);
2100 fn handle_tx_abort(&self, their_node_id: PublicKey, msg: &TxAbort);
2102
2103 fn handle_update_add_htlc(&self, their_node_id: PublicKey, msg: &UpdateAddHTLC);
2106 fn handle_update_fulfill_htlc(&self, their_node_id: PublicKey, msg: UpdateFulfillHTLC);
2108 fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailHTLC);
2110 fn handle_update_fail_malformed_htlc(
2112 &self, their_node_id: PublicKey, msg: &UpdateFailMalformedHTLC,
2113 );
2114 fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &CommitmentSigned);
2116 fn handle_commitment_signed_batch(
2118 &self, their_node_id: PublicKey, channel_id: ChannelId, batch: Vec<CommitmentSigned>,
2119 );
2120 fn handle_revoke_and_ack(&self, their_node_id: PublicKey, msg: &RevokeAndACK);
2122
2123 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
2124 fn handle_commitment_signed_batch_test(
2125 &self, their_node_id: PublicKey, batch: &Vec<CommitmentSigned>,
2126 ) {
2127 assert!(!batch.is_empty());
2128 if batch.len() == 1 {
2129 self.handle_commitment_signed(their_node_id, &batch[0]);
2130 } else {
2131 let channel_id = batch[0].channel_id;
2132 self.handle_commitment_signed_batch(their_node_id, channel_id, batch.clone());
2133 }
2134 }
2135
2136 fn handle_update_fee(&self, their_node_id: PublicKey, msg: &UpdateFee);
2138
2139 fn handle_announcement_signatures(
2142 &self, their_node_id: PublicKey, msg: &AnnouncementSignatures,
2143 );
2144
2145 fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &ChannelReestablish);
2148
2149 fn handle_channel_update(&self, their_node_id: PublicKey, msg: &ChannelUpdate);
2151
2152 fn handle_error(&self, their_node_id: PublicKey, msg: &ErrorMessage);
2155
2156 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>>;
2162
2163 fn message_received(&self);
2170}
2171
2172pub trait RoutingMessageHandler: BaseMessageHandler {
2180 fn handle_node_announcement(
2185 &self, their_node_id: Option<PublicKey>, msg: &NodeAnnouncement,
2186 ) -> Result<bool, LightningError>;
2187 fn handle_channel_announcement(
2192 &self, their_node_id: Option<PublicKey>, msg: &ChannelAnnouncement,
2193 ) -> Result<bool, LightningError>;
2194 fn handle_channel_update(
2199 &self, their_node_id: Option<PublicKey>, msg: &ChannelUpdate,
2200 ) -> Result<bool, LightningError>;
2201 fn get_next_channel_announcement(
2205 &self, starting_point: u64,
2206 ) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
2207 fn get_next_node_announcement(
2212 &self, starting_point: Option<&NodeId>,
2213 ) -> Option<NodeAnnouncement>;
2214 fn handle_reply_channel_range(
2218 &self, their_node_id: PublicKey, msg: ReplyChannelRange,
2219 ) -> Result<(), LightningError>;
2220 fn handle_reply_short_channel_ids_end(
2225 &self, their_node_id: PublicKey, msg: ReplyShortChannelIdsEnd,
2226 ) -> Result<(), LightningError>;
2227 fn handle_query_channel_range(
2230 &self, their_node_id: PublicKey, msg: QueryChannelRange,
2231 ) -> Result<(), LightningError>;
2232 fn handle_query_short_channel_ids(
2235 &self, their_node_id: PublicKey, msg: QueryShortChannelIds,
2236 ) -> Result<(), LightningError>;
2237
2238 fn processing_queue_high(&self) -> bool;
2244}
2245
2246pub trait OnionMessageHandler: BaseMessageHandler {
2248 fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage);
2250
2251 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage>;
2256
2257 fn timer_tick_occurred(&self);
2260}
2261
2262pub trait SendOnlyMessageHandler: BaseMessageHandler {}
2268
2269#[derive(Clone, Debug, PartialEq, Eq)]
2270pub struct FinalOnionHopData {
2273 pub payment_secret: PaymentSecret,
2277 pub total_msat: u64,
2281}
2282
2283mod fuzzy_internal_msgs {
2284 use super::{FinalOnionHopData, TrampolineOnionPacket};
2285 use crate::blinded_path::payment::{
2286 BlindedPaymentPath, PaymentConstraints, PaymentContext, PaymentRelay,
2287 };
2288 use crate::ln::onion_utils::AttributionData;
2289 use crate::offers::invoice_request::InvoiceRequest;
2290 use crate::types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
2291 use crate::types::payment::{PaymentPreimage, PaymentSecret};
2292 use bitcoin::secp256k1::PublicKey;
2293
2294 #[allow(unused_imports)]
2295 use crate::prelude::*;
2296
2297 pub struct InboundOnionForwardPayload {
2301 pub short_channel_id: u64,
2302 pub amt_to_forward: u64,
2304 pub outgoing_cltv_value: u32,
2305 }
2306
2307 #[allow(unused)]
2308 pub struct InboundTrampolineEntrypointPayload {
2309 pub amt_to_forward: u64,
2310 pub outgoing_cltv_value: u32,
2311 pub multipath_trampoline_data: Option<FinalOnionHopData>,
2312 pub trampoline_packet: TrampolineOnionPacket,
2313 pub current_path_key: Option<PublicKey>,
2316 }
2317
2318 pub struct InboundOnionReceivePayload {
2319 pub payment_data: Option<FinalOnionHopData>,
2320 pub payment_metadata: Option<Vec<u8>>,
2321 pub keysend_preimage: Option<PaymentPreimage>,
2322 pub custom_tlvs: Vec<(u64, Vec<u8>)>,
2323 pub sender_intended_htlc_amt_msat: u64,
2324 pub cltv_expiry_height: u32,
2325 }
2326 pub struct InboundOnionBlindedForwardPayload {
2327 pub short_channel_id: u64,
2328 pub payment_relay: PaymentRelay,
2329 pub payment_constraints: PaymentConstraints,
2330 pub features: BlindedHopFeatures,
2331 pub intro_node_blinding_point: Option<PublicKey>,
2332 pub next_blinding_override: Option<PublicKey>,
2333 }
2334 pub struct InboundOnionBlindedReceivePayload {
2335 pub sender_intended_htlc_amt_msat: u64,
2336 pub total_msat: u64,
2337 pub cltv_expiry_height: u32,
2338 pub payment_secret: PaymentSecret,
2339 pub payment_constraints: PaymentConstraints,
2340 pub payment_context: PaymentContext,
2341 pub intro_node_blinding_point: Option<PublicKey>,
2342 pub keysend_preimage: Option<PaymentPreimage>,
2343 pub invoice_request: Option<InvoiceRequest>,
2344 pub custom_tlvs: Vec<(u64, Vec<u8>)>,
2345 }
2346
2347 pub enum InboundOnionPayload {
2348 Forward(InboundOnionForwardPayload),
2349 TrampolineEntrypoint(InboundTrampolineEntrypointPayload),
2350 Receive(InboundOnionReceivePayload),
2351 BlindedForward(InboundOnionBlindedForwardPayload),
2352 BlindedReceive(InboundOnionBlindedReceivePayload),
2353 }
2354
2355 pub struct InboundTrampolineForwardPayload {
2356 pub next_trampoline: PublicKey,
2357 pub amt_to_forward: u64,
2359 pub outgoing_cltv_value: u32,
2360 }
2361
2362 pub struct InboundTrampolineBlindedForwardPayload {
2363 pub next_trampoline: PublicKey,
2364 pub payment_relay: PaymentRelay,
2365 pub payment_constraints: PaymentConstraints,
2366 pub features: BlindedHopFeatures,
2367 pub intro_node_blinding_point: Option<PublicKey>,
2368 pub next_blinding_override: Option<PublicKey>,
2369 }
2370
2371 pub enum InboundTrampolinePayload {
2372 Forward(InboundTrampolineForwardPayload),
2373 BlindedForward(InboundTrampolineBlindedForwardPayload),
2374 Receive(InboundOnionReceivePayload),
2375 BlindedReceive(InboundOnionBlindedReceivePayload),
2376 }
2377
2378 pub(crate) enum OutboundOnionPayload<'a> {
2379 Forward {
2380 short_channel_id: u64,
2381 amt_to_forward: u64,
2383 outgoing_cltv_value: u32,
2384 },
2385 TrampolineEntrypoint {
2386 amt_to_forward: u64,
2387 outgoing_cltv_value: u32,
2388 multipath_trampoline_data: Option<FinalOnionHopData>,
2389 trampoline_packet: TrampolineOnionPacket,
2390 },
2391 #[allow(unused)]
2395 BlindedTrampolineEntrypoint {
2396 amt_to_forward: u64,
2397 outgoing_cltv_value: u32,
2398 multipath_trampoline_data: Option<FinalOnionHopData>,
2399 trampoline_packet: TrampolineOnionPacket,
2400 current_path_key: PublicKey,
2402 },
2403 Receive {
2404 payment_data: Option<FinalOnionHopData>,
2405 payment_metadata: Option<&'a Vec<u8>>,
2406 keysend_preimage: Option<PaymentPreimage>,
2407 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2408 sender_intended_htlc_amt_msat: u64,
2409 cltv_expiry_height: u32,
2410 },
2411 BlindedForward {
2412 encrypted_tlvs: &'a Vec<u8>,
2413 intro_node_blinding_point: Option<PublicKey>,
2414 },
2415 BlindedReceive {
2416 sender_intended_htlc_amt_msat: u64,
2417 total_msat: u64,
2418 cltv_expiry_height: u32,
2419 encrypted_tlvs: &'a Vec<u8>,
2420 intro_node_blinding_point: Option<PublicKey>, keysend_preimage: Option<PaymentPreimage>,
2422 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2423 invoice_request: Option<&'a InvoiceRequest>,
2424 },
2425 }
2426
2427 pub(crate) enum OutboundTrampolinePayload<'a> {
2428 Forward {
2429 amt_to_forward: u64,
2431 outgoing_cltv_value: u32,
2432 outgoing_node_id: PublicKey,
2434 },
2435 #[cfg(test)]
2436 Receive {
2440 payment_data: Option<FinalOnionHopData>,
2441 sender_intended_htlc_amt_msat: u64,
2442 cltv_expiry_height: u32,
2443 },
2444 #[allow(unused)]
2445 LegacyBlindedPathEntry {
2448 amt_to_forward: u64,
2450 outgoing_cltv_value: u32,
2451 payment_paths: Vec<BlindedPaymentPath>,
2453 invoice_features: Option<Bolt12InvoiceFeatures>,
2455 },
2456 BlindedForward {
2457 encrypted_tlvs: &'a Vec<u8>,
2458 intro_node_blinding_point: Option<PublicKey>,
2459 },
2460 BlindedReceive {
2461 sender_intended_htlc_amt_msat: u64,
2462 total_msat: u64,
2463 cltv_expiry_height: u32,
2464 encrypted_tlvs: &'a Vec<u8>,
2465 intro_node_blinding_point: Option<PublicKey>, keysend_preimage: Option<PaymentPreimage>,
2467 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2468 },
2469 }
2470
2471 pub struct DecodedOnionErrorPacket {
2472 pub(crate) hmac: [u8; 32],
2473 pub(crate) failuremsg: Vec<u8>,
2474 pub(crate) pad: Vec<u8>,
2475 }
2476
2477 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
2478 pub struct OnionErrorPacket {
2479 pub data: Vec<u8>,
2482 pub attribution_data: Option<AttributionData>,
2483 }
2484}
2485#[cfg(fuzzing)]
2486pub use self::fuzzy_internal_msgs::*;
2487#[cfg(not(fuzzing))]
2488pub(crate) use self::fuzzy_internal_msgs::*;
2489
2490use super::onion_utils::AttributionData;
2491
2492#[derive(Clone, Hash, PartialEq, Eq)]
2494pub struct OnionPacket {
2495 pub version: u8,
2497 pub public_key: Result<PublicKey, secp256k1::Error>,
2503 pub hop_data: [u8; 20 * 65],
2505 pub hmac: [u8; 32],
2507}
2508
2509impl onion_utils::Packet for OnionPacket {
2510 type Data = onion_utils::FixedSizeOnionPacket;
2511 fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self {
2512 Self { version: 0, public_key: Ok(pubkey), hop_data: hop_data.0, hmac }
2513 }
2514}
2515
2516impl fmt::Debug for OnionPacket {
2517 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2518 f.write_fmt(format_args!(
2519 "OnionPacket version {} with hmac {:?}",
2520 self.version,
2521 &self.hmac[..]
2522 ))
2523 }
2524}
2525
2526#[derive(Clone, Hash, PartialEq, Eq)]
2528pub struct TrampolineOnionPacket {
2529 pub version: u8,
2531 pub public_key: PublicKey,
2533 pub hop_data: Vec<u8>,
2540 pub hmac: [u8; 32],
2542}
2543
2544impl onion_utils::Packet for TrampolineOnionPacket {
2545 type Data = Vec<u8>;
2546 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Self {
2547 Self { version: 0, public_key, hop_data, hmac }
2548 }
2549}
2550
2551impl Writeable for TrampolineOnionPacket {
2552 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2553 self.version.write(w)?;
2554 self.public_key.write(w)?;
2555 w.write_all(&self.hop_data)?;
2556 self.hmac.write(w)?;
2557 Ok(())
2558 }
2559}
2560
2561impl LengthReadable for TrampolineOnionPacket {
2562 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2563 let hop_data_len = r.remaining_bytes().saturating_sub(66); let version = Readable::read(r)?;
2566 let public_key = Readable::read(r)?;
2567
2568 let mut rd = FixedLengthReader::new(r, hop_data_len);
2569 let hop_data = WithoutLength::<Vec<u8>>::read_from_fixed_length_buffer(&mut rd)?.0;
2570
2571 let hmac = Readable::read(r)?;
2572
2573 Ok(TrampolineOnionPacket { version, public_key, hop_data, hmac })
2574 }
2575}
2576
2577impl Debug for TrampolineOnionPacket {
2578 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2579 f.write_fmt(format_args!(
2580 "TrampolineOnionPacket version {} with hmac {:?}",
2581 self.version,
2582 &self.hmac[..]
2583 ))
2584 }
2585}
2586
2587impl From<UpdateFailHTLC> for OnionErrorPacket {
2588 fn from(msg: UpdateFailHTLC) -> Self {
2589 OnionErrorPacket { data: msg.reason, attribution_data: msg.attribution_data }
2590 }
2591}
2592
2593impl fmt::Display for DecodeError {
2594 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2595 match *self {
2596 DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
2597 DecodeError::UnknownRequiredFeature => {
2598 f.write_str("Unknown required feature preventing decode")
2599 },
2600 DecodeError::InvalidValue => {
2601 f.write_str("Nonsense bytes didn't map to the type they were interpreted as")
2602 },
2603 DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
2604 DecodeError::BadLengthDescriptor => f.write_str(
2605 "A length descriptor in the packet didn't describe the later data correctly",
2606 ),
2607 DecodeError::Io(ref e) => fmt::Debug::fmt(e, f),
2608 DecodeError::UnsupportedCompression => {
2609 f.write_str("We don't support receiving messages with zlib-compressed fields")
2610 },
2611 DecodeError::DangerousValue => {
2612 f.write_str("Value would be dangerous to continue execution with")
2613 },
2614 }
2615 }
2616}
2617
2618impl From<io::Error> for DecodeError {
2619 fn from(e: io::Error) -> Self {
2620 if e.kind() == io::ErrorKind::UnexpectedEof {
2621 DecodeError::ShortRead
2622 } else {
2623 DecodeError::Io(e.kind())
2624 }
2625 }
2626}
2627
2628impl Writeable for AcceptChannel {
2629 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2630 self.common_fields.temporary_channel_id.write(w)?;
2631 self.common_fields.dust_limit_satoshis.write(w)?;
2632 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2633 self.channel_reserve_satoshis.write(w)?;
2634 self.common_fields.htlc_minimum_msat.write(w)?;
2635 self.common_fields.minimum_depth.write(w)?;
2636 self.common_fields.to_self_delay.write(w)?;
2637 self.common_fields.max_accepted_htlcs.write(w)?;
2638 self.common_fields.funding_pubkey.write(w)?;
2639 self.common_fields.revocation_basepoint.write(w)?;
2640 self.common_fields.payment_basepoint.write(w)?;
2641 self.common_fields.delayed_payment_basepoint.write(w)?;
2642 self.common_fields.htlc_basepoint.write(w)?;
2643 self.common_fields.first_per_commitment_point.write(w)?;
2644 #[cfg(not(taproot))]
2645 encode_tlv_stream!(w, {
2646 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2648 });
2649 #[cfg(taproot)]
2650 encode_tlv_stream!(w, {
2651 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2653 (4, self.next_local_nonce, option),
2654 });
2655 Ok(())
2656 }
2657}
2658
2659impl LengthReadable for AcceptChannel {
2660 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2661 let temporary_channel_id: ChannelId = Readable::read(r)?;
2662 let dust_limit_satoshis: u64 = Readable::read(r)?;
2663 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2664 let channel_reserve_satoshis: u64 = Readable::read(r)?;
2665 let htlc_minimum_msat: u64 = Readable::read(r)?;
2666 let minimum_depth: u32 = Readable::read(r)?;
2667 let to_self_delay: u16 = Readable::read(r)?;
2668 let max_accepted_htlcs: u16 = Readable::read(r)?;
2669 let funding_pubkey: PublicKey = Readable::read(r)?;
2670 let revocation_basepoint: PublicKey = Readable::read(r)?;
2671 let payment_basepoint: PublicKey = Readable::read(r)?;
2672 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2673 let htlc_basepoint: PublicKey = Readable::read(r)?;
2674 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2675
2676 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2677 let mut channel_type: Option<ChannelTypeFeatures> = None;
2678 #[cfg(not(taproot))]
2679 decode_tlv_stream!(r, {
2680 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2681 (1, channel_type, option),
2682 });
2683 #[cfg(taproot)]
2684 let mut next_local_nonce: Option<musig2::types::PublicNonce> = None;
2685 #[cfg(taproot)]
2686 decode_tlv_stream!(r, {
2687 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2688 (1, channel_type, option),
2689 (4, next_local_nonce, option),
2690 });
2691
2692 Ok(AcceptChannel {
2693 common_fields: CommonAcceptChannelFields {
2694 temporary_channel_id,
2695 dust_limit_satoshis,
2696 max_htlc_value_in_flight_msat,
2697 htlc_minimum_msat,
2698 minimum_depth,
2699 to_self_delay,
2700 max_accepted_htlcs,
2701 funding_pubkey,
2702 revocation_basepoint,
2703 payment_basepoint,
2704 delayed_payment_basepoint,
2705 htlc_basepoint,
2706 first_per_commitment_point,
2707 shutdown_scriptpubkey,
2708 channel_type,
2709 },
2710 channel_reserve_satoshis,
2711 #[cfg(taproot)]
2712 next_local_nonce,
2713 })
2714 }
2715}
2716
2717impl Writeable for AcceptChannelV2 {
2718 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2719 self.common_fields.temporary_channel_id.write(w)?;
2720 self.funding_satoshis.write(w)?;
2721 self.common_fields.dust_limit_satoshis.write(w)?;
2722 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2723 self.common_fields.htlc_minimum_msat.write(w)?;
2724 self.common_fields.minimum_depth.write(w)?;
2725 self.common_fields.to_self_delay.write(w)?;
2726 self.common_fields.max_accepted_htlcs.write(w)?;
2727 self.common_fields.funding_pubkey.write(w)?;
2728 self.common_fields.revocation_basepoint.write(w)?;
2729 self.common_fields.payment_basepoint.write(w)?;
2730 self.common_fields.delayed_payment_basepoint.write(w)?;
2731 self.common_fields.htlc_basepoint.write(w)?;
2732 self.common_fields.first_per_commitment_point.write(w)?;
2733 self.second_per_commitment_point.write(w)?;
2734
2735 encode_tlv_stream!(w, {
2736 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2738 (2, self.require_confirmed_inputs, option),
2739 });
2740 Ok(())
2741 }
2742}
2743
2744impl LengthReadable for AcceptChannelV2 {
2745 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2746 let temporary_channel_id: ChannelId = Readable::read(r)?;
2747 let funding_satoshis: u64 = Readable::read(r)?;
2748 let dust_limit_satoshis: u64 = Readable::read(r)?;
2749 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2750 let htlc_minimum_msat: u64 = Readable::read(r)?;
2751 let minimum_depth: u32 = Readable::read(r)?;
2752 let to_self_delay: u16 = Readable::read(r)?;
2753 let max_accepted_htlcs: u16 = Readable::read(r)?;
2754 let funding_pubkey: PublicKey = Readable::read(r)?;
2755 let revocation_basepoint: PublicKey = Readable::read(r)?;
2756 let payment_basepoint: PublicKey = Readable::read(r)?;
2757 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2758 let htlc_basepoint: PublicKey = Readable::read(r)?;
2759 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2760 let second_per_commitment_point: PublicKey = Readable::read(r)?;
2761
2762 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2763 let mut channel_type: Option<ChannelTypeFeatures> = None;
2764 let mut require_confirmed_inputs: Option<()> = None;
2765 decode_tlv_stream!(r, {
2766 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2767 (1, channel_type, option),
2768 (2, require_confirmed_inputs, option),
2769 });
2770
2771 Ok(AcceptChannelV2 {
2772 common_fields: CommonAcceptChannelFields {
2773 temporary_channel_id,
2774 dust_limit_satoshis,
2775 max_htlc_value_in_flight_msat,
2776 htlc_minimum_msat,
2777 minimum_depth,
2778 to_self_delay,
2779 max_accepted_htlcs,
2780 funding_pubkey,
2781 revocation_basepoint,
2782 payment_basepoint,
2783 delayed_payment_basepoint,
2784 htlc_basepoint,
2785 first_per_commitment_point,
2786 shutdown_scriptpubkey,
2787 channel_type,
2788 },
2789 funding_satoshis,
2790 second_per_commitment_point,
2791 require_confirmed_inputs,
2792 })
2793 }
2794}
2795
2796impl_writeable_msg!(Stfu, {
2797 channel_id,
2798 initiator,
2799}, {});
2800
2801impl_writeable_msg!(SpliceInit, {
2802 channel_id,
2803 funding_contribution_satoshis,
2804 funding_feerate_per_kw,
2805 locktime,
2806 funding_pubkey,
2807}, {
2808 (2, require_confirmed_inputs, option), });
2810
2811impl_writeable_msg!(SpliceAck, {
2812 channel_id,
2813 funding_contribution_satoshis,
2814 funding_pubkey,
2815}, {
2816 (2, require_confirmed_inputs, option), });
2818
2819impl_writeable_msg!(SpliceLocked, {
2820 channel_id,
2821 splice_txid,
2822}, {});
2823
2824impl Writeable for TxAddInput {
2825 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2826 self.channel_id.write(w)?;
2827 self.serial_id.write(w)?;
2828
2829 match &self.prevtx {
2830 Some(tx) => {
2831 (tx.serialized_length() as u16).write(w)?;
2832 tx.write(w)?;
2833 },
2834 None => 0u16.write(w)?,
2835 }
2836
2837 self.prevtx_out.write(w)?;
2838 self.sequence.write(w)?;
2839
2840 encode_tlv_stream!(w, {
2841 (0, self.shared_input_txid, option),
2842 });
2843 Ok(())
2844 }
2845}
2846
2847impl LengthReadable for TxAddInput {
2848 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2849 let channel_id: ChannelId = Readable::read(r)?;
2850 let serial_id: SerialId = Readable::read(r)?;
2851
2852 let prevtx_len: u16 = Readable::read(r)?;
2853 let prevtx = if prevtx_len > 0 {
2854 let mut tx_reader = FixedLengthReader::new(r, prevtx_len as u64);
2855 let tx: Transaction = Readable::read(&mut tx_reader)?;
2856 if tx_reader.bytes_remain() {
2857 return Err(DecodeError::BadLengthDescriptor);
2858 }
2859
2860 Some(tx)
2861 } else {
2862 None
2863 };
2864
2865 let prevtx_out: u32 = Readable::read(r)?;
2866 let sequence: u32 = Readable::read(r)?;
2867
2868 let mut shared_input_txid: Option<Txid> = None;
2869 decode_tlv_stream!(r, {
2870 (0, shared_input_txid, option),
2871 });
2872
2873 Ok(TxAddInput { channel_id, serial_id, prevtx, prevtx_out, sequence, shared_input_txid })
2874 }
2875}
2876impl_writeable_msg!(TxAddOutput, {
2877 channel_id,
2878 serial_id,
2879 sats,
2880 script,
2881}, {});
2882
2883impl_writeable_msg!(TxRemoveInput, {
2884 channel_id,
2885 serial_id,
2886}, {});
2887
2888impl_writeable_msg!(TxRemoveOutput, {
2889 channel_id,
2890 serial_id,
2891}, {});
2892
2893impl_writeable_msg!(TxComplete, {
2894 channel_id,
2895}, {});
2896
2897impl_writeable_msg!(TxSignatures, {
2898 channel_id,
2899 tx_hash,
2900 witnesses,
2901}, {
2902 (0, shared_input_signature, option), });
2904
2905impl_writeable_msg!(TxInitRbf, {
2906 channel_id,
2907 locktime,
2908 feerate_sat_per_1000_weight,
2909}, {
2910 (0, funding_output_contribution, option),
2911});
2912
2913impl_writeable_msg!(TxAckRbf, {
2914 channel_id,
2915}, {
2916 (0, funding_output_contribution, option),
2917});
2918
2919impl_writeable_msg!(TxAbort, {
2920 channel_id,
2921 data,
2922}, {});
2923
2924impl_writeable_msg!(AnnouncementSignatures, {
2925 channel_id,
2926 short_channel_id,
2927 node_signature,
2928 bitcoin_signature
2929}, {});
2930
2931impl_writeable_msg!(ChannelReestablish, {
2932 channel_id,
2933 next_local_commitment_number,
2934 next_remote_commitment_number,
2935 your_last_per_commitment_secret,
2936 my_current_per_commitment_point,
2937}, {
2938 (1, next_funding, option),
2939 (5, my_current_funding_locked, option),
2940});
2941
2942impl_writeable!(NextFunding, {
2943 txid,
2944 retransmit_flags
2945});
2946
2947impl_writeable!(FundingLocked, {
2948 txid,
2949 retransmit_flags
2950});
2951
2952impl_writeable_msg!(ClosingSigned,
2953 { channel_id, fee_satoshis, signature },
2954 { (1, fee_range, option) }
2955);
2956
2957impl_writeable_msg!(ClosingComplete,
2958 { channel_id, closer_scriptpubkey, closee_scriptpubkey, fee_satoshis, locktime },
2959 {
2960 (1, closer_output_only, option),
2961 (2, closee_output_only, option),
2962 (3, closer_and_closee_outputs, option)
2963 }
2964);
2965
2966impl_writeable_msg!(ClosingSig,
2967 { channel_id, closer_scriptpubkey, closee_scriptpubkey, fee_satoshis, locktime },
2968 {
2969 (1, closer_output_only, option),
2970 (2, closee_output_only, option),
2971 (3, closer_and_closee_outputs, option)
2972 }
2973);
2974
2975impl_writeable!(ClosingSignedFeeRange, {
2976 min_fee_satoshis,
2977 max_fee_satoshis
2978});
2979
2980#[cfg(not(taproot))]
2981impl_writeable_msg!(CommitmentSigned, {
2982 channel_id,
2983 signature,
2984 htlc_signatures
2985}, {
2986 (1, funding_txid, option),
2987});
2988
2989#[cfg(taproot)]
2990impl_writeable_msg!(CommitmentSigned, {
2991 channel_id,
2992 signature,
2993 htlc_signatures
2994}, {
2995 (1, funding_txid, option),
2996 (2, partial_signature_with_nonce, option),
2997});
2998
2999impl_writeable!(DecodedOnionErrorPacket, {
3000 hmac,
3001 failuremsg,
3002 pad
3003});
3004
3005#[cfg(not(taproot))]
3006impl_writeable_msg!(FundingCreated, {
3007 temporary_channel_id,
3008 funding_txid,
3009 funding_output_index,
3010 signature
3011}, {});
3012#[cfg(taproot)]
3013impl_writeable_msg!(FundingCreated, {
3014 temporary_channel_id,
3015 funding_txid,
3016 funding_output_index,
3017 signature
3018}, {
3019 (2, partial_signature_with_nonce, option),
3020 (4, next_local_nonce, option)
3021});
3022
3023#[cfg(not(taproot))]
3024impl_writeable_msg!(FundingSigned, {
3025 channel_id,
3026 signature
3027}, {});
3028
3029#[cfg(taproot)]
3030impl_writeable_msg!(FundingSigned, {
3031 channel_id,
3032 signature
3033}, {
3034 (2, partial_signature_with_nonce, option)
3035});
3036
3037impl_writeable_msg!(ChannelReady, {
3038 channel_id,
3039 next_per_commitment_point,
3040}, {
3041 (1, short_channel_id_alias, option),
3042});
3043
3044pub(crate) fn write_features_up_to_13<W: Writer>(
3045 w: &mut W, le_flags: &[u8],
3046) -> Result<(), io::Error> {
3047 let len = core::cmp::min(2, le_flags.len());
3048 (len as u16).write(w)?;
3049 for i in (0..len).rev() {
3050 if i == 0 {
3051 le_flags[i].write(w)?;
3052 } else {
3053 (le_flags[i] & 0b00_11_11_11).write(w)?;
3056 }
3057 }
3058 Ok(())
3059}
3060
3061impl Writeable for Init {
3062 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3063 write_features_up_to_13(w, self.features.le_flags())?;
3066 self.features.write(w)?;
3067 encode_tlv_stream!(w, {
3068 (1, self.networks.as_ref().map(|n| WithoutLength(n)), option),
3069 (3, self.remote_network_address, option),
3070 });
3071 Ok(())
3072 }
3073}
3074
3075impl LengthReadable for Init {
3076 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3077 let global_features: InitFeatures = Readable::read(r)?;
3078 let features: InitFeatures = Readable::read(r)?;
3079 let mut remote_network_address: Option<SocketAddress> = None;
3080 let mut networks: Option<WithoutLength<Vec<ChainHash>>> = None;
3081 decode_tlv_stream!(r, {
3082 (1, networks, option),
3083 (3, remote_network_address, option)
3084 });
3085 Ok(Init {
3086 features: features | global_features,
3087 networks: networks.map(|n| n.0),
3088 remote_network_address,
3089 })
3090 }
3091}
3092
3093impl Writeable for OpenChannel {
3094 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3095 self.common_fields.chain_hash.write(w)?;
3096 self.common_fields.temporary_channel_id.write(w)?;
3097 self.common_fields.funding_satoshis.write(w)?;
3098 self.push_msat.write(w)?;
3099 self.common_fields.dust_limit_satoshis.write(w)?;
3100 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
3101 self.channel_reserve_satoshis.write(w)?;
3102 self.common_fields.htlc_minimum_msat.write(w)?;
3103 self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
3104 self.common_fields.to_self_delay.write(w)?;
3105 self.common_fields.max_accepted_htlcs.write(w)?;
3106 self.common_fields.funding_pubkey.write(w)?;
3107 self.common_fields.revocation_basepoint.write(w)?;
3108 self.common_fields.payment_basepoint.write(w)?;
3109 self.common_fields.delayed_payment_basepoint.write(w)?;
3110 self.common_fields.htlc_basepoint.write(w)?;
3111 self.common_fields.first_per_commitment_point.write(w)?;
3112 self.common_fields.channel_flags.write(w)?;
3113 encode_tlv_stream!(w, {
3114 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
3116 });
3117 Ok(())
3118 }
3119}
3120
3121impl LengthReadable for OpenChannel {
3122 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3123 let chain_hash: ChainHash = Readable::read(r)?;
3124 let temporary_channel_id: ChannelId = Readable::read(r)?;
3125 let funding_satoshis: u64 = Readable::read(r)?;
3126 let push_msat: u64 = Readable::read(r)?;
3127 let dust_limit_satoshis: u64 = Readable::read(r)?;
3128 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
3129 let channel_reserve_satoshis: u64 = Readable::read(r)?;
3130 let htlc_minimum_msat: u64 = Readable::read(r)?;
3131 let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3132 let to_self_delay: u16 = Readable::read(r)?;
3133 let max_accepted_htlcs: u16 = Readable::read(r)?;
3134 let funding_pubkey: PublicKey = Readable::read(r)?;
3135 let revocation_basepoint: PublicKey = Readable::read(r)?;
3136 let payment_basepoint: PublicKey = Readable::read(r)?;
3137 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
3138 let htlc_basepoint: PublicKey = Readable::read(r)?;
3139 let first_per_commitment_point: PublicKey = Readable::read(r)?;
3140 let channel_flags: u8 = Readable::read(r)?;
3141
3142 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
3143 let mut channel_type: Option<ChannelTypeFeatures> = None;
3144 decode_tlv_stream!(r, {
3145 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
3146 (1, channel_type, option),
3147 });
3148 Ok(OpenChannel {
3149 common_fields: CommonOpenChannelFields {
3150 chain_hash,
3151 temporary_channel_id,
3152 funding_satoshis,
3153 dust_limit_satoshis,
3154 max_htlc_value_in_flight_msat,
3155 htlc_minimum_msat,
3156 commitment_feerate_sat_per_1000_weight,
3157 to_self_delay,
3158 max_accepted_htlcs,
3159 funding_pubkey,
3160 revocation_basepoint,
3161 payment_basepoint,
3162 delayed_payment_basepoint,
3163 htlc_basepoint,
3164 first_per_commitment_point,
3165 channel_flags,
3166 shutdown_scriptpubkey,
3167 channel_type,
3168 },
3169 push_msat,
3170 channel_reserve_satoshis,
3171 })
3172 }
3173}
3174
3175impl Writeable for OpenChannelV2 {
3176 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3177 self.common_fields.chain_hash.write(w)?;
3178 self.common_fields.temporary_channel_id.write(w)?;
3179 self.funding_feerate_sat_per_1000_weight.write(w)?;
3180 self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
3181 self.common_fields.funding_satoshis.write(w)?;
3182 self.common_fields.dust_limit_satoshis.write(w)?;
3183 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
3184 self.common_fields.htlc_minimum_msat.write(w)?;
3185 self.common_fields.to_self_delay.write(w)?;
3186 self.common_fields.max_accepted_htlcs.write(w)?;
3187 self.locktime.write(w)?;
3188 self.common_fields.funding_pubkey.write(w)?;
3189 self.common_fields.revocation_basepoint.write(w)?;
3190 self.common_fields.payment_basepoint.write(w)?;
3191 self.common_fields.delayed_payment_basepoint.write(w)?;
3192 self.common_fields.htlc_basepoint.write(w)?;
3193 self.common_fields.first_per_commitment_point.write(w)?;
3194 self.second_per_commitment_point.write(w)?;
3195 self.common_fields.channel_flags.write(w)?;
3196 encode_tlv_stream!(w, {
3197 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
3199 (2, self.require_confirmed_inputs, option),
3200 });
3201 Ok(())
3202 }
3203}
3204
3205impl LengthReadable for OpenChannelV2 {
3206 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3207 let chain_hash: ChainHash = Readable::read(r)?;
3208 let temporary_channel_id: ChannelId = Readable::read(r)?;
3209 let funding_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3210 let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3211 let funding_satoshis: u64 = Readable::read(r)?;
3212 let dust_limit_satoshis: u64 = Readable::read(r)?;
3213 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
3214 let htlc_minimum_msat: u64 = Readable::read(r)?;
3215 let to_self_delay: u16 = Readable::read(r)?;
3216 let max_accepted_htlcs: u16 = Readable::read(r)?;
3217 let locktime: u32 = Readable::read(r)?;
3218 let funding_pubkey: PublicKey = Readable::read(r)?;
3219 let revocation_basepoint: PublicKey = Readable::read(r)?;
3220 let payment_basepoint: PublicKey = Readable::read(r)?;
3221 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
3222 let htlc_basepoint: PublicKey = Readable::read(r)?;
3223 let first_per_commitment_point: PublicKey = Readable::read(r)?;
3224 let second_per_commitment_point: PublicKey = Readable::read(r)?;
3225 let channel_flags: u8 = Readable::read(r)?;
3226
3227 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
3228 let mut channel_type: Option<ChannelTypeFeatures> = None;
3229 let mut require_confirmed_inputs: Option<()> = None;
3230 decode_tlv_stream!(r, {
3231 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
3232 (1, channel_type, option),
3233 (2, require_confirmed_inputs, option),
3234 });
3235 Ok(OpenChannelV2 {
3236 common_fields: CommonOpenChannelFields {
3237 chain_hash,
3238 temporary_channel_id,
3239 funding_satoshis,
3240 dust_limit_satoshis,
3241 max_htlc_value_in_flight_msat,
3242 htlc_minimum_msat,
3243 commitment_feerate_sat_per_1000_weight,
3244 to_self_delay,
3245 max_accepted_htlcs,
3246 funding_pubkey,
3247 revocation_basepoint,
3248 payment_basepoint,
3249 delayed_payment_basepoint,
3250 htlc_basepoint,
3251 first_per_commitment_point,
3252 channel_flags,
3253 shutdown_scriptpubkey,
3254 channel_type,
3255 },
3256 funding_feerate_sat_per_1000_weight,
3257 locktime,
3258 second_per_commitment_point,
3259 require_confirmed_inputs,
3260 })
3261 }
3262}
3263
3264#[cfg(not(taproot))]
3265impl_writeable_msg!(RevokeAndACK, {
3266 channel_id,
3267 per_commitment_secret,
3268 next_per_commitment_point
3269}, {
3270 (75537, release_htlc_message_paths, optional_vec)
3271});
3272
3273#[cfg(taproot)]
3274impl_writeable_msg!(RevokeAndACK, {
3275 channel_id,
3276 per_commitment_secret,
3277 next_per_commitment_point
3278}, {
3279 (4, next_local_nonce, option),
3280 (75537, release_htlc_message_paths, optional_vec)
3281});
3282
3283impl_writeable_msg!(Shutdown, {
3284 channel_id,
3285 scriptpubkey
3286}, {});
3287
3288impl_writeable_msg!(UpdateFailHTLC, {
3289 channel_id,
3290 htlc_id,
3291 reason
3292}, {
3293 (1, attribution_data, option)
3294});
3295
3296impl_writeable_msg!(UpdateFailMalformedHTLC, {
3297 channel_id,
3298 htlc_id,
3299 sha256_of_onion,
3300 failure_code
3301}, {});
3302
3303impl_writeable_msg!(UpdateFee, {
3304 channel_id,
3305 feerate_per_kw
3306}, {});
3307
3308impl_writeable_msg!(UpdateFulfillHTLC, {
3309 channel_id,
3310 htlc_id,
3311 payment_preimage
3312}, {
3313 (1, attribution_data, option)
3314});
3315
3316impl_writeable_msg!(PeerStorage, { data }, {});
3317
3318impl_writeable_msg!(PeerStorageRetrieval, { data }, {});
3319
3320impl_writeable_msg!(StartBatch, {
3321 channel_id,
3322 batch_size
3323}, {
3324 (1, message_type, option)
3325});
3326
3327impl Writeable for OnionPacket {
3331 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3332 self.version.write(w)?;
3333 match self.public_key {
3334 Ok(pubkey) => pubkey.write(w)?,
3335 Err(_) => [0u8; 33].write(w)?,
3336 }
3337 w.write_all(&self.hop_data)?;
3338 self.hmac.write(w)?;
3339 Ok(())
3340 }
3341}
3342
3343impl Readable for OnionPacket {
3344 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3345 Ok(OnionPacket {
3346 version: Readable::read(r)?,
3347 public_key: {
3348 let mut buf = [0u8; 33];
3349 r.read_exact(&mut buf)?;
3350 PublicKey::from_slice(&buf)
3351 },
3352 hop_data: Readable::read(r)?,
3353 hmac: Readable::read(r)?,
3354 })
3355 }
3356}
3357
3358impl_writeable_msg!(UpdateAddHTLC, {
3359 channel_id,
3360 htlc_id,
3361 amount_msat,
3362 payment_hash,
3363 cltv_expiry,
3364 onion_routing_packet,
3365}, {
3366 (0, blinding_point, option),
3367 (65537, skimmed_fee_msat, option),
3368 (75537, hold_htlc, option),
3371});
3372
3373impl LengthReadable for OnionMessage {
3374 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3375 let blinding_point: PublicKey = Readable::read(r)?;
3376 let len: u16 = Readable::read(r)?;
3377 let mut packet_reader = FixedLengthReader::new(r, len as u64);
3378 let onion_routing_packet: onion_message::packet::Packet =
3379 <onion_message::packet::Packet as LengthReadable>::read_from_fixed_length_buffer(
3380 &mut packet_reader,
3381 )?;
3382 Ok(Self { blinding_point, onion_routing_packet })
3383 }
3384}
3385
3386impl Writeable for OnionMessage {
3387 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3388 self.blinding_point.write(w)?;
3389 let onion_packet_len = self.onion_routing_packet.serialized_length();
3390 (onion_packet_len as u16).write(w)?;
3391 self.onion_routing_packet.write(w)?;
3392 Ok(())
3393 }
3394}
3395
3396impl Writeable for FinalOnionHopData {
3397 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3398 self.payment_secret.0.write(w)?;
3399 HighZeroBytesDroppedBigSize(self.total_msat).write(w)
3400 }
3401}
3402
3403impl Readable for FinalOnionHopData {
3404 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3405 let secret: [u8; 32] = Readable::read(r)?;
3406 let amt: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
3407 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
3408 }
3409}
3410
3411impl<'a> Writeable for OutboundOnionPayload<'a> {
3412 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3413 match self {
3414 Self::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } => {
3415 _encode_varint_length_prefixed_tlv!(w, {
3416 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3417 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3418 (6, short_channel_id, required)
3419 });
3420 },
3421 Self::TrampolineEntrypoint {
3422 amt_to_forward,
3423 outgoing_cltv_value,
3424 ref multipath_trampoline_data,
3425 ref trampoline_packet,
3426 } => {
3427 _encode_varint_length_prefixed_tlv!(w, {
3428 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3429 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3430 (8, multipath_trampoline_data, option),
3431 (20, trampoline_packet, required)
3432 });
3433 },
3434 Self::BlindedTrampolineEntrypoint {
3435 amt_to_forward,
3436 outgoing_cltv_value,
3437 current_path_key,
3438 ref multipath_trampoline_data,
3439 ref trampoline_packet,
3440 } => {
3441 _encode_varint_length_prefixed_tlv!(w, {
3442 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3443 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3444 (8, multipath_trampoline_data, option),
3445 (12, current_path_key, required),
3446 (20, trampoline_packet, required)
3447 });
3448 },
3449 Self::Receive {
3450 ref payment_data,
3451 ref payment_metadata,
3452 ref keysend_preimage,
3453 sender_intended_htlc_amt_msat,
3454 cltv_expiry_height,
3455 ref custom_tlvs,
3456 } => {
3457 let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
3461 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> =
3462 custom_tlvs.iter().chain(keysend_tlv.iter()).collect();
3463 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
3464 _encode_varint_length_prefixed_tlv!(w, {
3465 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3466 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3467 (8, payment_data, option),
3468 (16, payment_metadata.map(|m| WithoutLength(m)), option)
3469 }, custom_tlvs.iter());
3470 },
3471 Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
3472 _encode_varint_length_prefixed_tlv!(w, {
3473 (10, *encrypted_tlvs, required_vec),
3474 (12, intro_node_blinding_point, option)
3475 });
3476 },
3477 Self::BlindedReceive {
3478 sender_intended_htlc_amt_msat,
3479 total_msat,
3480 cltv_expiry_height,
3481 encrypted_tlvs,
3482 intro_node_blinding_point,
3483 keysend_preimage,
3484 ref invoice_request,
3485 ref custom_tlvs,
3486 } => {
3487 let invoice_request_tlv = invoice_request.map(|invreq| (77_777, invreq.encode())); let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
3492 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> = custom_tlvs
3493 .iter()
3494 .chain(invoice_request_tlv.iter())
3495 .chain(keysend_tlv.iter())
3496 .collect();
3497 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
3498 _encode_varint_length_prefixed_tlv!(w, {
3499 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3500 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3501 (10, *encrypted_tlvs, required_vec),
3502 (12, intro_node_blinding_point, option),
3503 (18, HighZeroBytesDroppedBigSize(*total_msat), required)
3504 }, custom_tlvs.iter());
3505 },
3506 }
3507 Ok(())
3508 }
3509}
3510
3511impl<'a> Writeable for OutboundTrampolinePayload<'a> {
3512 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3513 match self {
3514 Self::Forward { amt_to_forward, outgoing_cltv_value, outgoing_node_id } => {
3515 _encode_varint_length_prefixed_tlv!(w, {
3516 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3517 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3518 (14, outgoing_node_id, required)
3519 });
3520 },
3521 #[cfg(test)]
3522 Self::Receive {
3523 ref payment_data,
3524 sender_intended_htlc_amt_msat,
3525 cltv_expiry_height,
3526 } => {
3527 _encode_varint_length_prefixed_tlv!(w, {
3528 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3529 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3530 (8, payment_data, option)
3531 });
3532 },
3533 Self::LegacyBlindedPathEntry {
3534 amt_to_forward,
3535 outgoing_cltv_value,
3536 payment_paths,
3537 invoice_features,
3538 } => {
3539 let mut blinded_path_serialization = [0u8; 2048]; let serialization_length = {
3541 let buffer_size = blinded_path_serialization.len();
3542 let mut blinded_path_slice = &mut blinded_path_serialization[..];
3543 for current_payment_path in payment_paths {
3544 current_payment_path.inner_blinded_path().write(&mut blinded_path_slice)?;
3545 current_payment_path.payinfo.write(&mut blinded_path_slice)?;
3546 }
3547 buffer_size - blinded_path_slice.len()
3548 };
3549 let blinded_path_serialization =
3550 &blinded_path_serialization[..serialization_length];
3551 _encode_varint_length_prefixed_tlv!(w, {
3552 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3553 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3554 (21, invoice_features.as_ref().map(|m| WithoutLength(m)), option),
3555 (22, WithoutLength(blinded_path_serialization), required)
3556 });
3557 },
3558 Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
3559 _encode_varint_length_prefixed_tlv!(w, {
3560 (10, *encrypted_tlvs, required_vec),
3561 (12, intro_node_blinding_point, option)
3562 });
3563 },
3564 Self::BlindedReceive {
3565 sender_intended_htlc_amt_msat,
3566 total_msat,
3567 cltv_expiry_height,
3568 encrypted_tlvs,
3569 intro_node_blinding_point,
3570 keysend_preimage,
3571 custom_tlvs,
3572 } => {
3573 _encode_varint_length_prefixed_tlv!(w, {
3574 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3575 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3576 (10, *encrypted_tlvs, required_vec),
3577 (12, intro_node_blinding_point, option),
3578 (18, HighZeroBytesDroppedBigSize(*total_msat), required),
3579 (20, keysend_preimage, option)
3580 }, custom_tlvs.iter());
3581 },
3582 }
3583 Ok(())
3584 }
3585}
3586
3587impl<NS: Deref> ReadableArgs<(Option<PublicKey>, NS)> for InboundOnionPayload
3588where
3589 NS::Target: NodeSigner,
3590{
3591 fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
3592 let (update_add_blinding_point, node_signer) = args;
3593
3594 let mut amt = None;
3595 let mut cltv_value = None;
3596 let mut short_id: Option<u64> = None;
3597 let mut payment_data: Option<FinalOnionHopData> = None;
3598 let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
3599 let mut intro_node_blinding_point = None;
3600 let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
3601 let mut total_msat = None;
3602 let mut keysend_preimage: Option<PaymentPreimage> = None;
3603 let mut trampoline_onion_packet: Option<TrampolineOnionPacket> = None;
3604 let mut invoice_request: Option<InvoiceRequest> = None;
3605 let mut custom_tlvs = Vec::new();
3606
3607 let tlv_len = BigSize::read(r)?;
3608 let mut rd = FixedLengthReader::new(r, tlv_len.0);
3609
3610 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
3611 (2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3612 (4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
3613 (6, short_id, option),
3614 (8, payment_data, option),
3615 (10, encrypted_tlvs_opt, option),
3616 (12, intro_node_blinding_point, option),
3617 (16, payment_metadata, option),
3618 (18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3619 (20, trampoline_onion_packet, option),
3620 (77_777, invoice_request, option),
3621 (5482373484, keysend_preimage, option)
3623 }, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
3624 if msg_type < 1 << 16 { return Ok(false) }
3625 let mut value = Vec::new();
3626 msg_reader.read_to_limit(&mut value, u64::MAX)?;
3627 custom_tlvs.push((msg_type, value));
3628 Ok(true)
3629 });
3630
3631 if amt.unwrap_or(0) > MAX_VALUE_MSAT {
3632 return Err(DecodeError::InvalidValue);
3633 }
3634 if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
3635 return Err(DecodeError::InvalidValue);
3636 }
3637
3638 if let Some(trampoline_onion_packet) = trampoline_onion_packet {
3639 if payment_metadata.is_some() || encrypted_tlvs_opt.is_some() || total_msat.is_some() {
3640 return Err(DecodeError::InvalidValue);
3641 }
3642 return Ok(Self::TrampolineEntrypoint(InboundTrampolineEntrypointPayload {
3643 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3644 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3645 multipath_trampoline_data: payment_data,
3646 trampoline_packet: trampoline_onion_packet,
3647 current_path_key: intro_node_blinding_point,
3648 }));
3649 }
3650
3651 if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
3652 if short_id.is_some() || payment_data.is_some() || payment_metadata.is_some() {
3653 return Err(DecodeError::InvalidValue);
3654 }
3655 let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
3656 let enc_tlvs_ss = node_signer
3657 .ecdh(Recipient::Node, &blinding_point, None)
3658 .map_err(|_| DecodeError::InvalidValue)?;
3659 let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
3660 let mut s = Cursor::new(&enc_tlvs);
3661 let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
3662 match ChaChaPolyReadAdapter::read(&mut reader, rho)? {
3663 ChaChaPolyReadAdapter {
3664 readable:
3665 BlindedPaymentTlvs::Forward(ForwardTlvs {
3666 short_channel_id,
3667 payment_relay,
3668 payment_constraints,
3669 features,
3670 next_blinding_override,
3671 }),
3672 } => {
3673 if amt.is_some()
3674 || cltv_value.is_some() || total_msat.is_some()
3675 || keysend_preimage.is_some()
3676 || invoice_request.is_some()
3677 {
3678 return Err(DecodeError::InvalidValue);
3679 }
3680 Ok(Self::BlindedForward(InboundOnionBlindedForwardPayload {
3681 short_channel_id,
3682 payment_relay,
3683 payment_constraints,
3684 features,
3685 intro_node_blinding_point,
3686 next_blinding_override,
3687 }))
3688 },
3689 ChaChaPolyReadAdapter { readable: BlindedPaymentTlvs::Receive(receive_tlvs) } => {
3690 let ReceiveTlvs { tlvs, authentication: (hmac, nonce) } = receive_tlvs;
3691 let expanded_key = node_signer.get_expanded_key();
3692 if tlvs.verify_for_offer_payment(hmac, nonce, &expanded_key).is_err() {
3693 return Err(DecodeError::InvalidValue);
3694 }
3695
3696 let UnauthenticatedReceiveTlvs {
3697 payment_secret,
3698 payment_constraints,
3699 payment_context,
3700 } = tlvs;
3701 if total_msat.unwrap_or(0) > MAX_VALUE_MSAT {
3702 return Err(DecodeError::InvalidValue);
3703 }
3704 Ok(Self::BlindedReceive(InboundOnionBlindedReceivePayload {
3705 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3706 total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
3707 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3708 payment_secret,
3709 payment_constraints,
3710 payment_context,
3711 intro_node_blinding_point,
3712 keysend_preimage,
3713 invoice_request,
3714 custom_tlvs,
3715 }))
3716 },
3717 }
3718 } else if let Some(short_channel_id) = short_id {
3719 if payment_data.is_some()
3720 || payment_metadata.is_some()
3721 || encrypted_tlvs_opt.is_some()
3722 || total_msat.is_some()
3723 || invoice_request.is_some()
3724 {
3725 return Err(DecodeError::InvalidValue);
3726 }
3727 Ok(Self::Forward(InboundOnionForwardPayload {
3728 short_channel_id,
3729 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3730 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3731 }))
3732 } else {
3733 if encrypted_tlvs_opt.is_some() || total_msat.is_some() || invoice_request.is_some() {
3734 return Err(DecodeError::InvalidValue);
3735 }
3736 if let Some(data) = &payment_data {
3737 if data.total_msat > MAX_VALUE_MSAT {
3738 return Err(DecodeError::InvalidValue);
3739 }
3740 }
3741 Ok(Self::Receive(InboundOnionReceivePayload {
3742 payment_data,
3743 payment_metadata: payment_metadata.map(|w| w.0),
3744 keysend_preimage,
3745 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3746 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3747 custom_tlvs,
3748 }))
3749 }
3750 }
3751}
3752
3753impl<NS: Deref> ReadableArgs<(Option<PublicKey>, NS)> for InboundTrampolinePayload
3754where
3755 NS::Target: NodeSigner,
3756{
3757 fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
3758 let (update_add_blinding_point, node_signer) = args;
3759
3760 let mut amt = None;
3761 let mut cltv_value = None;
3762 let mut payment_data: Option<FinalOnionHopData> = None;
3763 let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
3764 let mut intro_node_blinding_point = None;
3765 let mut next_trampoline: Option<PublicKey> = None;
3766 let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
3767 let mut total_msat = None;
3768 let mut keysend_preimage: Option<PaymentPreimage> = None;
3769 let mut invoice_request: Option<InvoiceRequest> = None;
3770 let mut custom_tlvs = Vec::new();
3771
3772 let tlv_len = BigSize::read(r)?;
3773 let mut rd = FixedLengthReader::new(r, tlv_len.0);
3774 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
3775 (2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3776 (4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
3777 (8, payment_data, option),
3778 (10, encrypted_tlvs_opt, option),
3779 (12, intro_node_blinding_point, option),
3780 (14, next_trampoline, option),
3781 (16, payment_metadata, option),
3782 (18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3783 (77_777, invoice_request, option),
3784 (5482373484, keysend_preimage, option)
3786 }, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
3787 if msg_type < 1 << 16 { return Ok(false) }
3788 let mut value = Vec::new();
3789 msg_reader.read_to_limit(&mut value, u64::MAX)?;
3790 custom_tlvs.push((msg_type, value));
3791 Ok(true)
3792 });
3793
3794 if amt.unwrap_or(0) > MAX_VALUE_MSAT {
3795 return Err(DecodeError::InvalidValue);
3796 }
3797 if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
3798 return Err(DecodeError::InvalidValue);
3799 }
3800
3801 if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
3802 if next_trampoline.is_some() || payment_data.is_some() || payment_metadata.is_some() {
3803 return Err(DecodeError::InvalidValue);
3804 }
3805 let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
3806 let enc_tlvs_ss = node_signer
3807 .ecdh(Recipient::Node, &blinding_point, None)
3808 .map_err(|_| DecodeError::InvalidValue)?;
3809 let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
3810 let mut s = Cursor::new(&enc_tlvs);
3811 let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
3812 match ChaChaPolyReadAdapter::read(&mut reader, rho)? {
3813 ChaChaPolyReadAdapter {
3814 readable:
3815 BlindedTrampolineTlvs::Forward(TrampolineForwardTlvs {
3816 next_trampoline,
3817 payment_relay,
3818 payment_constraints,
3819 features,
3820 next_blinding_override,
3821 }),
3822 } => {
3823 if amt.is_some()
3824 || cltv_value.is_some() || total_msat.is_some()
3825 || keysend_preimage.is_some()
3826 || invoice_request.is_some()
3827 {
3828 return Err(DecodeError::InvalidValue);
3829 }
3830 Ok(Self::BlindedForward(InboundTrampolineBlindedForwardPayload {
3831 next_trampoline,
3832 payment_relay,
3833 payment_constraints,
3834 features,
3835 intro_node_blinding_point,
3836 next_blinding_override,
3837 }))
3838 },
3839 ChaChaPolyReadAdapter {
3840 readable: BlindedTrampolineTlvs::Receive(receive_tlvs),
3841 } => {
3842 let ReceiveTlvs { tlvs, authentication: (hmac, nonce) } = receive_tlvs;
3843 let expanded_key = node_signer.get_expanded_key();
3844 if tlvs.verify_for_offer_payment(hmac, nonce, &expanded_key).is_err() {
3845 return Err(DecodeError::InvalidValue);
3846 }
3847
3848 let UnauthenticatedReceiveTlvs {
3849 payment_secret,
3850 payment_constraints,
3851 payment_context,
3852 } = tlvs;
3853 if total_msat.unwrap_or(0) > MAX_VALUE_MSAT {
3854 return Err(DecodeError::InvalidValue);
3855 }
3856 Ok(Self::BlindedReceive(InboundOnionBlindedReceivePayload {
3857 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3858 total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
3859 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3860 payment_secret,
3861 payment_constraints,
3862 payment_context,
3863 intro_node_blinding_point,
3864 keysend_preimage,
3865 invoice_request,
3866 custom_tlvs,
3867 }))
3868 },
3869 }
3870 } else if let Some(next_trampoline) = next_trampoline {
3871 if payment_data.is_some()
3872 || payment_metadata.is_some()
3873 || encrypted_tlvs_opt.is_some()
3874 || total_msat.is_some()
3875 || invoice_request.is_some()
3876 {
3877 return Err(DecodeError::InvalidValue);
3878 }
3879 Ok(Self::Forward(InboundTrampolineForwardPayload {
3880 next_trampoline,
3881 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3882 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3883 }))
3884 } else {
3885 if encrypted_tlvs_opt.is_some() || total_msat.is_some() || invoice_request.is_some() {
3886 return Err(DecodeError::InvalidValue);
3887 }
3888 if let Some(data) = &payment_data {
3889 if data.total_msat > MAX_VALUE_MSAT {
3890 return Err(DecodeError::InvalidValue);
3891 }
3892 }
3893 Ok(Self::Receive(InboundOnionReceivePayload {
3894 payment_data,
3895 payment_metadata: payment_metadata.map(|w| w.0),
3896 keysend_preimage,
3897 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3898 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3899 custom_tlvs,
3900 }))
3901 }
3902 }
3903}
3904
3905impl Writeable for Ping {
3906 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3907 self.ponglen.write(w)?;
3908 vec![0u8; self.byteslen as usize].write(w)?; Ok(())
3910 }
3911}
3912
3913impl LengthReadable for Ping {
3914 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3915 Ok(Ping {
3916 ponglen: Readable::read(r)?,
3917 byteslen: {
3918 let byteslen = Readable::read(r)?;
3919 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
3920 byteslen
3921 },
3922 })
3923 }
3924}
3925
3926impl Writeable for Pong {
3927 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3928 vec![0u8; self.byteslen as usize].write(w)?; Ok(())
3930 }
3931}
3932
3933impl LengthReadable for Pong {
3934 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3935 Ok(Pong {
3936 byteslen: {
3937 let byteslen = Readable::read(r)?;
3938 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
3939 byteslen
3940 },
3941 })
3942 }
3943}
3944
3945impl Writeable for UnsignedChannelAnnouncement {
3946 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3947 self.features.write(w)?;
3948 self.chain_hash.write(w)?;
3949 self.short_channel_id.write(w)?;
3950 self.node_id_1.write(w)?;
3951 self.node_id_2.write(w)?;
3952 self.bitcoin_key_1.write(w)?;
3953 self.bitcoin_key_2.write(w)?;
3954 w.write_all(&self.excess_data[..])?;
3955 Ok(())
3956 }
3957}
3958
3959impl LengthReadable for UnsignedChannelAnnouncement {
3960 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3961 Ok(Self {
3962 features: Readable::read(r)?,
3963 chain_hash: Readable::read(r)?,
3964 short_channel_id: Readable::read(r)?,
3965 node_id_1: Readable::read(r)?,
3966 node_id_2: Readable::read(r)?,
3967 bitcoin_key_1: Readable::read(r)?,
3968 bitcoin_key_2: Readable::read(r)?,
3969 excess_data: read_to_end(r)?,
3970 })
3971 }
3972}
3973
3974impl Writeable for ChannelAnnouncement {
3975 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3976 self.node_signature_1.write(w)?;
3977 self.node_signature_2.write(w)?;
3978 self.bitcoin_signature_1.write(w)?;
3979 self.bitcoin_signature_2.write(w)?;
3980 self.contents.write(w)?;
3981 Ok(())
3982 }
3983}
3984
3985impl LengthReadable for ChannelAnnouncement {
3986 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3987 Ok(Self {
3988 node_signature_1: Readable::read(r)?,
3989 node_signature_2: Readable::read(r)?,
3990 bitcoin_signature_1: Readable::read(r)?,
3991 bitcoin_signature_2: Readable::read(r)?,
3992 contents: LengthReadable::read_from_fixed_length_buffer(r)?,
3993 })
3994 }
3995}
3996
3997impl Writeable for UnsignedChannelUpdate {
3998 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3999 self.chain_hash.write(w)?;
4000 self.short_channel_id.write(w)?;
4001 self.timestamp.write(w)?;
4002 (self.message_flags | 1).write(w)?;
4005 self.channel_flags.write(w)?;
4006 self.cltv_expiry_delta.write(w)?;
4007 self.htlc_minimum_msat.write(w)?;
4008 self.fee_base_msat.write(w)?;
4009 self.fee_proportional_millionths.write(w)?;
4010 self.htlc_maximum_msat.write(w)?;
4011 w.write_all(&self.excess_data[..])?;
4012 Ok(())
4013 }
4014}
4015
4016impl LengthReadable for UnsignedChannelUpdate {
4017 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4018 let res = Self {
4019 chain_hash: Readable::read(r)?,
4020 short_channel_id: Readable::read(r)?,
4021 timestamp: Readable::read(r)?,
4022 message_flags: Readable::read(r)?,
4023 channel_flags: Readable::read(r)?,
4024 cltv_expiry_delta: Readable::read(r)?,
4025 htlc_minimum_msat: Readable::read(r)?,
4026 fee_base_msat: Readable::read(r)?,
4027 fee_proportional_millionths: Readable::read(r)?,
4028 htlc_maximum_msat: Readable::read(r)?,
4029 excess_data: read_to_end(r)?,
4030 };
4031 if res.message_flags & 1 != 1 {
4032 Err(DecodeError::InvalidValue)
4035 } else {
4036 Ok(res)
4037 }
4038 }
4039}
4040
4041impl Writeable for ChannelUpdate {
4042 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4043 self.signature.write(w)?;
4044 self.contents.write(w)?;
4045 Ok(())
4046 }
4047}
4048
4049impl LengthReadable for ChannelUpdate {
4050 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4051 Ok(Self {
4052 signature: Readable::read(r)?,
4053 contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4054 })
4055 }
4056}
4057
4058impl Writeable for ErrorMessage {
4059 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4060 self.channel_id.write(w)?;
4061 (self.data.len() as u16).write(w)?;
4062 w.write_all(self.data.as_bytes())?;
4063 Ok(())
4064 }
4065}
4066
4067impl LengthReadable for ErrorMessage {
4068 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4069 Ok(Self {
4070 channel_id: Readable::read(r)?,
4071 data: {
4072 let sz: usize = <u16 as Readable>::read(r)? as usize;
4073 let mut data = Vec::with_capacity(sz);
4074 data.resize(sz, 0);
4075 r.read_exact(&mut data)?;
4076 match String::from_utf8(data) {
4077 Ok(s) => s,
4078 Err(_) => return Err(DecodeError::InvalidValue),
4079 }
4080 },
4081 })
4082 }
4083}
4084
4085impl Writeable for WarningMessage {
4086 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4087 self.channel_id.write(w)?;
4088 (self.data.len() as u16).write(w)?;
4089 w.write_all(self.data.as_bytes())?;
4090 Ok(())
4091 }
4092}
4093
4094impl LengthReadable for WarningMessage {
4095 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4096 Ok(Self {
4097 channel_id: Readable::read(r)?,
4098 data: {
4099 let sz: usize = <u16 as Readable>::read(r)? as usize;
4100 let mut data = Vec::with_capacity(sz);
4101 data.resize(sz, 0);
4102 r.read_exact(&mut data)?;
4103 match String::from_utf8(data) {
4104 Ok(s) => s,
4105 Err(_) => return Err(DecodeError::InvalidValue),
4106 }
4107 },
4108 })
4109 }
4110}
4111
4112impl Writeable for UnsignedNodeAnnouncement {
4113 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4114 self.features.write(w)?;
4115 self.timestamp.write(w)?;
4116 self.node_id.write(w)?;
4117 w.write_all(&self.rgb)?;
4118 self.alias.write(w)?;
4119
4120 let mut addr_len = 0;
4121 for addr in self.addresses.iter() {
4122 addr_len += 1 + addr.len();
4123 }
4124 (addr_len + self.excess_address_data.len() as u16).write(w)?;
4125 for addr in self.addresses.iter() {
4126 addr.write(w)?;
4127 }
4128 w.write_all(&self.excess_address_data[..])?;
4129 w.write_all(&self.excess_data[..])?;
4130 Ok(())
4131 }
4132}
4133
4134impl LengthReadable for UnsignedNodeAnnouncement {
4135 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4136 let features: NodeFeatures = Readable::read(r)?;
4137 let timestamp: u32 = Readable::read(r)?;
4138 let node_id: NodeId = Readable::read(r)?;
4139 let mut rgb = [0; 3];
4140 r.read_exact(&mut rgb)?;
4141 let alias: NodeAlias = Readable::read(r)?;
4142
4143 let addr_len: u16 = Readable::read(r)?;
4144 let mut addresses: Vec<SocketAddress> = Vec::new();
4145 let mut addr_readpos = 0;
4146 let mut excess = false;
4147 let mut excess_byte = 0;
4148 loop {
4149 if addr_len <= addr_readpos {
4150 break;
4151 }
4152 match Readable::read(r) {
4153 Ok(Ok(addr)) => {
4154 if addr_len < addr_readpos + 1 + addr.len() {
4155 return Err(DecodeError::BadLengthDescriptor);
4156 }
4157 addr_readpos += (1 + addr.len()) as u16;
4158 addresses.push(addr);
4159 },
4160 Ok(Err(unknown_descriptor)) => {
4161 excess = true;
4162 excess_byte = unknown_descriptor;
4163 break;
4164 },
4165 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
4166 Err(e) => return Err(e),
4167 }
4168 }
4169
4170 let mut excess_data = vec![];
4171 let excess_address_data = if addr_readpos < addr_len {
4172 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
4173 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
4174 if excess {
4175 excess_address_data[0] = excess_byte;
4176 }
4177 excess_address_data
4178 } else {
4179 if excess {
4180 excess_data.push(excess_byte);
4181 }
4182 Vec::new()
4183 };
4184 excess_data.extend(read_to_end(r)?.iter());
4185 Ok(UnsignedNodeAnnouncement {
4186 features,
4187 timestamp,
4188 node_id,
4189 rgb,
4190 alias,
4191 addresses,
4192 excess_address_data,
4193 excess_data,
4194 })
4195 }
4196}
4197
4198impl Writeable for NodeAnnouncement {
4199 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4200 self.signature.write(w)?;
4201 self.contents.write(w)?;
4202 Ok(())
4203 }
4204}
4205
4206impl LengthReadable for NodeAnnouncement {
4207 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4208 Ok(Self {
4209 signature: Readable::read(r)?,
4210 contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4211 })
4212 }
4213}
4214
4215impl LengthReadable for QueryShortChannelIds {
4216 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4217 let chain_hash: ChainHash = Readable::read(r)?;
4218
4219 let encoding_len: u16 = Readable::read(r)?;
4220 let encoding_type: u8 = Readable::read(r)?;
4221
4222 if encoding_type != EncodingType::Uncompressed as u8 {
4225 return Err(DecodeError::UnsupportedCompression);
4226 }
4227
4228 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
4231 return Err(DecodeError::InvalidValue);
4232 }
4233
4234 let short_channel_id_count: u16 = (encoding_len - 1) / 8;
4237 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
4238 for _ in 0..short_channel_id_count {
4239 short_channel_ids.push(Readable::read(r)?);
4240 }
4241
4242 Ok(QueryShortChannelIds { chain_hash, short_channel_ids })
4243 }
4244}
4245
4246impl Writeable for QueryShortChannelIds {
4247 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4248 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
4250
4251 self.chain_hash.write(w)?;
4252 encoding_len.write(w)?;
4253
4254 (EncodingType::Uncompressed as u8).write(w)?;
4256
4257 for scid in self.short_channel_ids.iter() {
4258 scid.write(w)?;
4259 }
4260
4261 Ok(())
4262 }
4263}
4264
4265impl_writeable_msg!(ReplyShortChannelIdsEnd, {
4266 chain_hash,
4267 full_information,
4268}, {});
4269
4270impl QueryChannelRange {
4271 pub fn end_blocknum(&self) -> u32 {
4275 match self.first_blocknum.checked_add(self.number_of_blocks) {
4276 Some(block) => block,
4277 None => u32::max_value(),
4278 }
4279 }
4280}
4281
4282impl_writeable_msg!(QueryChannelRange, {
4283 chain_hash,
4284 first_blocknum,
4285 number_of_blocks
4286}, {});
4287
4288impl LengthReadable for ReplyChannelRange {
4289 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4290 let chain_hash: ChainHash = Readable::read(r)?;
4291 let first_blocknum: u32 = Readable::read(r)?;
4292 let number_of_blocks: u32 = Readable::read(r)?;
4293 let sync_complete: bool = Readable::read(r)?;
4294
4295 let encoding_len: u16 = Readable::read(r)?;
4296 let encoding_type: u8 = Readable::read(r)?;
4297
4298 if encoding_type != EncodingType::Uncompressed as u8 {
4301 return Err(DecodeError::UnsupportedCompression);
4302 }
4303
4304 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
4307 return Err(DecodeError::InvalidValue);
4308 }
4309
4310 let short_channel_id_count: u16 = (encoding_len - 1) / 8;
4313 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
4314 for _ in 0..short_channel_id_count {
4315 short_channel_ids.push(Readable::read(r)?);
4316 }
4317
4318 Ok(ReplyChannelRange {
4319 chain_hash,
4320 first_blocknum,
4321 number_of_blocks,
4322 sync_complete,
4323 short_channel_ids,
4324 })
4325 }
4326}
4327
4328impl Writeable for ReplyChannelRange {
4329 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4330 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
4331 self.chain_hash.write(w)?;
4332 self.first_blocknum.write(w)?;
4333 self.number_of_blocks.write(w)?;
4334 self.sync_complete.write(w)?;
4335
4336 encoding_len.write(w)?;
4337 (EncodingType::Uncompressed as u8).write(w)?;
4338 for scid in self.short_channel_ids.iter() {
4339 scid.write(w)?;
4340 }
4341
4342 Ok(())
4343 }
4344}
4345
4346impl_writeable_msg!(GossipTimestampFilter, {
4347 chain_hash,
4348 first_timestamp,
4349 timestamp_range,
4350}, {});
4351
4352#[cfg(test)]
4353mod tests {
4354 use crate::ln::msgs::SocketAddress;
4355 use crate::ln::msgs::{
4356 self, CommonAcceptChannelFields, CommonOpenChannelFields, FinalOnionHopData,
4357 InboundOnionForwardPayload, InboundOnionReceivePayload, OutboundTrampolinePayload,
4358 TrampolineOnionPacket,
4359 };
4360 use crate::ln::onion_utils::{AttributionData, HMAC_COUNT, HMAC_LEN, HOLD_TIME_LEN, MAX_HOPS};
4361 use crate::ln::types::ChannelId;
4362 use crate::routing::gossip::{NodeAlias, NodeId};
4363 use crate::types::features::{
4364 ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures,
4365 };
4366 use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
4367 use crate::util::ser::{BigSize, Hostname, LengthReadable, Readable, ReadableArgs, Writeable};
4368 use crate::util::test_utils;
4369 use bitcoin::hex::DisplayHex;
4370 use bitcoin::{Amount, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness};
4371
4372 use bitcoin::address::Address;
4373 use bitcoin::constants::ChainHash;
4374 use bitcoin::hash_types::Txid;
4375 use bitcoin::hex::FromHex;
4376 use bitcoin::locktime::absolute::LockTime;
4377 use bitcoin::network::Network;
4378 use bitcoin::opcodes;
4379 use bitcoin::script::Builder;
4380 use bitcoin::transaction::Version;
4381
4382 use bitcoin::secp256k1::{Message, Secp256k1};
4383 use bitcoin::secp256k1::{PublicKey, SecretKey};
4384
4385 use crate::chain::transaction::OutPoint;
4386 use crate::io::{self, Cursor};
4387 use crate::prelude::*;
4388 use core::str::FromStr;
4389
4390 use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
4391 #[cfg(feature = "std")]
4392 use crate::ln::msgs::SocketAddressParseError;
4393 #[cfg(feature = "std")]
4394 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
4395 use types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
4396
4397 #[test]
4398 fn encoding_channel_reestablish() {
4399 let public_key = {
4400 let secp_ctx = Secp256k1::new();
4401 PublicKey::from_secret_key(
4402 &secp_ctx,
4403 &SecretKey::from_slice(
4404 &<Vec<u8>>::from_hex(
4405 "0101010101010101010101010101010101010101010101010101010101010101",
4406 )
4407 .unwrap()[..],
4408 )
4409 .unwrap(),
4410 )
4411 };
4412
4413 let cr = msgs::ChannelReestablish {
4414 channel_id: ChannelId::from_bytes([
4415 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,
4416 0, 0, 0, 0,
4417 ]),
4418 next_local_commitment_number: 3,
4419 next_remote_commitment_number: 4,
4420 your_last_per_commitment_secret: [9; 32],
4421 my_current_per_commitment_point: public_key,
4422 next_funding: None,
4423 my_current_funding_locked: None,
4424 };
4425
4426 let encoded_value = cr.encode();
4427 assert_eq!(
4428 encoded_value,
4429 vec![
4430 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,
4431 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,
4435 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4437 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4438 143, ]
4440 );
4441 }
4442
4443 #[test]
4444 fn encoding_channel_reestablish_with_next_funding_txid() {
4445 let public_key = {
4446 let secp_ctx = Secp256k1::new();
4447 PublicKey::from_secret_key(
4448 &secp_ctx,
4449 &SecretKey::from_slice(
4450 &<Vec<u8>>::from_hex(
4451 "0101010101010101010101010101010101010101010101010101010101010101",
4452 )
4453 .unwrap()[..],
4454 )
4455 .unwrap(),
4456 )
4457 };
4458
4459 let cr = msgs::ChannelReestablish {
4460 channel_id: ChannelId::from_bytes([
4461 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,
4462 0, 0, 0, 0,
4463 ]),
4464 next_local_commitment_number: 3,
4465 next_remote_commitment_number: 4,
4466 your_last_per_commitment_secret: [9; 32],
4467 my_current_per_commitment_point: public_key,
4468 next_funding: Some(msgs::NextFunding {
4469 txid: Txid::from_raw_hash(
4470 bitcoin::hashes::Hash::from_slice(&[
4471 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15,
4472 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
4473 ])
4474 .unwrap(),
4475 ),
4476 retransmit_flags: 1,
4477 }),
4478 my_current_funding_locked: None,
4479 };
4480
4481 let encoded_value = cr.encode();
4482 assert_eq!(
4483 encoded_value,
4484 vec![
4485 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,
4486 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,
4490 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4492 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4493 143, 1, 33, 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4,
4497 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, 1, ]
4499 );
4500 }
4501
4502 #[test]
4503 fn encoding_channel_reestablish_with_funding_locked_txid() {
4504 let public_key = {
4505 let secp_ctx = Secp256k1::new();
4506 PublicKey::from_secret_key(
4507 &secp_ctx,
4508 &SecretKey::from_slice(
4509 &<Vec<u8>>::from_hex(
4510 "0101010101010101010101010101010101010101010101010101010101010101",
4511 )
4512 .unwrap()[..],
4513 )
4514 .unwrap(),
4515 )
4516 };
4517
4518 let cr = msgs::ChannelReestablish {
4519 channel_id: ChannelId::from_bytes([
4520 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,
4521 0, 0, 0, 0,
4522 ]),
4523 next_local_commitment_number: 3,
4524 next_remote_commitment_number: 4,
4525 your_last_per_commitment_secret: [9; 32],
4526 my_current_per_commitment_point: public_key,
4527 next_funding: None,
4528 my_current_funding_locked: Some(msgs::FundingLocked {
4529 txid: Txid::from_raw_hash(
4530 bitcoin::hashes::Hash::from_slice(&[
4531 21, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15,
4532 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
4533 ])
4534 .unwrap(),
4535 ),
4536 retransmit_flags: 1,
4537 }),
4538 };
4539
4540 let encoded_value = cr.encode();
4541 assert_eq!(
4542 encoded_value,
4543 vec![
4544 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,
4545 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,
4549 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4551 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4552 143, 5, 33, 21, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4,
4556 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, 1, ]
4558 );
4559 }
4560
4561 macro_rules! get_keys_from {
4562 ($slice: expr, $secp_ctx: expr) => {{
4563 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex($slice).unwrap()[..]).unwrap();
4564 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
4565 (privkey, pubkey)
4566 }};
4567 }
4568
4569 macro_rules! get_sig_on {
4570 ($privkey: expr, $ctx: expr, $string: expr) => {{
4571 let sighash = Message::from_digest_slice(&$string.into_bytes()[..]).unwrap();
4572 $ctx.sign_ecdsa(&sighash, &$privkey)
4573 }};
4574 }
4575
4576 #[test]
4577 fn encoding_announcement_signatures() {
4578 let secp_ctx = Secp256k1::new();
4579 let (privkey, _) = get_keys_from!(
4580 "0101010101010101010101010101010101010101010101010101010101010101",
4581 secp_ctx
4582 );
4583 let sig_1 =
4584 get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
4585 let sig_2 =
4586 get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
4587 let announcement_signatures = msgs::AnnouncementSignatures {
4588 channel_id: ChannelId::from_bytes([
4589 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,
4590 0, 0, 0, 0,
4591 ]),
4592 short_channel_id: 2316138423780173,
4593 node_signature: sig_1,
4594 bitcoin_signature: sig_2,
4595 };
4596
4597 let encoded_value = announcement_signatures.encode();
4598 assert_eq!(encoded_value, <Vec<u8>>::from_hex("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
4599 }
4600
4601 fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
4602 let secp_ctx = Secp256k1::new();
4603 let (privkey_1, pubkey_1) = get_keys_from!(
4604 "0101010101010101010101010101010101010101010101010101010101010101",
4605 secp_ctx
4606 );
4607 let (privkey_2, pubkey_2) = get_keys_from!(
4608 "0202020202020202020202020202020202020202020202020202020202020202",
4609 secp_ctx
4610 );
4611 let (privkey_3, pubkey_3) = get_keys_from!(
4612 "0303030303030303030303030303030303030303030303030303030303030303",
4613 secp_ctx
4614 );
4615 let (privkey_4, pubkey_4) = get_keys_from!(
4616 "0404040404040404040404040404040404040404040404040404040404040404",
4617 secp_ctx
4618 );
4619 let sig_1 =
4620 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4621 let sig_2 =
4622 get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
4623 let sig_3 =
4624 get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
4625 let sig_4 =
4626 get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
4627 let mut features = ChannelFeatures::empty();
4628 if unknown_features_bits {
4629 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
4630 }
4631 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
4632 features,
4633 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4634 short_channel_id: 2316138423780173,
4635 node_id_1: NodeId::from_pubkey(&pubkey_1),
4636 node_id_2: NodeId::from_pubkey(&pubkey_2),
4637 bitcoin_key_1: NodeId::from_pubkey(&pubkey_3),
4638 bitcoin_key_2: NodeId::from_pubkey(&pubkey_4),
4639 excess_data: if excess_data {
4640 vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40]
4641 } else {
4642 Vec::new()
4643 },
4644 };
4645 let channel_announcement = msgs::ChannelAnnouncement {
4646 node_signature_1: sig_1,
4647 node_signature_2: sig_2,
4648 bitcoin_signature_1: sig_3,
4649 bitcoin_signature_2: sig_4,
4650 contents: unsigned_channel_announcement,
4651 };
4652 let encoded_value = channel_announcement.encode();
4653 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
4654 if unknown_features_bits {
4655 target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
4656 } else {
4657 target_value.append(&mut <Vec<u8>>::from_hex("0000").unwrap());
4658 }
4659 target_value.append(
4660 &mut <Vec<u8>>::from_hex(
4661 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4662 )
4663 .unwrap(),
4664 );
4665 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
4666 if excess_data {
4667 target_value.append(&mut <Vec<u8>>::from_hex("0a00001400001e000028").unwrap());
4668 }
4669 assert_eq!(encoded_value, target_value);
4670 }
4671
4672 #[test]
4673 fn encoding_channel_announcement() {
4674 do_encoding_channel_announcement(true, false);
4675 do_encoding_channel_announcement(false, true);
4676 do_encoding_channel_announcement(false, false);
4677 do_encoding_channel_announcement(true, true);
4678 }
4679
4680 fn do_encoding_node_announcement(
4681 unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool,
4682 hostname: bool, excess_address_data: bool, excess_data: bool,
4683 ) {
4684 let secp_ctx = Secp256k1::new();
4685 let (privkey_1, pubkey_1) = get_keys_from!(
4686 "0101010101010101010101010101010101010101010101010101010101010101",
4687 secp_ctx
4688 );
4689 let sig_1 =
4690 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4691 let features = if unknown_features_bits {
4692 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
4693 } else {
4694 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
4696 };
4697 let mut addresses = Vec::new();
4698 if ipv4 {
4699 addresses.push(SocketAddress::TcpIpV4 { addr: [255, 254, 253, 252], port: 9735 });
4700 }
4701 if ipv6 {
4702 addresses.push(SocketAddress::TcpIpV6 {
4703 addr: [
4704 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240,
4705 ],
4706 port: 9735,
4707 });
4708 }
4709 if onionv2 {
4710 addresses.push(msgs::SocketAddress::OnionV2([
4711 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7,
4712 ]));
4713 }
4714 if onionv3 {
4715 addresses.push(msgs::SocketAddress::OnionV3 {
4716 ed25519_pubkey: [
4717 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240,
4718 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224,
4719 ],
4720 checksum: 32,
4721 version: 16,
4722 port: 9735,
4723 });
4724 }
4725 if hostname {
4726 addresses.push(SocketAddress::Hostname {
4727 hostname: Hostname::try_from(String::from("host")).unwrap(),
4728 port: 9735,
4729 });
4730 }
4731 let mut addr_len = 0;
4732 for addr in &addresses {
4733 addr_len += addr.len() + 1;
4734 }
4735 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
4736 features,
4737 timestamp: 20190119,
4738 node_id: NodeId::from_pubkey(&pubkey_1),
4739 rgb: [32; 3],
4740 alias: NodeAlias([16; 32]),
4741 addresses,
4742 excess_address_data: if excess_address_data {
4743 vec![
4744 33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34,
4745 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84,
4746 174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42,
4747 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105,
4748 ]
4749 } else {
4750 Vec::new()
4751 },
4752 excess_data: if excess_data {
4753 vec![
4754 59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160,
4755 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8,
4756 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17,
4757 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253,
4758 ]
4759 } else {
4760 Vec::new()
4761 },
4762 };
4763 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
4764 let node_announcement =
4765 msgs::NodeAnnouncement { signature: sig_1, contents: unsigned_node_announcement };
4766 let encoded_value = node_announcement.encode();
4767 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4768 if unknown_features_bits {
4769 target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
4770 } else {
4771 target_value.append(&mut <Vec<u8>>::from_hex("000122").unwrap());
4772 }
4773 target_value.append(&mut <Vec<u8>>::from_hex("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
4774 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
4775 if ipv4 {
4776 target_value.append(&mut <Vec<u8>>::from_hex("01fffefdfc2607").unwrap());
4777 }
4778 if ipv6 {
4779 target_value.append(
4780 &mut <Vec<u8>>::from_hex("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap(),
4781 );
4782 }
4783 if onionv2 {
4784 target_value.append(&mut <Vec<u8>>::from_hex("03fffefdfcfbfaf9f8f7f62607").unwrap());
4785 }
4786 if onionv3 {
4787 target_value.append(
4788 &mut <Vec<u8>>::from_hex(
4789 "04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607",
4790 )
4791 .unwrap(),
4792 );
4793 }
4794 if hostname {
4795 target_value.append(&mut <Vec<u8>>::from_hex("0504686f73742607").unwrap());
4796 }
4797 if excess_address_data {
4798 target_value.append(&mut <Vec<u8>>::from_hex("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
4799 }
4800 if excess_data {
4801 target_value.append(&mut <Vec<u8>>::from_hex("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
4802 }
4803 assert_eq!(encoded_value, target_value);
4804 }
4805
4806 #[test]
4807 fn encoding_node_announcement() {
4808 do_encoding_node_announcement(true, true, true, true, true, true, true, true);
4809 do_encoding_node_announcement(false, false, false, false, false, false, false, false);
4810 do_encoding_node_announcement(false, true, false, false, false, false, false, false);
4811 do_encoding_node_announcement(false, false, true, false, false, false, false, false);
4812 do_encoding_node_announcement(false, false, false, true, false, false, false, false);
4813 do_encoding_node_announcement(false, false, false, false, true, false, false, false);
4814 do_encoding_node_announcement(false, false, false, false, false, true, false, false);
4815 do_encoding_node_announcement(false, false, false, false, false, false, true, false);
4816 do_encoding_node_announcement(false, true, false, true, false, false, true, false);
4817 do_encoding_node_announcement(false, false, true, false, true, false, false, false);
4818 }
4819
4820 fn do_encoding_channel_update(direction: bool, disable: bool, excess_data: bool) {
4821 let secp_ctx = Secp256k1::new();
4822 let (privkey_1, _) = get_keys_from!(
4823 "0101010101010101010101010101010101010101010101010101010101010101",
4824 secp_ctx
4825 );
4826 let sig_1 =
4827 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4828 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
4829 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4830 short_channel_id: 2316138423780173,
4831 timestamp: 20190119,
4832 message_flags: 1, channel_flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
4834 cltv_expiry_delta: 144,
4835 htlc_minimum_msat: 1000000,
4836 htlc_maximum_msat: 131355275467161,
4837 fee_base_msat: 10000,
4838 fee_proportional_millionths: 20,
4839 excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() },
4840 };
4841 let channel_update =
4842 msgs::ChannelUpdate { signature: sig_1, contents: unsigned_channel_update };
4843 let encoded_value = channel_update.encode();
4844 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4845 target_value.append(
4846 &mut <Vec<u8>>::from_hex(
4847 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4848 )
4849 .unwrap(),
4850 );
4851 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d013413a7").unwrap());
4852 target_value.append(&mut <Vec<u8>>::from_hex("01").unwrap());
4853 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
4854 if direction {
4855 let flag = target_value.last_mut().unwrap();
4856 *flag = 1;
4857 }
4858 if disable {
4859 let flag = target_value.last_mut().unwrap();
4860 *flag |= 1 << 1;
4861 }
4862 target_value
4863 .append(&mut <Vec<u8>>::from_hex("009000000000000f42400000271000000014").unwrap());
4864 target_value.append(&mut <Vec<u8>>::from_hex("0000777788889999").unwrap());
4865 if excess_data {
4866 target_value.append(&mut <Vec<u8>>::from_hex("000000003b9aca00").unwrap());
4867 }
4868 assert_eq!(encoded_value, target_value);
4869 }
4870
4871 #[test]
4872 fn encoding_channel_update() {
4873 do_encoding_channel_update(false, false, false);
4874 do_encoding_channel_update(false, false, true);
4875 do_encoding_channel_update(true, false, false);
4876 do_encoding_channel_update(true, false, true);
4877 do_encoding_channel_update(false, true, false);
4878 do_encoding_channel_update(false, true, true);
4879 do_encoding_channel_update(true, true, false);
4880 do_encoding_channel_update(true, true, true);
4881 }
4882
4883 fn do_encoding_open_channel(random_bit: bool, shutdown: bool, incl_chan_type: bool) {
4884 let secp_ctx = Secp256k1::new();
4885 let (_, pubkey_1) = get_keys_from!(
4886 "0101010101010101010101010101010101010101010101010101010101010101",
4887 secp_ctx
4888 );
4889 let (_, pubkey_2) = get_keys_from!(
4890 "0202020202020202020202020202020202020202020202020202020202020202",
4891 secp_ctx
4892 );
4893 let (_, pubkey_3) = get_keys_from!(
4894 "0303030303030303030303030303030303030303030303030303030303030303",
4895 secp_ctx
4896 );
4897 let (_, pubkey_4) = get_keys_from!(
4898 "0404040404040404040404040404040404040404040404040404040404040404",
4899 secp_ctx
4900 );
4901 let (_, pubkey_5) = get_keys_from!(
4902 "0505050505050505050505050505050505050505050505050505050505050505",
4903 secp_ctx
4904 );
4905 let (_, pubkey_6) = get_keys_from!(
4906 "0606060606060606060606060606060606060606060606060606060606060606",
4907 secp_ctx
4908 );
4909 let open_channel = msgs::OpenChannel {
4910 common_fields: CommonOpenChannelFields {
4911 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4912 temporary_channel_id: ChannelId::from_bytes([2; 32]),
4913 funding_satoshis: 1311768467284833366,
4914 dust_limit_satoshis: 3608586615801332854,
4915 max_htlc_value_in_flight_msat: 8517154655701053848,
4916 htlc_minimum_msat: 2316138423780173,
4917 commitment_feerate_sat_per_1000_weight: 821716,
4918 to_self_delay: 49340,
4919 max_accepted_htlcs: 49340,
4920 funding_pubkey: pubkey_1,
4921 revocation_basepoint: pubkey_2,
4922 payment_basepoint: pubkey_3,
4923 delayed_payment_basepoint: pubkey_4,
4924 htlc_basepoint: pubkey_5,
4925 first_per_commitment_point: pubkey_6,
4926 channel_flags: if random_bit { 1 << 5 } else { 0 },
4927 shutdown_scriptpubkey: if shutdown {
4928 Some(
4929 Address::p2pkh(
4930 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
4931 Network::Testnet,
4932 )
4933 .script_pubkey(),
4934 )
4935 } else {
4936 None
4937 },
4938 channel_type: if incl_chan_type {
4939 Some(ChannelTypeFeatures::empty())
4940 } else {
4941 None
4942 },
4943 },
4944 push_msat: 2536655962884945560,
4945 channel_reserve_satoshis: 8665828695742877976,
4946 };
4947 let encoded_value = open_channel.encode();
4948 let mut target_value = Vec::new();
4949 target_value.append(
4950 &mut <Vec<u8>>::from_hex(
4951 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4952 )
4953 .unwrap(),
4954 );
4955 target_value.append(&mut <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
4956 if random_bit {
4957 target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
4958 } else {
4959 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
4960 }
4961 if shutdown {
4962 target_value.append(
4963 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
4964 .unwrap(),
4965 );
4966 }
4967 if incl_chan_type {
4968 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
4969 }
4970 assert_eq!(encoded_value, target_value);
4971 }
4972
4973 #[test]
4974 fn encoding_open_channel() {
4975 do_encoding_open_channel(false, false, false);
4976 do_encoding_open_channel(false, false, true);
4977 do_encoding_open_channel(false, true, false);
4978 do_encoding_open_channel(false, true, true);
4979 do_encoding_open_channel(true, false, false);
4980 do_encoding_open_channel(true, false, true);
4981 do_encoding_open_channel(true, true, false);
4982 do_encoding_open_channel(true, true, true);
4983 }
4984
4985 fn do_encoding_open_channelv2(
4986 random_bit: bool, shutdown: bool, incl_chan_type: bool, require_confirmed_inputs: bool,
4987 ) {
4988 let secp_ctx = Secp256k1::new();
4989 let (_, pubkey_1) = get_keys_from!(
4990 "0101010101010101010101010101010101010101010101010101010101010101",
4991 secp_ctx
4992 );
4993 let (_, pubkey_2) = get_keys_from!(
4994 "0202020202020202020202020202020202020202020202020202020202020202",
4995 secp_ctx
4996 );
4997 let (_, pubkey_3) = get_keys_from!(
4998 "0303030303030303030303030303030303030303030303030303030303030303",
4999 secp_ctx
5000 );
5001 let (_, pubkey_4) = get_keys_from!(
5002 "0404040404040404040404040404040404040404040404040404040404040404",
5003 secp_ctx
5004 );
5005 let (_, pubkey_5) = get_keys_from!(
5006 "0505050505050505050505050505050505050505050505050505050505050505",
5007 secp_ctx
5008 );
5009 let (_, pubkey_6) = get_keys_from!(
5010 "0606060606060606060606060606060606060606060606060606060606060606",
5011 secp_ctx
5012 );
5013 let (_, pubkey_7) = get_keys_from!(
5014 "0707070707070707070707070707070707070707070707070707070707070707",
5015 secp_ctx
5016 );
5017 let open_channelv2 = msgs::OpenChannelV2 {
5018 common_fields: CommonOpenChannelFields {
5019 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
5020 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5021 commitment_feerate_sat_per_1000_weight: 821716,
5022 funding_satoshis: 1311768467284833366,
5023 dust_limit_satoshis: 3608586615801332854,
5024 max_htlc_value_in_flight_msat: 8517154655701053848,
5025 htlc_minimum_msat: 2316138423780173,
5026 to_self_delay: 49340,
5027 max_accepted_htlcs: 49340,
5028 funding_pubkey: pubkey_1,
5029 revocation_basepoint: pubkey_2,
5030 payment_basepoint: pubkey_3,
5031 delayed_payment_basepoint: pubkey_4,
5032 htlc_basepoint: pubkey_5,
5033 first_per_commitment_point: pubkey_6,
5034 channel_flags: if random_bit { 1 << 5 } else { 0 },
5035 shutdown_scriptpubkey: if shutdown {
5036 Some(
5037 Address::p2pkh(
5038 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5039 Network::Testnet,
5040 )
5041 .script_pubkey(),
5042 )
5043 } else {
5044 None
5045 },
5046 channel_type: if incl_chan_type {
5047 Some(ChannelTypeFeatures::empty())
5048 } else {
5049 None
5050 },
5051 },
5052 funding_feerate_sat_per_1000_weight: 821716,
5053 locktime: 305419896,
5054 second_per_commitment_point: pubkey_7,
5055 require_confirmed_inputs: if require_confirmed_inputs { Some(()) } else { None },
5056 };
5057 let encoded_value = open_channelv2.encode();
5058 let mut target_value = Vec::new();
5059 target_value.append(
5060 &mut <Vec<u8>>::from_hex(
5061 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
5062 )
5063 .unwrap(),
5064 );
5065 target_value.append(
5066 &mut <Vec<u8>>::from_hex(
5067 "0202020202020202020202020202020202020202020202020202020202020202",
5068 )
5069 .unwrap(),
5070 );
5071 target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
5072 target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
5073 target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap());
5074 target_value.append(&mut <Vec<u8>>::from_hex("3214466870114476").unwrap());
5075 target_value.append(&mut <Vec<u8>>::from_hex("7633030896203198").unwrap());
5076 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d").unwrap());
5077 target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
5078 target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
5079 target_value.append(&mut <Vec<u8>>::from_hex("12345678").unwrap());
5080 target_value.append(
5081 &mut <Vec<u8>>::from_hex(
5082 "031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",
5083 )
5084 .unwrap(),
5085 );
5086 target_value.append(
5087 &mut <Vec<u8>>::from_hex(
5088 "024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",
5089 )
5090 .unwrap(),
5091 );
5092 target_value.append(
5093 &mut <Vec<u8>>::from_hex(
5094 "02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
5095 )
5096 .unwrap(),
5097 );
5098 target_value.append(
5099 &mut <Vec<u8>>::from_hex(
5100 "03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b",
5101 )
5102 .unwrap(),
5103 );
5104 target_value.append(
5105 &mut <Vec<u8>>::from_hex(
5106 "0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7",
5107 )
5108 .unwrap(),
5109 );
5110 target_value.append(
5111 &mut <Vec<u8>>::from_hex(
5112 "03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a",
5113 )
5114 .unwrap(),
5115 );
5116 target_value.append(
5117 &mut <Vec<u8>>::from_hex(
5118 "02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f",
5119 )
5120 .unwrap(),
5121 );
5122
5123 if random_bit {
5124 target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
5125 } else {
5126 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
5127 }
5128 if shutdown {
5129 target_value.append(
5130 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5131 .unwrap(),
5132 );
5133 }
5134 if incl_chan_type {
5135 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
5136 }
5137 if require_confirmed_inputs {
5138 target_value.append(&mut <Vec<u8>>::from_hex("0200").unwrap());
5139 }
5140 assert_eq!(encoded_value, target_value);
5141 }
5142
5143 #[test]
5144 fn encoding_open_channelv2() {
5145 do_encoding_open_channelv2(false, false, false, false);
5146 do_encoding_open_channelv2(false, false, false, true);
5147 do_encoding_open_channelv2(false, false, true, false);
5148 do_encoding_open_channelv2(false, false, true, true);
5149 do_encoding_open_channelv2(false, true, false, false);
5150 do_encoding_open_channelv2(false, true, false, true);
5151 do_encoding_open_channelv2(false, true, true, false);
5152 do_encoding_open_channelv2(false, true, true, true);
5153 do_encoding_open_channelv2(true, false, false, false);
5154 do_encoding_open_channelv2(true, false, false, true);
5155 do_encoding_open_channelv2(true, false, true, false);
5156 do_encoding_open_channelv2(true, false, true, true);
5157 do_encoding_open_channelv2(true, true, false, false);
5158 do_encoding_open_channelv2(true, true, false, true);
5159 do_encoding_open_channelv2(true, true, true, false);
5160 do_encoding_open_channelv2(true, true, true, true);
5161 }
5162
5163 fn do_encoding_accept_channel(shutdown: bool) {
5164 let secp_ctx = Secp256k1::new();
5165 let (_, pubkey_1) = get_keys_from!(
5166 "0101010101010101010101010101010101010101010101010101010101010101",
5167 secp_ctx
5168 );
5169 let (_, pubkey_2) = get_keys_from!(
5170 "0202020202020202020202020202020202020202020202020202020202020202",
5171 secp_ctx
5172 );
5173 let (_, pubkey_3) = get_keys_from!(
5174 "0303030303030303030303030303030303030303030303030303030303030303",
5175 secp_ctx
5176 );
5177 let (_, pubkey_4) = get_keys_from!(
5178 "0404040404040404040404040404040404040404040404040404040404040404",
5179 secp_ctx
5180 );
5181 let (_, pubkey_5) = get_keys_from!(
5182 "0505050505050505050505050505050505050505050505050505050505050505",
5183 secp_ctx
5184 );
5185 let (_, pubkey_6) = get_keys_from!(
5186 "0606060606060606060606060606060606060606060606060606060606060606",
5187 secp_ctx
5188 );
5189 let accept_channel = msgs::AcceptChannel {
5190 common_fields: CommonAcceptChannelFields {
5191 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5192 dust_limit_satoshis: 1311768467284833366,
5193 max_htlc_value_in_flight_msat: 2536655962884945560,
5194 htlc_minimum_msat: 2316138423780173,
5195 minimum_depth: 821716,
5196 to_self_delay: 49340,
5197 max_accepted_htlcs: 49340,
5198 funding_pubkey: pubkey_1,
5199 revocation_basepoint: pubkey_2,
5200 payment_basepoint: pubkey_3,
5201 delayed_payment_basepoint: pubkey_4,
5202 htlc_basepoint: pubkey_5,
5203 first_per_commitment_point: pubkey_6,
5204 shutdown_scriptpubkey: if shutdown {
5205 Some(
5206 Address::p2pkh(
5207 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5208 Network::Testnet,
5209 )
5210 .script_pubkey(),
5211 )
5212 } else {
5213 None
5214 },
5215 channel_type: None,
5216 },
5217 channel_reserve_satoshis: 3608586615801332854,
5218 #[cfg(taproot)]
5219 next_local_nonce: None,
5220 };
5221 let encoded_value = accept_channel.encode();
5222 let mut target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
5223 if shutdown {
5224 target_value.append(
5225 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5226 .unwrap(),
5227 );
5228 }
5229 assert_eq!(encoded_value, target_value);
5230 }
5231
5232 #[test]
5233 fn encoding_accept_channel() {
5234 do_encoding_accept_channel(false);
5235 do_encoding_accept_channel(true);
5236 }
5237
5238 fn do_encoding_accept_channelv2(shutdown: bool) {
5239 let secp_ctx = Secp256k1::new();
5240 let (_, pubkey_1) = get_keys_from!(
5241 "0101010101010101010101010101010101010101010101010101010101010101",
5242 secp_ctx
5243 );
5244 let (_, pubkey_2) = get_keys_from!(
5245 "0202020202020202020202020202020202020202020202020202020202020202",
5246 secp_ctx
5247 );
5248 let (_, pubkey_3) = get_keys_from!(
5249 "0303030303030303030303030303030303030303030303030303030303030303",
5250 secp_ctx
5251 );
5252 let (_, pubkey_4) = get_keys_from!(
5253 "0404040404040404040404040404040404040404040404040404040404040404",
5254 secp_ctx
5255 );
5256 let (_, pubkey_5) = get_keys_from!(
5257 "0505050505050505050505050505050505050505050505050505050505050505",
5258 secp_ctx
5259 );
5260 let (_, pubkey_6) = get_keys_from!(
5261 "0606060606060606060606060606060606060606060606060606060606060606",
5262 secp_ctx
5263 );
5264 let (_, pubkey_7) = get_keys_from!(
5265 "0707070707070707070707070707070707070707070707070707070707070707",
5266 secp_ctx
5267 );
5268 let accept_channelv2 = msgs::AcceptChannelV2 {
5269 common_fields: CommonAcceptChannelFields {
5270 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5271 dust_limit_satoshis: 1311768467284833366,
5272 max_htlc_value_in_flight_msat: 2536655962884945560,
5273 htlc_minimum_msat: 2316138423780173,
5274 minimum_depth: 821716,
5275 to_self_delay: 49340,
5276 max_accepted_htlcs: 49340,
5277 funding_pubkey: pubkey_1,
5278 revocation_basepoint: pubkey_2,
5279 payment_basepoint: pubkey_3,
5280 delayed_payment_basepoint: pubkey_4,
5281 htlc_basepoint: pubkey_5,
5282 first_per_commitment_point: pubkey_6,
5283 shutdown_scriptpubkey: if shutdown {
5284 Some(
5285 Address::p2pkh(
5286 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5287 Network::Testnet,
5288 )
5289 .script_pubkey(),
5290 )
5291 } else {
5292 None
5293 },
5294 channel_type: None,
5295 },
5296 funding_satoshis: 1311768467284833366,
5297 second_per_commitment_point: pubkey_7,
5298 require_confirmed_inputs: None,
5299 };
5300 let encoded_value = accept_channelv2.encode();
5301 let mut target_value =
5302 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5303 .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(
5312 &mut <Vec<u8>>::from_hex(
5313 "031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",
5314 )
5315 .unwrap(),
5316 ); target_value.append(
5318 &mut <Vec<u8>>::from_hex(
5319 "024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",
5320 )
5321 .unwrap(),
5322 ); target_value.append(
5324 &mut <Vec<u8>>::from_hex(
5325 "02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
5326 )
5327 .unwrap(),
5328 ); target_value.append(
5330 &mut <Vec<u8>>::from_hex(
5331 "03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b",
5332 )
5333 .unwrap(),
5334 ); target_value.append(
5336 &mut <Vec<u8>>::from_hex(
5337 "0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7",
5338 )
5339 .unwrap(),
5340 ); target_value.append(
5342 &mut <Vec<u8>>::from_hex(
5343 "03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a",
5344 )
5345 .unwrap(),
5346 ); target_value.append(
5348 &mut <Vec<u8>>::from_hex(
5349 "02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f",
5350 )
5351 .unwrap(),
5352 ); if shutdown {
5354 target_value.append(
5355 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5356 .unwrap(),
5357 );
5358 }
5359 assert_eq!(encoded_value, target_value);
5360 }
5361
5362 #[test]
5363 fn encoding_accept_channelv2() {
5364 do_encoding_accept_channelv2(false);
5365 do_encoding_accept_channelv2(true);
5366 }
5367
5368 #[test]
5369 fn encoding_funding_created() {
5370 let secp_ctx = Secp256k1::new();
5371 let (privkey_1, _) = get_keys_from!(
5372 "0101010101010101010101010101010101010101010101010101010101010101",
5373 secp_ctx
5374 );
5375 let sig_1 =
5376 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5377 let funding_created = msgs::FundingCreated {
5378 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5379 funding_txid: Txid::from_str(
5380 "c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e",
5381 )
5382 .unwrap(),
5383 funding_output_index: 255,
5384 signature: sig_1,
5385 #[cfg(taproot)]
5386 partial_signature_with_nonce: None,
5387 #[cfg(taproot)]
5388 next_local_nonce: None,
5389 };
5390 let encoded_value = funding_created.encode();
5391 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5392 assert_eq!(encoded_value, target_value);
5393 }
5394
5395 #[test]
5396 fn encoding_funding_signed() {
5397 let secp_ctx = Secp256k1::new();
5398 let (privkey_1, _) = get_keys_from!(
5399 "0101010101010101010101010101010101010101010101010101010101010101",
5400 secp_ctx
5401 );
5402 let sig_1 =
5403 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5404 let funding_signed = msgs::FundingSigned {
5405 channel_id: ChannelId::from_bytes([2; 32]),
5406 signature: sig_1,
5407 #[cfg(taproot)]
5408 partial_signature_with_nonce: None,
5409 };
5410 let encoded_value = funding_signed.encode();
5411 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5412 assert_eq!(encoded_value, target_value);
5413 }
5414
5415 #[test]
5416 fn encoding_channel_ready() {
5417 let secp_ctx = Secp256k1::new();
5418 let (_, pubkey_1) = get_keys_from!(
5419 "0101010101010101010101010101010101010101010101010101010101010101",
5420 secp_ctx
5421 );
5422 let channel_ready = msgs::ChannelReady {
5423 channel_id: ChannelId::from_bytes([2; 32]),
5424 next_per_commitment_point: pubkey_1,
5425 short_channel_id_alias: None,
5426 };
5427 let encoded_value = channel_ready.encode();
5428 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
5429 assert_eq!(encoded_value, target_value);
5430 }
5431
5432 #[test]
5433 fn encoding_splice_init() {
5434 let secp_ctx = Secp256k1::new();
5435 let (_, pubkey_1) = get_keys_from!(
5436 "0101010101010101010101010101010101010101010101010101010101010101",
5437 secp_ctx
5438 );
5439 let splice_init = msgs::SpliceInit {
5440 channel_id: ChannelId::from_bytes([2; 32]),
5441 funding_contribution_satoshis: -123456,
5442 funding_feerate_per_kw: 2000,
5443 locktime: 0,
5444 funding_pubkey: pubkey_1,
5445 require_confirmed_inputs: Some(()),
5446 };
5447 let encoded_value = splice_init.encode();
5448 assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
5449 }
5450
5451 #[test]
5452 fn encoding_stfu() {
5453 let stfu = msgs::Stfu { channel_id: ChannelId::from_bytes([2; 32]), initiator: true };
5454 let encoded_value = stfu.encode();
5455 assert_eq!(
5456 encoded_value.as_hex().to_string(),
5457 "020202020202020202020202020202020202020202020202020202020202020201"
5458 );
5459
5460 let stfu = msgs::Stfu { channel_id: ChannelId::from_bytes([3; 32]), initiator: false };
5461 let encoded_value = stfu.encode();
5462 assert_eq!(
5463 encoded_value.as_hex().to_string(),
5464 "030303030303030303030303030303030303030303030303030303030303030300"
5465 );
5466 }
5467
5468 #[test]
5469 fn encoding_splice_ack() {
5470 let secp_ctx = Secp256k1::new();
5471 let (_, pubkey_1) = get_keys_from!(
5472 "0101010101010101010101010101010101010101010101010101010101010101",
5473 secp_ctx
5474 );
5475 let splice_ack = msgs::SpliceAck {
5476 channel_id: ChannelId::from_bytes([2; 32]),
5477 funding_contribution_satoshis: -123456,
5478 funding_pubkey: pubkey_1,
5479 require_confirmed_inputs: Some(()),
5480 };
5481 let encoded_value = splice_ack.encode();
5482 assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
5483 }
5484
5485 #[test]
5486 fn encoding_splice_locked() {
5487 let splice_locked = msgs::SpliceLocked {
5488 channel_id: ChannelId::from_bytes([2; 32]),
5489 splice_txid: Txid::from_str(
5490 "c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e",
5491 )
5492 .unwrap(),
5493 };
5494 let encoded_value = splice_locked.encode();
5495 assert_eq!(encoded_value.as_hex().to_string(), "02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2");
5496 }
5497
5498 #[test]
5499 fn encoding_tx_add_input() {
5500 let tx_add_input = msgs::TxAddInput {
5501 channel_id: ChannelId::from_bytes([2; 32]),
5502 serial_id: 4886718345,
5503 prevtx: Some(Transaction {
5504 version: Version::TWO,
5505 lock_time: LockTime::ZERO,
5506 input: vec![TxIn {
5507 previous_output: OutPoint { txid: Txid::from_str("305bab643ee297b8b6b76b320792c8223d55082122cb606bf89382146ced9c77").unwrap(), index: 2 }.into_bitcoin_outpoint(),
5508 script_sig: ScriptBuf::new(),
5509 sequence: Sequence(0xfffffffd),
5510 witness: Witness::from_slice(&[
5511 <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
5512 <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
5513 }],
5514 output: vec![
5515 TxOut {
5516 value: Amount::from_sat(12704566),
5517 script_pubkey: Address::from_str("bc1qzlffunw52jav8vwdu5x3jfk6sr8u22rmq3xzw2").unwrap().assume_checked().script_pubkey(),
5518 },
5519 TxOut {
5520 value: Amount::from_sat(245148),
5521 script_pubkey: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().assume_checked().script_pubkey(),
5522 },
5523 ],
5524 }),
5525 prevtx_out: 305419896,
5526 sequence: 305419896,
5527 shared_input_txid: None,
5528 };
5529 let encoded_value = tx_add_input.encode();
5530 let target_value = "0202020202020202020202020202020202020202020202020202020202020202000000012345678900de02000000000101779ced6c148293f86b60cb222108553d22c89207326bb7b6b897e23e64ab5b300200000000fdffffff0236dbc1000000000016001417d29e4dd454bac3b1cde50d1926da80cfc5287b9cbd03000000000016001436ec78d514df462da95e6a00c24daa8915362d420247304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701210301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944000000001234567812345678";
5531 assert_eq!(encoded_value.as_hex().to_string(), target_value);
5532 }
5533
5534 #[test]
5535 fn encoding_tx_add_input_shared() {
5536 let tx_add_input = msgs::TxAddInput {
5537 channel_id: ChannelId::from_bytes([2; 32]),
5538 serial_id: 4886718345,
5539 prevtx: None,
5540 prevtx_out: 305419896,
5541 sequence: 305419896,
5542 shared_input_txid: Some(
5543 Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e")
5544 .unwrap(),
5545 ),
5546 };
5547 let encoded_value = tx_add_input.encode();
5548 let target_value = "020202020202020202020202020202020202020202020202020202020202020200000001234567890000123456781234567800206e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2";
5549 assert_eq!(encoded_value.as_hex().to_string(), target_value);
5550 }
5551
5552 #[test]
5553 fn encoding_tx_add_output() {
5554 let tx_add_output = msgs::TxAddOutput {
5555 channel_id: ChannelId::from_bytes([2; 32]),
5556 serial_id: 4886718345,
5557 sats: 4886718345,
5558 script: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z")
5559 .unwrap()
5560 .assume_checked()
5561 .script_pubkey(),
5562 };
5563 let encoded_value = tx_add_output.encode();
5564 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000000012345678900000001234567890016001436ec78d514df462da95e6a00c24daa8915362d42").unwrap();
5565 assert_eq!(encoded_value, target_value);
5566 }
5567
5568 #[test]
5569 fn encoding_tx_remove_input() {
5570 let tx_remove_input = msgs::TxRemoveInput {
5571 channel_id: ChannelId::from_bytes([2; 32]),
5572 serial_id: 4886718345,
5573 };
5574 let encoded_value = tx_remove_input.encode();
5575 let target_value = <Vec<u8>>::from_hex(
5576 "02020202020202020202020202020202020202020202020202020202020202020000000123456789",
5577 )
5578 .unwrap();
5579 assert_eq!(encoded_value, target_value);
5580 }
5581
5582 #[test]
5583 fn encoding_tx_remove_output() {
5584 let tx_remove_output = msgs::TxRemoveOutput {
5585 channel_id: ChannelId::from_bytes([2; 32]),
5586 serial_id: 4886718345,
5587 };
5588 let encoded_value = tx_remove_output.encode();
5589 let target_value = <Vec<u8>>::from_hex(
5590 "02020202020202020202020202020202020202020202020202020202020202020000000123456789",
5591 )
5592 .unwrap();
5593 assert_eq!(encoded_value, target_value);
5594 }
5595
5596 #[test]
5597 fn encoding_tx_complete() {
5598 let tx_complete = msgs::TxComplete { channel_id: ChannelId::from_bytes([2; 32]) };
5599 let encoded_value = tx_complete.encode();
5600 let target_value =
5601 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5602 .unwrap();
5603 assert_eq!(encoded_value, target_value);
5604 }
5605
5606 #[test]
5607 fn encoding_tx_signatures() {
5608 let secp_ctx = Secp256k1::new();
5609 let (privkey_1, _) = get_keys_from!(
5610 "0101010101010101010101010101010101010101010101010101010101010101",
5611 secp_ctx
5612 );
5613 let sig_1 =
5614 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5615
5616 let tx_signatures = msgs::TxSignatures {
5617 channel_id: ChannelId::from_bytes([2; 32]),
5618 tx_hash: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
5619 witnesses: vec![
5620 Witness::from_slice(&[
5621 <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
5622 <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
5623 Witness::from_slice(&[
5624 <Vec<u8>>::from_hex("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap(),
5625 <Vec<u8>>::from_hex("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap()]),
5626 ],
5627 shared_input_signature: Some(sig_1),
5628 };
5629 let encoded_value = tx_signatures.encode();
5630 let mut target_value =
5631 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5632 .unwrap(); target_value.append(
5634 &mut <Vec<u8>>::from_hex(
5635 "6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2",
5636 )
5637 .unwrap(),
5638 ); 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());
5646 target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); target_value.append(
5648 &mut <Vec<u8>>::from_hex(
5649 "0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944",
5650 )
5651 .unwrap(),
5652 );
5653 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());
5658 target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); target_value.append(
5660 &mut <Vec<u8>>::from_hex(
5661 "028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5",
5662 )
5663 .unwrap(),
5664 );
5665 target_value.append(&mut <Vec<u8>>::from_hex("0040").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap());
5667 assert_eq!(encoded_value, target_value);
5668 }
5669
5670 fn do_encoding_tx_init_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
5671 let tx_init_rbf = msgs::TxInitRbf {
5672 channel_id: ChannelId::from_bytes([2; 32]),
5673 locktime: 305419896,
5674 feerate_sat_per_1000_weight: 20190119,
5675 funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target {
5676 Some(value)
5677 } else {
5678 None
5679 },
5680 };
5681 let encoded_value = tx_init_rbf.encode();
5682 let mut target_value =
5683 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5684 .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 {
5688 target_value.push(0x00); target_value.push(target.len() as u8 / 2); target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); }
5692 assert_eq!(encoded_value, target_value);
5693 }
5694
5695 #[test]
5696 fn encoding_tx_init_rbf() {
5697 do_encoding_tx_init_rbf(Some((1311768467284833366, "1234567890123456")));
5698 do_encoding_tx_init_rbf(Some((13117684672, "000000030DDFFBC0")));
5699 do_encoding_tx_init_rbf(None);
5700 }
5701
5702 fn do_encoding_tx_ack_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
5703 let tx_ack_rbf = msgs::TxAckRbf {
5704 channel_id: ChannelId::from_bytes([2; 32]),
5705 funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target {
5706 Some(value)
5707 } else {
5708 None
5709 },
5710 };
5711 let encoded_value = tx_ack_rbf.encode();
5712 let mut target_value =
5713 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5714 .unwrap();
5715 if let Some((_, target)) = funding_value_with_hex_target {
5716 target_value.push(0x00); target_value.push(target.len() as u8 / 2); target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); }
5720 assert_eq!(encoded_value, target_value);
5721 }
5722
5723 #[test]
5724 fn encoding_tx_ack_rbf() {
5725 do_encoding_tx_ack_rbf(Some((1311768467284833366, "1234567890123456")));
5726 do_encoding_tx_ack_rbf(Some((13117684672, "000000030DDFFBC0")));
5727 do_encoding_tx_ack_rbf(None);
5728 }
5729
5730 #[test]
5731 fn encoding_tx_abort() {
5732 let tx_abort = msgs::TxAbort {
5733 channel_id: ChannelId::from_bytes([2; 32]),
5734 data: <Vec<u8>>::from_hex("54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(),
5735 };
5736 let encoded_value = tx_abort.encode();
5737 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202002C54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap();
5738 assert_eq!(encoded_value, target_value);
5739 }
5740
5741 fn do_encoding_shutdown(script_type: u8) {
5742 let secp_ctx = Secp256k1::new();
5743 let (_, pubkey_1) = get_keys_from!(
5744 "0101010101010101010101010101010101010101010101010101010101010101",
5745 secp_ctx
5746 );
5747 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
5748 let shutdown = msgs::Shutdown {
5749 channel_id: ChannelId::from_bytes([2; 32]),
5750 scriptpubkey: if script_type == 1 {
5751 Address::p2pkh(
5752 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5753 Network::Testnet,
5754 )
5755 .script_pubkey()
5756 } else if script_type == 2 {
5757 Address::p2sh(&script, Network::Testnet).unwrap().script_pubkey()
5758 } else if script_type == 3 {
5759 Address::p2wpkh(&::bitcoin::CompressedPublicKey(pubkey_1), Network::Testnet)
5760 .script_pubkey()
5761 } else {
5762 Address::p2wsh(&script, Network::Testnet).script_pubkey()
5763 },
5764 };
5765 let encoded_value = shutdown.encode();
5766 let mut target_value =
5767 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5768 .unwrap();
5769 if script_type == 1 {
5770 target_value.append(
5771 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5772 .unwrap(),
5773 );
5774 } else if script_type == 2 {
5775 target_value.append(
5776 &mut <Vec<u8>>::from_hex("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87")
5777 .unwrap(),
5778 );
5779 } else if script_type == 3 {
5780 target_value.append(
5781 &mut <Vec<u8>>::from_hex("0016001479b000887626b294a914501a4cd226b58b235983")
5782 .unwrap(),
5783 );
5784 } else if script_type == 4 {
5785 target_value.append(
5786 &mut <Vec<u8>>::from_hex(
5787 "002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260",
5788 )
5789 .unwrap(),
5790 );
5791 }
5792 assert_eq!(encoded_value, target_value);
5793 }
5794
5795 #[test]
5796 fn encoding_shutdown() {
5797 do_encoding_shutdown(1);
5798 do_encoding_shutdown(2);
5799 do_encoding_shutdown(3);
5800 do_encoding_shutdown(4);
5801 }
5802
5803 #[test]
5804 fn encoding_closing_signed() {
5805 let secp_ctx = Secp256k1::new();
5806 let (privkey_1, _) = get_keys_from!(
5807 "0101010101010101010101010101010101010101010101010101010101010101",
5808 secp_ctx
5809 );
5810 let sig_1 =
5811 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5812 let closing_signed = msgs::ClosingSigned {
5813 channel_id: ChannelId::from_bytes([2; 32]),
5814 fee_satoshis: 2316138423780173,
5815 signature: sig_1,
5816 fee_range: None,
5817 };
5818 let encoded_value = closing_signed.encode();
5819 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5820 assert_eq!(encoded_value, target_value);
5821 assert_eq!(
5822 msgs::ClosingSigned::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(),
5823 closing_signed
5824 );
5825
5826 let closing_signed_with_range = msgs::ClosingSigned {
5827 channel_id: ChannelId::from_bytes([2; 32]),
5828 fee_satoshis: 2316138423780173,
5829 signature: sig_1,
5830 fee_range: Some(msgs::ClosingSignedFeeRange {
5831 min_fee_satoshis: 0xdeadbeef,
5832 max_fee_satoshis: 0x1badcafe01234567,
5833 }),
5834 };
5835 let encoded_value_with_range = closing_signed_with_range.encode();
5836 let target_value_with_range = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a011000000000deadbeef1badcafe01234567").unwrap();
5837 assert_eq!(encoded_value_with_range, target_value_with_range);
5838 assert_eq!(
5839 msgs::ClosingSigned::read_from_fixed_length_buffer(&mut &target_value_with_range[..])
5840 .unwrap(),
5841 closing_signed_with_range
5842 );
5843 }
5844
5845 #[test]
5846 fn encoding_update_add_htlc() {
5847 let secp_ctx = Secp256k1::new();
5848 let (_, pubkey_1) = get_keys_from!(
5849 "0101010101010101010101010101010101010101010101010101010101010101",
5850 secp_ctx
5851 );
5852 let onion_routing_packet = msgs::OnionPacket {
5853 version: 255,
5854 public_key: Ok(pubkey_1),
5855 hop_data: [1; 20 * 65],
5856 hmac: [2; 32],
5857 };
5858 let update_add_htlc = msgs::UpdateAddHTLC {
5859 channel_id: ChannelId::from_bytes([2; 32]),
5860 htlc_id: 2316138423780173,
5861 amount_msat: 3608586615801332854,
5862 payment_hash: PaymentHash([1; 32]),
5863 cltv_expiry: 821716,
5864 onion_routing_packet,
5865 skimmed_fee_msat: None,
5866 blinding_point: None,
5867 hold_htlc: None,
5868 };
5869 let encoded_value = update_add_htlc.encode();
5870 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
5871 assert_eq!(encoded_value, target_value);
5872 }
5873
5874 #[test]
5875 fn encoding_update_fulfill_htlc() {
5876 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
5877 channel_id: ChannelId::from_bytes([2; 32]),
5878 htlc_id: 2316138423780173,
5879 payment_preimage: PaymentPreimage([1; 32]),
5880 attribution_data: None,
5881 };
5882 let encoded_value = update_fulfill_htlc.encode();
5883 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
5884 assert_eq!(encoded_value, target_value);
5885 }
5886
5887 #[test]
5888 fn encoding_update_fail_htlc() {
5889 let update_fail_htlc = msgs::UpdateFailHTLC {
5890 channel_id: ChannelId::from_bytes([2; 32]),
5891 htlc_id: 2316138423780173,
5892 reason: [1; 32].to_vec(),
5893 attribution_data: Some(AttributionData {
5894 hold_times: [3; MAX_HOPS * HOLD_TIME_LEN],
5895 hmacs: [3; HMAC_LEN * HMAC_COUNT],
5896 }),
5897 };
5898 let encoded_value = update_fail_htlc.encode();
5899 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0020010101010101010101010101010101010101010101010101010101010101010101fd03980303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303").unwrap();
5900 assert_eq!(encoded_value, target_value);
5901 }
5902
5903 #[test]
5904 fn encoding_update_fail_malformed_htlc() {
5905 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
5906 channel_id: ChannelId::from_bytes([2; 32]),
5907 htlc_id: 2316138423780173,
5908 sha256_of_onion: [1; 32],
5909 failure_code: 255,
5910 };
5911 let encoded_value = update_fail_malformed_htlc.encode();
5912 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
5913 assert_eq!(encoded_value, target_value);
5914 }
5915
5916 fn do_encoding_commitment_signed(htlcs: bool) {
5917 let secp_ctx = Secp256k1::new();
5918 let (privkey_1, _) = get_keys_from!(
5919 "0101010101010101010101010101010101010101010101010101010101010101",
5920 secp_ctx
5921 );
5922 let (privkey_2, _) = get_keys_from!(
5923 "0202020202020202020202020202020202020202020202020202020202020202",
5924 secp_ctx
5925 );
5926 let (privkey_3, _) = get_keys_from!(
5927 "0303030303030303030303030303030303030303030303030303030303030303",
5928 secp_ctx
5929 );
5930 let (privkey_4, _) = get_keys_from!(
5931 "0404040404040404040404040404040404040404040404040404040404040404",
5932 secp_ctx
5933 );
5934 let sig_1 =
5935 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5936 let sig_2 =
5937 get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
5938 let sig_3 =
5939 get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
5940 let sig_4 =
5941 get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
5942 let commitment_signed = msgs::CommitmentSigned {
5943 channel_id: ChannelId::from_bytes([2; 32]),
5944 signature: sig_1,
5945 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
5946 funding_txid: Some(
5947 Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e")
5948 .unwrap(),
5949 ),
5950 #[cfg(taproot)]
5951 partial_signature_with_nonce: None,
5952 };
5953 let encoded_value = commitment_signed.encode();
5954 let mut target_value = "0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a".to_string();
5955 if htlcs {
5956 target_value += "00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd";
5957 } else {
5958 target_value += "0000";
5959 }
5960 target_value += "01"; target_value += "20"; target_value += "6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2"; assert_eq!(encoded_value.as_hex().to_string(), target_value);
5964 }
5965
5966 #[test]
5967 fn encoding_commitment_signed() {
5968 do_encoding_commitment_signed(true);
5969 do_encoding_commitment_signed(false);
5970 }
5971
5972 #[test]
5973 fn encoding_revoke_and_ack() {
5974 let secp_ctx = Secp256k1::new();
5975 let (_, pubkey_1) = get_keys_from!(
5976 "0101010101010101010101010101010101010101010101010101010101010101",
5977 secp_ctx
5978 );
5979 let raa = msgs::RevokeAndACK {
5980 channel_id: ChannelId::from_bytes([2; 32]),
5981 per_commitment_secret: [
5982 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,
5983 1, 1, 1, 1,
5984 ],
5985 next_per_commitment_point: pubkey_1,
5986 #[cfg(taproot)]
5987 next_local_nonce: None,
5988 release_htlc_message_paths: Vec::new(),
5989 };
5990 let encoded_value = raa.encode();
5991 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
5992 assert_eq!(encoded_value, target_value);
5993 }
5994
5995 #[test]
5996 fn encoding_update_fee() {
5997 let update_fee = msgs::UpdateFee {
5998 channel_id: ChannelId::from_bytes([2; 32]),
5999 feerate_per_kw: 20190119,
6000 };
6001 let encoded_value = update_fee.encode();
6002 let target_value = <Vec<u8>>::from_hex(
6003 "0202020202020202020202020202020202020202020202020202020202020202013413a7",
6004 )
6005 .unwrap();
6006 assert_eq!(encoded_value, target_value);
6007 }
6008
6009 #[test]
6010 fn encoding_init() {
6011 let mainnet_hash = ChainHash::using_genesis_block(Network::Bitcoin);
6012 assert_eq!(msgs::Init {
6013 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
6014 networks: Some(vec![mainnet_hash]),
6015 remote_network_address: None,
6016 }.encode(), <Vec<u8>>::from_hex("00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
6017 assert_eq!(
6018 msgs::Init {
6019 features: InitFeatures::from_le_bytes(vec![0xFF]),
6020 networks: None,
6021 remote_network_address: None,
6022 }
6023 .encode(),
6024 <Vec<u8>>::from_hex("0001ff0001ff").unwrap()
6025 );
6026 assert_eq!(
6027 msgs::Init {
6028 features: InitFeatures::from_le_bytes(vec![]),
6029 networks: Some(vec![mainnet_hash]),
6030 remote_network_address: None,
6031 }
6032 .encode(),
6033 <Vec<u8>>::from_hex(
6034 "0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000"
6035 )
6036 .unwrap()
6037 );
6038 assert_eq!(msgs::Init {
6039 features: InitFeatures::from_le_bytes(vec![]),
6040 networks: Some(vec![ChainHash::from(&[1; 32]), ChainHash::from(&[2; 32])]),
6041 remote_network_address: None,
6042 }.encode(), <Vec<u8>>::from_hex("00000000014001010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap());
6043 let init_msg = msgs::Init {
6044 features: InitFeatures::from_le_bytes(vec![]),
6045 networks: Some(vec![mainnet_hash]),
6046 remote_network_address: Some(SocketAddress::TcpIpV4 {
6047 addr: [127, 0, 0, 1],
6048 port: 1000,
6049 }),
6050 };
6051 let encoded_value = init_msg.encode();
6052 let target_value = <Vec<u8>>::from_hex("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8").unwrap();
6053 assert_eq!(encoded_value, target_value);
6054 assert_eq!(
6055 msgs::Init::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(),
6056 init_msg
6057 );
6058 }
6059
6060 #[test]
6061 fn encoding_error() {
6062 let error = msgs::ErrorMessage {
6063 channel_id: ChannelId::from_bytes([2; 32]),
6064 data: String::from("rust-lightning"),
6065 };
6066 let encoded_value = error.encode();
6067 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
6068 assert_eq!(encoded_value, target_value);
6069 }
6070
6071 #[test]
6072 fn encoding_warning() {
6073 let error = msgs::WarningMessage {
6074 channel_id: ChannelId::from_bytes([2; 32]),
6075 data: String::from("rust-lightning"),
6076 };
6077 let encoded_value = error.encode();
6078 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
6079 assert_eq!(encoded_value, target_value);
6080 }
6081
6082 #[test]
6083 fn encoding_ping() {
6084 let ping = msgs::Ping { ponglen: 64, byteslen: 64 };
6085 let encoded_value = ping.encode();
6086 let target_value = <Vec<u8>>::from_hex("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6087 assert_eq!(encoded_value, target_value);
6088 }
6089
6090 #[test]
6091 fn encoding_peer_storage() {
6092 let peer_storage =
6093 msgs::PeerStorage { data: <Vec<u8>>::from_hex("01020304050607080910").unwrap() };
6094 let encoded_value = peer_storage.encode();
6095 let target_value = <Vec<u8>>::from_hex("000a01020304050607080910").unwrap();
6096 assert_eq!(encoded_value, target_value);
6097 }
6098
6099 #[test]
6100 fn encoding_peer_storage_retrieval() {
6101 let peer_storage_retrieval = msgs::PeerStorageRetrieval {
6102 data: <Vec<u8>>::from_hex("01020304050607080910").unwrap(),
6103 };
6104 let encoded_value = peer_storage_retrieval.encode();
6105 let target_value = <Vec<u8>>::from_hex("000a01020304050607080910").unwrap();
6106 assert_eq!(encoded_value, target_value);
6107 }
6108
6109 #[test]
6110 fn encoding_pong() {
6111 let pong = msgs::Pong { byteslen: 64 };
6112 let encoded_value = pong.encode();
6113 let target_value = <Vec<u8>>::from_hex("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6114 assert_eq!(encoded_value, target_value);
6115 }
6116
6117 #[test]
6118 fn encoding_nonfinal_onion_hop_data() {
6119 let outbound_msg = msgs::OutboundOnionPayload::Forward {
6120 short_channel_id: 0xdeadbeef1bad1dea,
6121 amt_to_forward: 0x0badf00d01020304,
6122 outgoing_cltv_value: 0xffffffff,
6123 };
6124 let encoded_value = outbound_msg.encode();
6125 let target_value =
6126 <Vec<u8>>::from_hex("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
6127 assert_eq!(encoded_value, target_value);
6128
6129 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6130 let inbound_msg =
6131 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6132 if let msgs::InboundOnionPayload::Forward(InboundOnionForwardPayload {
6133 short_channel_id,
6134 amt_to_forward,
6135 outgoing_cltv_value,
6136 }) = inbound_msg
6137 {
6138 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
6139 assert_eq!(amt_to_forward, 0x0badf00d01020304);
6140 assert_eq!(outgoing_cltv_value, 0xffffffff);
6141 } else {
6142 panic!();
6143 }
6144 }
6145
6146 #[test]
6147 fn encoding_final_onion_hop_data() {
6148 let outbound_msg = msgs::OutboundOnionPayload::Receive {
6149 payment_data: None,
6150 payment_metadata: None,
6151 keysend_preimage: None,
6152 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6153 cltv_expiry_height: 0xffffffff,
6154 custom_tlvs: &vec![],
6155 };
6156 let encoded_value = outbound_msg.encode();
6157 let target_value = <Vec<u8>>::from_hex("1002080badf00d010203040404ffffffff").unwrap();
6158 assert_eq!(encoded_value, target_value);
6159
6160 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6161 let inbound_msg =
6162 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6163 if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6164 payment_data: None,
6165 sender_intended_htlc_amt_msat,
6166 cltv_expiry_height,
6167 ..
6168 }) = inbound_msg
6169 {
6170 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6171 assert_eq!(cltv_expiry_height, 0xffffffff);
6172 } else {
6173 panic!();
6174 }
6175 }
6176
6177 #[test]
6178 fn encoding_final_onion_hop_data_with_secret() {
6179 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
6180 let outbound_msg = msgs::OutboundOnionPayload::Receive {
6181 payment_data: Some(FinalOnionHopData {
6182 payment_secret: expected_payment_secret,
6183 total_msat: 0x1badca1f,
6184 }),
6185 payment_metadata: None,
6186 keysend_preimage: None,
6187 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6188 cltv_expiry_height: 0xffffffff,
6189 custom_tlvs: &vec![],
6190 };
6191 let encoded_value = outbound_msg.encode();
6192 let target_value = <Vec<u8>>::from_hex("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
6193 assert_eq!(encoded_value, target_value);
6194
6195 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6196 let inbound_msg =
6197 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6198 if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6199 payment_data: Some(FinalOnionHopData { payment_secret, total_msat: 0x1badca1f }),
6200 sender_intended_htlc_amt_msat,
6201 cltv_expiry_height,
6202 payment_metadata: None,
6203 keysend_preimage: None,
6204 custom_tlvs,
6205 }) = inbound_msg
6206 {
6207 assert_eq!(payment_secret, expected_payment_secret);
6208 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6209 assert_eq!(cltv_expiry_height, 0xffffffff);
6210 assert_eq!(custom_tlvs, vec![]);
6211 } else {
6212 panic!();
6213 }
6214 }
6215
6216 #[test]
6217 fn encoding_final_onion_hop_data_with_bad_custom_tlvs() {
6218 let bad_type_range_tlvs = vec![((1 << 16) - 4, vec![42]), ((1 << 16) - 2, vec![42; 32])];
6221 let mut msg = msgs::OutboundOnionPayload::Receive {
6222 payment_data: None,
6223 payment_metadata: None,
6224 keysend_preimage: None,
6225 custom_tlvs: &bad_type_range_tlvs,
6226 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6227 cltv_expiry_height: 0xffffffff,
6228 };
6229 let encoded_value = msg.encode();
6230 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6231 assert!(msgs::InboundOnionPayload::read(
6232 &mut Cursor::new(&encoded_value[..]),
6233 (None, &node_signer)
6234 )
6235 .is_err());
6236 let good_type_range_tlvs = vec![((1 << 16) - 3, vec![42]), ((1 << 16) - 1, vec![42; 32])];
6237 if let msgs::OutboundOnionPayload::Receive { ref mut custom_tlvs, .. } = msg {
6238 *custom_tlvs = &good_type_range_tlvs;
6239 }
6240 let encoded_value = msg.encode();
6241 let inbound_msg =
6242 ReadableArgs::read(&mut Cursor::new(&encoded_value[..]), (None, &node_signer)).unwrap();
6243 match inbound_msg {
6244 msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6245 custom_tlvs, ..
6246 }) => assert!(custom_tlvs.is_empty()),
6247 _ => panic!(),
6248 }
6249 }
6250
6251 #[test]
6252 fn encoding_final_onion_hop_data_with_custom_tlvs() {
6253 let expected_custom_tlvs =
6254 vec![(5482373483, vec![0x12, 0x34]), (5482373487, vec![0x42u8; 8])];
6255 let msg = msgs::OutboundOnionPayload::Receive {
6256 payment_data: None,
6257 payment_metadata: None,
6258 keysend_preimage: None,
6259 custom_tlvs: &expected_custom_tlvs,
6260 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6261 cltv_expiry_height: 0xffffffff,
6262 };
6263 let encoded_value = msg.encode();
6264 let target_value = <Vec<u8>>::from_hex("2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242").unwrap();
6265 assert_eq!(encoded_value, target_value);
6266 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6267 let inbound_msg: msgs::InboundOnionPayload =
6268 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6269 if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6270 payment_data: None,
6271 payment_metadata: None,
6272 keysend_preimage: None,
6273 custom_tlvs,
6274 sender_intended_htlc_amt_msat,
6275 cltv_expiry_height: outgoing_cltv_value,
6276 ..
6277 }) = inbound_msg
6278 {
6279 assert_eq!(custom_tlvs, expected_custom_tlvs);
6280 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6281 assert_eq!(outgoing_cltv_value, 0xffffffff);
6282 } else {
6283 panic!();
6284 }
6285 }
6286
6287 #[test]
6288 fn encoding_final_onion_hop_data_with_trampoline_packet() {
6289 let secp_ctx = Secp256k1::new();
6290 let (_private_key, public_key) = get_keys_from!(
6291 "0101010101010101010101010101010101010101010101010101010101010101",
6292 secp_ctx
6293 );
6294
6295 let compressed_public_key = public_key.serialize();
6296 assert_eq!(compressed_public_key.len(), 33);
6297
6298 let trampoline_packet = TrampolineOnionPacket {
6299 version: 0,
6300 public_key,
6301 hop_data: vec![1; 650], hmac: [2; 32],
6303 };
6304 let encoded_trampoline_packet = trampoline_packet.encode();
6305 assert_eq!(encoded_trampoline_packet.len(), 716);
6306
6307 {
6308 let decoded_trampoline_packet: TrampolineOnionPacket =
6310 <TrampolineOnionPacket as LengthReadable>::read_from_fixed_length_buffer(
6311 &mut &encoded_trampoline_packet[..],
6312 )
6313 .unwrap();
6314 assert_eq!(decoded_trampoline_packet.encode(), encoded_trampoline_packet);
6315 }
6316
6317 let msg = msgs::OutboundOnionPayload::TrampolineEntrypoint {
6318 multipath_trampoline_data: None,
6319 amt_to_forward: 0x0badf00d01020304,
6320 outgoing_cltv_value: 0xffffffff,
6321 trampoline_packet,
6322 };
6323 let encoded_payload = msg.encode();
6324
6325 let trampoline_type_bytes = &encoded_payload[19..=19];
6326 let mut trampoline_type_cursor = Cursor::new(trampoline_type_bytes);
6327 let trampoline_type_big_size: BigSize =
6328 Readable::read(&mut trampoline_type_cursor).unwrap();
6329 assert_eq!(trampoline_type_big_size.0, 20);
6330
6331 let trampoline_length_bytes = &encoded_payload[20..=22];
6332 let mut trampoline_length_cursor = Cursor::new(trampoline_length_bytes);
6333 let trampoline_length_big_size: BigSize =
6334 Readable::read(&mut trampoline_length_cursor).unwrap();
6335 assert_eq!(trampoline_length_big_size.0, encoded_trampoline_packet.len() as u64);
6336 }
6337
6338 #[test]
6339 fn encoding_final_onion_hop_data_with_eclair_trampoline_packet() {
6340 let public_key = PublicKey::from_slice(
6341 &<Vec<u8>>::from_hex(
6342 "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
6343 )
6344 .unwrap(),
6345 )
6346 .unwrap();
6347 let hop_data = <Vec<u8>>::from_hex("cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4c").unwrap();
6348 let hmac_vector =
6349 <Vec<u8>>::from_hex("bb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c")
6350 .unwrap();
6351 let mut hmac = [0; 32];
6352 hmac.copy_from_slice(&hmac_vector);
6353
6354 let compressed_public_key = public_key.serialize();
6355 assert_eq!(compressed_public_key.len(), 33);
6356
6357 let trampoline_packet = TrampolineOnionPacket { version: 0, public_key, hop_data, hmac };
6358 let encoded_trampoline_packet = trampoline_packet.encode();
6359 let expected_eclair_trampoline_packet = <Vec<u8>>::from_hex("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4cbb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c").unwrap();
6360 assert_eq!(encoded_trampoline_packet, expected_eclair_trampoline_packet);
6361 }
6362
6363 #[test]
6364 fn encoding_outbound_trampoline_payload() {
6365 let mut trampoline_features = Bolt12InvoiceFeatures::empty();
6366 trampoline_features.set_basic_mpp_optional();
6367 let introduction_node = PublicKey::from_slice(
6368 &<Vec<u8>>::from_hex(
6369 "032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",
6370 )
6371 .unwrap(),
6372 )
6373 .unwrap();
6374 let blinding_point = PublicKey::from_slice(
6375 &<Vec<u8>>::from_hex(
6376 "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
6377 )
6378 .unwrap(),
6379 )
6380 .unwrap();
6381 let trampoline_payload = OutboundTrampolinePayload::LegacyBlindedPathEntry {
6382 amt_to_forward: 150_000_000,
6383 outgoing_cltv_value: 800_000,
6384 payment_paths: vec![BlindedPaymentPath::from_blinded_path_and_payinfo(
6385 introduction_node,
6386 blinding_point,
6387 vec![],
6388 BlindedPayInfo {
6389 fee_base_msat: 500,
6390 fee_proportional_millionths: 1_000,
6391 cltv_expiry_delta: 36,
6392 htlc_minimum_msat: 1,
6393 htlc_maximum_msat: 500_000_000,
6394 features: BlindedHopFeatures::empty(),
6395 },
6396 )],
6397 invoice_features: Some(trampoline_features),
6398 };
6399 let serialized_payload = trampoline_payload.encode().to_lower_hex_string();
6400 assert_eq!(serialized_payload, "71020408f0d18004030c35001503020000165f032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e66868099102eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661900000001f4000003e800240000000000000001000000001dcd65000000");
6401 }
6402
6403 #[test]
6404 fn encode_trampoline_blinded_path_payload() {
6405 let trampoline_payload_eve = OutboundTrampolinePayload::BlindedReceive {
6406 sender_intended_htlc_amt_msat: 150_000_000,
6407 total_msat: 150_000_000,
6408 cltv_expiry_height: 800_000,
6409 encrypted_tlvs: &<Vec<u8>>::from_hex("bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c").unwrap(),
6410 intro_node_blinding_point: None,
6411 keysend_preimage: None,
6412 custom_tlvs: &vec![],
6413 };
6414 let eve_payload = trampoline_payload_eve.encode().to_lower_hex_string();
6415 assert_eq!(eve_payload, "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180");
6416
6417 let trampoline_payload_dave = OutboundTrampolinePayload::BlindedForward {
6418 encrypted_tlvs: &<Vec<u8>>::from_hex("0ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a").unwrap(),
6419 intro_node_blinding_point: Some(PublicKey::from_slice(&<Vec<u8>>::from_hex("02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e").unwrap()).unwrap()),
6420 };
6421 let dave_payload = trampoline_payload_dave.encode().to_lower_hex_string();
6422 assert_eq!(dave_payload, "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e")
6423 }
6424
6425 #[test]
6426 fn query_channel_range_end_blocknum() {
6427 let tests: Vec<(u32, u32, u32)> =
6428 vec![(10000, 1500, 11500), (0, 0xffffffff, 0xffffffff), (1, 0xffffffff, 0xffffffff)];
6429
6430 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
6431 let sut = msgs::QueryChannelRange {
6432 chain_hash: ChainHash::using_genesis_block(Network::Regtest),
6433 first_blocknum,
6434 number_of_blocks,
6435 };
6436 assert_eq!(sut.end_blocknum(), expected);
6437 }
6438 }
6439
6440 #[test]
6441 fn encoding_query_channel_range() {
6442 let mut query_channel_range = msgs::QueryChannelRange {
6443 chain_hash: ChainHash::using_genesis_block(Network::Regtest),
6444 first_blocknum: 100000,
6445 number_of_blocks: 1500,
6446 };
6447 let encoded_value = query_channel_range.encode();
6448 let target_value = <Vec<u8>>::from_hex(
6449 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000186a0000005dc",
6450 )
6451 .unwrap();
6452 assert_eq!(encoded_value, target_value);
6453
6454 query_channel_range =
6455 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6456 assert_eq!(query_channel_range.first_blocknum, 100000);
6457 assert_eq!(query_channel_range.number_of_blocks, 1500);
6458 }
6459
6460 #[test]
6461 fn encoding_reply_channel_range() {
6462 do_encoding_reply_channel_range(0);
6463 do_encoding_reply_channel_range(1);
6464 }
6465
6466 fn do_encoding_reply_channel_range(encoding_type: u8) {
6467 let mut target_value = <Vec<u8>>::from_hex(
6468 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000b8a06000005dc01",
6469 )
6470 .unwrap();
6471 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6472 let mut reply_channel_range = msgs::ReplyChannelRange {
6473 chain_hash: expected_chain_hash,
6474 first_blocknum: 756230,
6475 number_of_blocks: 1500,
6476 sync_complete: true,
6477 short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
6478 };
6479
6480 if encoding_type == 0 {
6481 target_value.append(
6482 &mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4")
6483 .unwrap(),
6484 );
6485 let encoded_value = reply_channel_range.encode();
6486 assert_eq!(encoded_value, target_value);
6487
6488 reply_channel_range =
6489 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6490 assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
6491 assert_eq!(reply_channel_range.first_blocknum, 756230);
6492 assert_eq!(reply_channel_range.number_of_blocks, 1500);
6493 assert_eq!(reply_channel_range.sync_complete, true);
6494 assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
6495 assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
6496 assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
6497 } else {
6498 target_value.append(
6499 &mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a")
6500 .unwrap(),
6501 );
6502 let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> =
6503 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]);
6504 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
6505 }
6506 }
6507
6508 #[test]
6509 fn encoding_query_short_channel_ids() {
6510 do_encoding_query_short_channel_ids(0);
6511 do_encoding_query_short_channel_ids(1);
6512 }
6513
6514 fn do_encoding_query_short_channel_ids(encoding_type: u8) {
6515 let mut target_value =
6516 <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f")
6517 .unwrap();
6518 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6519 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
6520 chain_hash: expected_chain_hash,
6521 short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
6522 };
6523
6524 if encoding_type == 0 {
6525 target_value.append(
6526 &mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4")
6527 .unwrap(),
6528 );
6529 let encoded_value = query_short_channel_ids.encode();
6530 assert_eq!(encoded_value, target_value);
6531
6532 query_short_channel_ids =
6533 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6534 assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
6535 assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
6536 assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
6537 assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
6538 } else {
6539 target_value.append(
6540 &mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a")
6541 .unwrap(),
6542 );
6543 let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> =
6544 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]);
6545 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
6546 }
6547 }
6548
6549 #[test]
6550 fn encoding_reply_short_channel_ids_end() {
6551 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6552 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
6553 chain_hash: expected_chain_hash,
6554 full_information: true,
6555 };
6556 let encoded_value = reply_short_channel_ids_end.encode();
6557 let target_value = <Vec<u8>>::from_hex(
6558 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f01",
6559 )
6560 .unwrap();
6561 assert_eq!(encoded_value, target_value);
6562
6563 reply_short_channel_ids_end =
6564 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6565 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
6566 assert_eq!(reply_short_channel_ids_end.full_information, true);
6567 }
6568
6569 #[test]
6570 fn encoding_gossip_timestamp_filter() {
6571 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6572 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
6573 chain_hash: expected_chain_hash,
6574 first_timestamp: 1590000000,
6575 timestamp_range: 0xffff_ffff,
6576 };
6577 let encoded_value = gossip_timestamp_filter.encode();
6578 let target_value = <Vec<u8>>::from_hex(
6579 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f5ec57980ffffffff",
6580 )
6581 .unwrap();
6582 assert_eq!(encoded_value, target_value);
6583
6584 gossip_timestamp_filter =
6585 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6586 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
6587 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
6588 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);
6589 }
6590
6591 #[test]
6592 fn decode_onion_hop_data_len_as_bigsize() {
6593 let big_payload = encode_big_payload().unwrap();
6601 let mut rd = Cursor::new(&big_payload[..]);
6602
6603 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6604 <msgs::InboundOnionPayload as ReadableArgs<(
6605 Option<PublicKey>,
6606 &test_utils::TestKeysInterface,
6607 )>>::read(&mut rd, (None, &&node_signer))
6608 .unwrap();
6609 }
6610 fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
6612 use crate::util::ser::HighZeroBytesDroppedBigSize;
6613 let payload = msgs::OutboundOnionPayload::Forward {
6614 short_channel_id: 0xdeadbeef1bad1dea,
6615 amt_to_forward: 1000,
6616 outgoing_cltv_value: 0xffffffff,
6617 };
6618 let mut encoded_payload = Vec::new();
6619 let test_bytes = vec![42u8; 1000];
6620 if let msgs::OutboundOnionPayload::Forward {
6621 short_channel_id,
6622 amt_to_forward,
6623 outgoing_cltv_value,
6624 } = payload
6625 {
6626 _encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
6627 (1, &test_bytes, required_vec),
6628 (2, HighZeroBytesDroppedBigSize(amt_to_forward), required),
6629 (4, HighZeroBytesDroppedBigSize(outgoing_cltv_value), required),
6630 (6, short_channel_id, required)
6631 });
6632 }
6633 Ok(encoded_payload)
6634 }
6635
6636 #[test]
6637 #[cfg(feature = "std")]
6638 fn test_socket_address_from_str() {
6639 let tcpip_v4 =
6640 SocketAddress::TcpIpV4 { addr: Ipv4Addr::new(127, 0, 0, 1).octets(), port: 1234 };
6641 assert_eq!(tcpip_v4, SocketAddress::from_str("127.0.0.1:1234").unwrap());
6642 assert_eq!(tcpip_v4, SocketAddress::from_str(&tcpip_v4.to_string()).unwrap());
6643
6644 let tcpip_v6 = SocketAddress::TcpIpV6 {
6645 addr: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).octets(),
6646 port: 1234,
6647 };
6648 assert_eq!(tcpip_v6, SocketAddress::from_str("[0:0:0:0:0:0:0:1]:1234").unwrap());
6649 assert_eq!(tcpip_v6, SocketAddress::from_str(&tcpip_v6.to_string()).unwrap());
6650
6651 let hostname = SocketAddress::Hostname {
6652 hostname: Hostname::try_from("lightning-node.mydomain.com".to_string()).unwrap(),
6653 port: 1234,
6654 };
6655 assert_eq!(hostname, SocketAddress::from_str("lightning-node.mydomain.com:1234").unwrap());
6656 assert_eq!(hostname, SocketAddress::from_str(&hostname.to_string()).unwrap());
6657
6658 let onion_v2 = SocketAddress::OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7]);
6659 assert_eq!(
6660 "OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7])",
6661 &onion_v2.to_string()
6662 );
6663 assert_eq!(
6664 Err(SocketAddressParseError::InvalidOnionV3),
6665 SocketAddress::from_str("FACEBOOKCOREWWWI.onion:9735")
6666 );
6667
6668 let onion_v3 = SocketAddress::OnionV3 {
6669 ed25519_pubkey: [
6670 121, 188, 198, 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247,
6671 246, 85, 111, 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31,
6672 ],
6673 checksum: 8519,
6674 version: 3,
6675 port: 1234,
6676 };
6677 let onion_v3_str = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:1234";
6678 let parsed = SocketAddress::from_str(onion_v3_str).unwrap();
6679 assert_eq!(onion_v3, parsed);
6680 assert_eq!(onion_v3_str, parsed.to_string());
6681 match parsed {
6682 SocketAddress::OnionV3 { version, .. } => assert_eq!(version, 3),
6683 _ => panic!("expected OnionV3"),
6684 }
6685
6686 assert_eq!(
6687 Err(SocketAddressParseError::InvalidOnionV3),
6688 SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6.onion:1234")
6689 );
6690 assert_eq!(
6691 Err(SocketAddressParseError::InvalidInput),
6692 SocketAddress::from_str("127.0.0.1@1234")
6693 );
6694 assert_eq!(Err(SocketAddressParseError::InvalidInput), "".parse::<SocketAddress>());
6695 assert!(SocketAddress::from_str(
6696 "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94"
6697 )
6698 .is_err());
6699 assert!(SocketAddress::from_str("wrong$%#.com:1234").is_err());
6700 assert_eq!(
6701 Err(SocketAddressParseError::InvalidPort),
6702 SocketAddress::from_str("example.com:wrong")
6703 );
6704 assert!("localhost".parse::<SocketAddress>().is_err());
6705 assert!("localhost:invalid-port".parse::<SocketAddress>().is_err());
6706 assert!("invalid-onion-v3-hostname.onion:8080".parse::<SocketAddress>().is_err());
6707 assert!("b32.example.onion:invalid-port".parse::<SocketAddress>().is_err());
6708 assert!("invalid-address".parse::<SocketAddress>().is_err());
6709 assert!(SocketAddress::from_str(
6710 "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234"
6711 )
6712 .is_err());
6713 }
6714
6715 #[test]
6716 #[cfg(feature = "std")]
6717 fn test_socket_address_to_socket_addrs() {
6718 assert_eq!(
6719 SocketAddress::TcpIpV4 { addr: [0u8; 4], port: 1337 }
6720 .to_socket_addrs()
6721 .unwrap()
6722 .next()
6723 .unwrap(),
6724 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 1337))
6725 );
6726 assert_eq!(
6727 SocketAddress::TcpIpV6 { addr: [0u8; 16], port: 1337 }
6728 .to_socket_addrs()
6729 .unwrap()
6730 .next()
6731 .unwrap(),
6732 SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from([0u8; 16]), 1337, 0, 0))
6733 );
6734 assert_eq!(
6735 SocketAddress::Hostname {
6736 hostname: Hostname::try_from("0.0.0.0".to_string()).unwrap(),
6737 port: 0,
6738 }
6739 .to_socket_addrs()
6740 .unwrap()
6741 .next()
6742 .unwrap(),
6743 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from([0u8; 4]), 0))
6744 );
6745 assert!(SocketAddress::OnionV2([0u8; 12]).to_socket_addrs().is_err());
6746 assert!(SocketAddress::OnionV3 {
6747 ed25519_pubkey: [
6748 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85, 111,
6749 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3
6750 ],
6751 checksum: 48326,
6752 version: 121,
6753 port: 1234
6754 }
6755 .to_socket_addrs()
6756 .is_err());
6757 }
6758}