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::{BlindedPaymentTlvs, DummyTlvs, ForwardTlvs, ReceiveTlvs};
36use crate::blinded_path::payment::{BlindedTrampolineTlvs, TrampolineForwardTlvs};
37use crate::ln::onion_utils;
38use crate::ln::types::ChannelId;
39use crate::offers::invoice_request::InvoiceRequest;
40use crate::onion_message;
41use crate::sign::{NodeSigner, Recipient};
42use crate::types::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
43use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
44
45#[allow(unused_imports)]
46use crate::prelude::*;
47
48use crate::io::{self, Cursor, Read};
49use crate::io_extras::read_to_end;
50use core::fmt;
51use core::fmt::Debug;
52use core::fmt::Display;
53use core::ops::Deref;
54#[cfg(feature = "std")]
55use core::str::FromStr;
56#[cfg(feature = "std")]
57use std::net::SocketAddr;
58
59use crate::crypto::streams::{ChaChaTriPolyReadAdapter, TriPolyAADUsed};
60use crate::util::base32;
61use crate::util::logger;
62use crate::util::ser::{
63 BigSize, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname, LengthLimitedRead,
64 LengthReadable, LengthReadableArgs, Readable, ReadableArgs, WithoutLength, Writeable, Writer,
65};
66
67use crate::routing::gossip::{NodeAlias, NodeId};
68
69pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
71
72#[derive(Clone, Debug, Hash, PartialEq, Eq)]
74pub enum DecodeError {
75 UnknownVersion,
79 UnknownRequiredFeature,
81 InvalidValue,
87 ShortRead,
89 BadLengthDescriptor,
91 Io(io::ErrorKind),
93 UnsupportedCompression,
95 DangerousValue,
105}
106
107#[derive(Clone, Debug, Hash, PartialEq, Eq)]
111pub struct Init {
112 pub features: InitFeatures,
114 pub networks: Option<Vec<ChainHash>>,
118 pub remote_network_address: Option<SocketAddress>,
125}
126
127#[derive(Clone, Debug, Hash, PartialEq, Eq)]
131pub struct ErrorMessage {
132 pub channel_id: ChannelId,
137 pub data: String,
143}
144
145#[derive(Clone, Debug, Hash, PartialEq, Eq)]
149pub struct WarningMessage {
150 pub channel_id: ChannelId,
154 pub data: String,
160}
161
162#[derive(Clone, Debug, Hash, PartialEq, Eq)]
166pub struct Ping {
167 pub ponglen: u16,
169 pub byteslen: u16,
173}
174
175#[derive(Clone, Debug, Hash, PartialEq, Eq)]
179pub struct Pong {
180 pub byteslen: u16,
184}
185
186#[derive(Clone, Debug, Hash, PartialEq, Eq)]
191pub struct CommonOpenChannelFields {
192 pub chain_hash: ChainHash,
194 pub temporary_channel_id: ChannelId,
198 pub funding_satoshis: u64,
201 pub dust_limit_satoshis: u64,
204 pub max_htlc_value_in_flight_msat: u64,
206 pub htlc_minimum_msat: u64,
208 pub commitment_feerate_sat_per_1000_weight: u32,
211 pub to_self_delay: u16,
214 pub max_accepted_htlcs: u16,
216 pub funding_pubkey: PublicKey,
218 pub revocation_basepoint: PublicKey,
220 pub payment_basepoint: PublicKey,
222 pub delayed_payment_basepoint: PublicKey,
225 pub htlc_basepoint: PublicKey,
227 pub first_per_commitment_point: PublicKey,
229 pub channel_flags: u8,
231 pub shutdown_scriptpubkey: Option<ScriptBuf>,
234 pub channel_type: Option<ChannelTypeFeatures>,
237}
238
239impl CommonOpenChannelFields {
240 pub fn channel_parameters(&self) -> ChannelParameters {
242 ChannelParameters {
243 dust_limit_satoshis: self.dust_limit_satoshis,
244 max_htlc_value_in_flight_msat: self.max_htlc_value_in_flight_msat,
245 htlc_minimum_msat: self.htlc_minimum_msat,
246 commitment_feerate_sat_per_1000_weight: self.commitment_feerate_sat_per_1000_weight,
247 to_self_delay: self.to_self_delay,
248 max_accepted_htlcs: self.max_accepted_htlcs,
249 }
250 }
251}
252
253#[derive(Clone, Debug, Hash, PartialEq, Eq)]
256pub struct ChannelParameters {
257 pub dust_limit_satoshis: u64,
260 pub max_htlc_value_in_flight_msat: u64,
262 pub htlc_minimum_msat: u64,
264 pub commitment_feerate_sat_per_1000_weight: u32,
267 pub to_self_delay: u16,
270 pub max_accepted_htlcs: u16,
272}
273
274#[derive(Clone, Debug, Hash, PartialEq, Eq)]
280pub struct OpenChannel {
281 pub common_fields: CommonOpenChannelFields,
283 pub push_msat: u64,
285 pub channel_reserve_satoshis: u64,
287}
288
289#[derive(Clone, Debug, Hash, PartialEq, Eq)]
295pub struct OpenChannelV2 {
296 pub common_fields: CommonOpenChannelFields,
298 pub funding_feerate_sat_per_1000_weight: u32,
300 pub locktime: u32,
302 pub second_per_commitment_point: PublicKey,
304 pub require_confirmed_inputs: Option<()>,
306 pub disable_channel_reserve: Option<()>,
308}
309
310#[derive(Clone, Debug, Hash, PartialEq, Eq)]
315pub struct CommonAcceptChannelFields {
316 pub temporary_channel_id: ChannelId,
318 pub dust_limit_satoshis: u64,
321 pub max_htlc_value_in_flight_msat: u64,
323 pub htlc_minimum_msat: u64,
325 pub minimum_depth: u32,
327 pub to_self_delay: u16,
330 pub max_accepted_htlcs: u16,
332 pub funding_pubkey: PublicKey,
334 pub revocation_basepoint: PublicKey,
336 pub payment_basepoint: PublicKey,
338 pub delayed_payment_basepoint: PublicKey,
341 pub htlc_basepoint: PublicKey,
343 pub first_per_commitment_point: PublicKey,
345 pub shutdown_scriptpubkey: Option<ScriptBuf>,
348 pub channel_type: Option<ChannelTypeFeatures>,
354}
355
356#[derive(Clone, Debug, Hash, PartialEq, Eq)]
362pub struct AcceptChannel {
363 pub common_fields: CommonAcceptChannelFields,
365 pub channel_reserve_satoshis: u64,
367}
368
369#[derive(Clone, Debug, Hash, PartialEq, Eq)]
375pub struct AcceptChannelV2 {
376 pub common_fields: CommonAcceptChannelFields,
378 pub funding_satoshis: u64,
380 pub second_per_commitment_point: PublicKey,
382 pub require_confirmed_inputs: Option<()>,
384 pub disable_channel_reserve: Option<()>,
386}
387
388#[derive(Clone, Debug, Hash, PartialEq, Eq)]
394pub struct FundingCreated {
395 pub temporary_channel_id: ChannelId,
397 pub funding_txid: Txid,
399 pub funding_output_index: u16,
401 pub signature: Signature,
403}
404
405#[derive(Clone, Debug, Hash, PartialEq, Eq)]
411pub struct FundingSigned {
412 pub channel_id: ChannelId,
414 pub signature: Signature,
416}
417
418#[derive(Clone, Debug, Hash, PartialEq, Eq)]
422pub struct ChannelReady {
423 pub channel_id: ChannelId,
425 pub next_per_commitment_point: PublicKey,
427 pub short_channel_id_alias: Option<u64>,
432}
433
434pub type SerialId = u64;
437
438#[derive(Clone, Debug, PartialEq, Eq)]
442pub struct Stfu {
443 pub channel_id: ChannelId,
445 pub initiator: bool,
447}
448
449#[derive(Clone, Debug, PartialEq, Eq)]
453pub struct SpliceInit {
454 pub channel_id: ChannelId,
456 pub funding_contribution_satoshis: i64,
459 pub funding_feerate_per_kw: u32,
461 pub locktime: u32,
463 pub funding_pubkey: PublicKey,
465 pub require_confirmed_inputs: Option<()>,
467}
468
469#[derive(Clone, Debug, PartialEq, Eq)]
473pub struct SpliceAck {
474 pub channel_id: ChannelId,
476 pub funding_contribution_satoshis: i64,
479 pub funding_pubkey: PublicKey,
481 pub require_confirmed_inputs: Option<()>,
483}
484
485#[derive(Clone, Debug, PartialEq, Eq)]
489pub struct SpliceLocked {
490 pub channel_id: ChannelId,
492 pub splice_txid: Txid,
494}
495
496#[derive(Clone, Debug, Hash, PartialEq, Eq)]
500pub struct TxAddInput {
501 pub channel_id: ChannelId,
503 pub serial_id: SerialId,
506 pub prevtx: Option<Transaction>,
509 pub prevtx_out: u32,
511 pub sequence: u32,
513 pub shared_input_txid: Option<Txid>,
515}
516
517#[derive(Clone, Debug, Hash, PartialEq, Eq)]
521pub struct TxAddOutput {
522 pub channel_id: ChannelId,
524 pub serial_id: SerialId,
527 pub sats: u64,
529 pub script: ScriptBuf,
531}
532
533#[derive(Clone, Debug, Hash, PartialEq, Eq)]
537pub struct TxRemoveInput {
538 pub channel_id: ChannelId,
540 pub serial_id: SerialId,
542}
543
544#[derive(Clone, Debug, Hash, PartialEq, Eq)]
548pub struct TxRemoveOutput {
549 pub channel_id: ChannelId,
551 pub serial_id: SerialId,
553}
554
555#[derive(Clone, Debug, Hash, PartialEq, Eq)]
560pub struct TxComplete {
561 pub channel_id: ChannelId,
563}
564
565#[derive(Clone, Debug, Hash, PartialEq, Eq)]
570pub struct TxSignatures {
571 pub channel_id: ChannelId,
573 pub tx_hash: Txid,
575 pub witnesses: Vec<Witness>,
577 pub shared_input_signature: Option<Signature>,
579}
580
581#[derive(Clone, Debug, Hash, PartialEq, Eq)]
586pub struct TxInitRbf {
587 pub channel_id: ChannelId,
589 pub locktime: u32,
591 pub feerate_sat_per_1000_weight: u32,
593 pub funding_output_contribution: Option<i64>,
596}
597
598#[derive(Clone, Debug, Hash, PartialEq, Eq)]
603pub struct TxAckRbf {
604 pub channel_id: ChannelId,
606 pub funding_output_contribution: Option<i64>,
609}
610
611#[derive(Clone, Debug, Hash, PartialEq, Eq)]
615pub struct TxAbort {
616 pub channel_id: ChannelId,
618 pub data: Vec<u8>,
620}
621
622#[derive(Clone, Debug, Hash, PartialEq, Eq)]
626pub struct Shutdown {
627 pub channel_id: ChannelId,
629 pub scriptpubkey: ScriptBuf,
633}
634
635#[derive(Clone, Debug, Hash, PartialEq, Eq)]
640pub struct ClosingSignedFeeRange {
641 pub min_fee_satoshis: u64,
644 pub max_fee_satoshis: u64,
647}
648
649#[derive(Clone, Debug, Hash, PartialEq, Eq)]
653pub struct ClosingSigned {
654 pub channel_id: ChannelId,
656 pub fee_satoshis: u64,
658 pub signature: Signature,
660 pub fee_range: Option<ClosingSignedFeeRange>,
663}
664
665#[derive(Clone, Debug, Hash, PartialEq, Eq)]
669pub struct ClosingComplete {
670 pub channel_id: ChannelId,
672 pub closer_scriptpubkey: ScriptBuf,
674 pub closee_scriptpubkey: ScriptBuf,
676 pub fee_satoshis: u64,
678 pub locktime: u32,
680 pub closer_output_only: Option<Signature>,
682 pub closee_output_only: Option<Signature>,
684 pub closer_and_closee_outputs: Option<Signature>,
686}
687
688#[derive(Clone, Debug, Hash, PartialEq, Eq)]
692pub struct ClosingSig {
693 pub channel_id: ChannelId,
695 pub closer_scriptpubkey: ScriptBuf,
697 pub closee_scriptpubkey: ScriptBuf,
699 pub fee_satoshis: u64,
701 pub locktime: u32,
703 pub closer_output_only: Option<Signature>,
705 pub closee_output_only: Option<Signature>,
707 pub closer_and_closee_outputs: Option<Signature>,
709}
710
711#[derive(Clone, Debug, Hash, PartialEq, Eq)]
716pub struct StartBatch {
717 pub channel_id: ChannelId,
719 pub batch_size: u16,
721 pub message_type: Option<u16>,
723}
724
725#[derive(Clone, Debug, Hash, PartialEq, Eq)]
729pub struct UpdateAddHTLC {
730 pub channel_id: ChannelId,
732 pub htlc_id: u64,
734 pub amount_msat: u64,
736 pub payment_hash: PaymentHash,
738 pub cltv_expiry: u32,
740 pub skimmed_fee_msat: Option<u64>,
745 pub onion_routing_packet: OnionPacket,
747 pub blinding_point: Option<PublicKey>,
750 pub hold_htlc: Option<()>,
755 pub accountable: Option<bool>,
762}
763
764struct AccountableBool<T>(T);
765
766impl Writeable for AccountableBool<&bool> {
767 #[inline]
768 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
769 let wire_value = if *self.0 { 7u8 } else { 0u8 };
770 writer.write_all(&[wire_value])
771 }
772}
773
774impl Readable for AccountableBool<bool> {
775 #[inline]
776 fn read<R: Read>(reader: &mut R) -> Result<AccountableBool<bool>, DecodeError> {
777 let mut buf = [0u8; 1];
778 reader.read_exact(&mut buf)?;
779 let bool_value = buf[0] == 7;
780 Ok(AccountableBool(bool_value))
781 }
782}
783
784impl From<bool> for AccountableBool<bool> {
785 fn from(val: bool) -> Self {
786 Self(val)
787 }
788}
789
790impl From<AccountableBool<bool>> for bool {
791 fn from(val: AccountableBool<bool>) -> Self {
792 val.0
793 }
794}
795
796#[derive(Clone, Debug, Hash, PartialEq, Eq)]
800pub struct OnionMessage {
801 pub blinding_point: PublicKey,
803 pub onion_routing_packet: onion_message::packet::Packet,
805}
806
807#[derive(Clone, Debug, Hash, PartialEq, Eq)]
811pub struct UpdateFulfillHTLC {
812 pub channel_id: ChannelId,
814 pub htlc_id: u64,
816 pub payment_preimage: PaymentPreimage,
818 pub attribution_data: Option<AttributionData>,
820}
821
822#[derive(Clone, Debug, Hash, PartialEq, Eq)]
832pub struct PeerStorage {
833 pub data: Vec<u8>,
835}
836
837#[derive(Clone, Debug, Hash, PartialEq, Eq)]
847pub struct PeerStorageRetrieval {
848 pub data: Vec<u8>,
850}
851
852#[derive(Clone, Debug, Hash, PartialEq, Eq)]
856pub struct UpdateFailHTLC {
857 pub channel_id: ChannelId,
859 pub htlc_id: u64,
861 pub(crate) reason: Vec<u8>,
862
863 pub attribution_data: Option<AttributionData>,
865}
866#[derive(Clone, Debug, Hash, PartialEq, Eq)]
870pub struct UpdateFailMalformedHTLC {
871 pub channel_id: ChannelId,
873 pub htlc_id: u64,
875 pub(crate) sha256_of_onion: [u8; 32],
876 pub failure_code: u16,
878}
879
880#[derive(Clone, Debug, Hash, PartialEq, Eq)]
884pub struct CommitmentSigned {
885 pub channel_id: ChannelId,
887 pub signature: Signature,
889 pub htlc_signatures: Vec<Signature>,
891 pub funding_txid: Option<Txid>,
893}
894
895#[derive(Clone, Debug, Hash, PartialEq, Eq)]
899pub struct RevokeAndACK {
900 pub channel_id: ChannelId,
902 pub per_commitment_secret: [u8; 32],
904 pub next_per_commitment_point: PublicKey,
906 pub release_htlc_message_paths: Vec<(u64, BlindedMessagePath)>,
913}
914
915#[derive(Clone, Debug, Hash, PartialEq, Eq)]
919pub struct UpdateFee {
920 pub channel_id: ChannelId,
922 pub feerate_per_kw: u32,
924}
925
926#[derive(Clone, Debug, Hash, PartialEq, Eq)]
930pub struct ChannelReestablish {
931 pub channel_id: ChannelId,
933 pub next_local_commitment_number: u64,
935 pub next_remote_commitment_number: u64,
937 pub your_last_per_commitment_secret: [u8; 32],
940 pub my_current_per_commitment_point: PublicKey,
942 pub next_funding: Option<NextFunding>,
956 pub my_current_funding_locked: Option<FundingLocked>,
963}
964
965#[derive(Clone, Debug, Hash, PartialEq, Eq)]
968pub struct NextFunding {
969 pub txid: Txid,
971
972 pub retransmit_flags: u8,
976}
977
978impl NextFunding {
979 pub fn retransmit(&mut self, flag: NextFundingFlag) {
981 self.retransmit_flags |= 1 << flag as u8;
982 }
983
984 pub fn should_retransmit(&self, flag: NextFundingFlag) -> bool {
986 self.retransmit_flags & (1 << flag as u8) != 0
987 }
988}
989
990#[repr(u8)]
992pub enum NextFundingFlag {
993 CommitmentSigned = 0,
995}
996
997#[derive(Clone, Debug, Hash, PartialEq, Eq)]
999pub struct FundingLocked {
1000 pub txid: Txid,
1003
1004 pub retransmit_flags: u8,
1008}
1009
1010impl FundingLocked {
1011 pub fn retransmit(&mut self, flag: FundingLockedFlags) {
1013 self.retransmit_flags |= 1 << flag as u8;
1014 }
1015
1016 pub fn should_retransmit(&self, flag: FundingLockedFlags) -> bool {
1018 self.retransmit_flags & (1 << flag as u8) != 0
1019 }
1020}
1021
1022#[repr(u8)]
1024pub enum FundingLockedFlags {
1025 AnnouncementSignatures = 0,
1027}
1028
1029#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1033pub struct AnnouncementSignatures {
1034 pub channel_id: ChannelId,
1036 pub short_channel_id: u64,
1038 pub node_signature: Signature,
1040 pub bitcoin_signature: Signature,
1042}
1043
1044#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1046pub enum SocketAddress {
1047 TcpIpV4 {
1049 addr: [u8; 4],
1051 port: u16,
1053 },
1054 TcpIpV6 {
1056 addr: [u8; 16],
1058 port: u16,
1060 },
1061 OnionV2([u8; 12]),
1066 OnionV3 {
1071 ed25519_pubkey: [u8; 32],
1073 checksum: u16,
1075 version: u8,
1077 port: u16,
1079 },
1080 Hostname {
1082 hostname: Hostname,
1084 port: u16,
1086 },
1087}
1088impl SocketAddress {
1089 pub(crate) fn get_id(&self) -> u8 {
1092 match self {
1093 &SocketAddress::TcpIpV4 { .. } => 1,
1094 &SocketAddress::TcpIpV6 { .. } => 2,
1095 &SocketAddress::OnionV2(_) => 3,
1096 &SocketAddress::OnionV3 { .. } => 4,
1097 &SocketAddress::Hostname { .. } => 5,
1098 }
1099 }
1100
1101 fn len(&self) -> u16 {
1103 match self {
1104 &SocketAddress::TcpIpV4 { .. } => 6,
1105 &SocketAddress::TcpIpV6 { .. } => 18,
1106 &SocketAddress::OnionV2(_) => 12,
1107 &SocketAddress::OnionV3 { .. } => 37,
1108 &SocketAddress::Hostname { ref hostname, .. } => u16::from(hostname.len()) + 3,
1110 }
1111 }
1112
1113 pub(crate) const MAX_LEN: u16 = 258;
1117
1118 pub(crate) fn is_tor(&self) -> bool {
1119 match self {
1120 &SocketAddress::TcpIpV4 { .. } => false,
1121 &SocketAddress::TcpIpV6 { .. } => false,
1122 &SocketAddress::OnionV2(_) => true,
1123 &SocketAddress::OnionV3 { .. } => true,
1124 &SocketAddress::Hostname { .. } => false,
1125 }
1126 }
1127}
1128
1129impl Writeable for SocketAddress {
1130 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1131 match self {
1132 &SocketAddress::TcpIpV4 { ref addr, ref port } => {
1133 1u8.write(writer)?;
1134 addr.write(writer)?;
1135 port.write(writer)?;
1136 },
1137 &SocketAddress::TcpIpV6 { ref addr, ref port } => {
1138 2u8.write(writer)?;
1139 addr.write(writer)?;
1140 port.write(writer)?;
1141 },
1142 &SocketAddress::OnionV2(bytes) => {
1143 3u8.write(writer)?;
1144 bytes.write(writer)?;
1145 },
1146 &SocketAddress::OnionV3 { ref ed25519_pubkey, ref checksum, ref version, ref port } => {
1147 4u8.write(writer)?;
1148 ed25519_pubkey.write(writer)?;
1149 checksum.write(writer)?;
1150 version.write(writer)?;
1151 port.write(writer)?;
1152 },
1153 &SocketAddress::Hostname { ref hostname, ref port } => {
1154 5u8.write(writer)?;
1155 hostname.write(writer)?;
1156 port.write(writer)?;
1157 },
1158 }
1159 Ok(())
1160 }
1161}
1162
1163impl Readable for Result<SocketAddress, u8> {
1164 fn read<R: Read>(reader: &mut R) -> Result<Result<SocketAddress, u8>, DecodeError> {
1165 let byte = <u8 as Readable>::read(reader)?;
1166 match byte {
1167 1 => Ok(Ok(SocketAddress::TcpIpV4 {
1168 addr: Readable::read(reader)?,
1169 port: Readable::read(reader)?,
1170 })),
1171 2 => Ok(Ok(SocketAddress::TcpIpV6 {
1172 addr: Readable::read(reader)?,
1173 port: Readable::read(reader)?,
1174 })),
1175 3 => Ok(Ok(SocketAddress::OnionV2(Readable::read(reader)?))),
1176 4 => Ok(Ok(SocketAddress::OnionV3 {
1177 ed25519_pubkey: Readable::read(reader)?,
1178 checksum: Readable::read(reader)?,
1179 version: Readable::read(reader)?,
1180 port: Readable::read(reader)?,
1181 })),
1182 5 => Ok(Ok(SocketAddress::Hostname {
1183 hostname: Readable::read(reader)?,
1184 port: Readable::read(reader)?,
1185 })),
1186 _ => return Ok(Err(byte)),
1187 }
1188 }
1189}
1190
1191impl Readable for SocketAddress {
1192 fn read<R: Read>(reader: &mut R) -> Result<SocketAddress, DecodeError> {
1193 match Readable::read(reader) {
1194 Ok(Ok(res)) => Ok(res),
1195 Ok(Err(_)) => Err(DecodeError::UnknownVersion),
1196 Err(e) => Err(e),
1197 }
1198 }
1199}
1200
1201#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1203pub enum SocketAddressParseError {
1204 SocketAddrParse,
1206 InvalidInput,
1208 InvalidPort,
1210 InvalidOnionV3,
1212}
1213
1214impl fmt::Display for SocketAddressParseError {
1215 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1216 match self {
1217 SocketAddressParseError::SocketAddrParse => write!(f, "Socket address (IPv4/IPv6) parsing error"),
1218 SocketAddressParseError::InvalidInput => write!(f, "Invalid input format. \
1219 Expected: \"<ipv4>:<port>\", \"[<ipv6>]:<port>\", \"<onion address>.onion:<port>\" or \"<hostname>:<port>\""),
1220 SocketAddressParseError::InvalidPort => write!(f, "Invalid port"),
1221 SocketAddressParseError::InvalidOnionV3 => write!(f, "Invalid onion v3 address"),
1222 }
1223 }
1224}
1225
1226#[cfg(feature = "std")]
1227impl std::error::Error for SocketAddressParseError {}
1228
1229#[cfg(feature = "std")]
1230impl From<std::net::SocketAddrV4> for SocketAddress {
1231 fn from(addr: std::net::SocketAddrV4) -> Self {
1232 SocketAddress::TcpIpV4 { addr: addr.ip().octets(), port: addr.port() }
1233 }
1234}
1235
1236#[cfg(feature = "std")]
1237impl From<std::net::SocketAddrV6> for SocketAddress {
1238 fn from(addr: std::net::SocketAddrV6) -> Self {
1239 SocketAddress::TcpIpV6 { addr: addr.ip().octets(), port: addr.port() }
1240 }
1241}
1242
1243#[cfg(feature = "std")]
1244impl From<std::net::SocketAddr> for SocketAddress {
1245 fn from(addr: std::net::SocketAddr) -> Self {
1246 match addr {
1247 std::net::SocketAddr::V4(addr) => addr.into(),
1248 std::net::SocketAddr::V6(addr) => addr.into(),
1249 }
1250 }
1251}
1252
1253#[cfg(feature = "std")]
1254impl std::net::ToSocketAddrs for SocketAddress {
1255 type Iter = std::vec::IntoIter<std::net::SocketAddr>;
1256
1257 fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
1258 match self {
1259 SocketAddress::TcpIpV4 { addr, port } => {
1260 let ip_addr = std::net::Ipv4Addr::from(*addr);
1261 let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1262 Ok(vec![socket_addr].into_iter())
1263 },
1264 SocketAddress::TcpIpV6 { addr, port } => {
1265 let ip_addr = std::net::Ipv6Addr::from(*addr);
1266 let socket_addr = SocketAddr::new(ip_addr.into(), *port);
1267 Ok(vec![socket_addr].into_iter())
1268 },
1269 SocketAddress::Hostname { ref hostname, port } => {
1270 (hostname.as_str(), *port).to_socket_addrs()
1271 },
1272 SocketAddress::OnionV2(..) => Err(std::io::Error::other(
1273 "Resolution of OnionV2 addresses is currently unsupported.",
1274 )),
1275 SocketAddress::OnionV3 { .. } => Err(std::io::Error::other(
1276 "Resolution of OnionV3 addresses is currently unsupported.",
1277 )),
1278 }
1279 }
1280}
1281
1282pub fn parse_onion_address(
1286 host: &str, port: u16,
1287) -> Result<SocketAddress, SocketAddressParseError> {
1288 if !host.ends_with(".onion") {
1289 return Err(SocketAddressParseError::InvalidInput);
1290 }
1291 let domain = &host[..host.len() - ".onion".len()];
1292 if domain.len() != 56 {
1293 return Err(SocketAddressParseError::InvalidOnionV3);
1294 }
1295 let onion = base32::Alphabet::RFC4648 { padding: false }
1296 .decode(domain)
1297 .map_err(|_| SocketAddressParseError::InvalidOnionV3)?;
1298 if onion.len() != 35 {
1299 return Err(SocketAddressParseError::InvalidOnionV3);
1300 }
1301
1302 let mut ed25519_pubkey = [0u8; 32];
1303 ed25519_pubkey.copy_from_slice(&onion[0..32]);
1304
1305 let checksum = u16::from_be_bytes([onion[32], onion[33]]);
1306 let version = onion[34];
1307
1308 Ok(SocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port })
1309}
1310
1311impl Display for SocketAddress {
1312 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1313 match self {
1314 SocketAddress::TcpIpV4{addr, port} => write!(
1315 f, "{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)?,
1316 SocketAddress::TcpIpV6{addr, port} => write!(
1317 f,
1318 "[{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}]:{}",
1319 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
1320 )?,
1321 SocketAddress::OnionV2(bytes) => write!(f, "OnionV2({:?})", bytes)?,
1322 SocketAddress::OnionV3 {
1323 ed25519_pubkey,
1324 checksum,
1325 version,
1326 port,
1327 } => {
1328 let mut addr = Vec::with_capacity(35);
1329 addr.extend_from_slice(ed25519_pubkey);
1330 let [c0, c1] = checksum.to_be_bytes();
1331 addr.push(c0);
1332 addr.push(c1);
1333 addr.push(*version);
1334 let onion = base32::Alphabet::RFC4648 { padding: false }.encode(&addr).to_lowercase();
1335 write!(f, "{}.onion:{}", onion, port)?
1336 },
1337 SocketAddress::Hostname { hostname, port } => write!(f, "{}:{}", hostname, port)?,
1338 }
1339 Ok(())
1340 }
1341}
1342
1343#[cfg(feature = "std")]
1344impl FromStr for SocketAddress {
1345 type Err = SocketAddressParseError;
1346
1347 fn from_str(s: &str) -> Result<Self, Self::Err> {
1348 match std::net::SocketAddr::from_str(s) {
1349 Ok(addr) => Ok(addr.into()),
1350 Err(_) => {
1351 let trimmed_input = match s.rfind(":") {
1352 Some(pos) => pos,
1353 None => return Err(SocketAddressParseError::InvalidInput),
1354 };
1355 let host = &s[..trimmed_input];
1356 let port: u16 = s[trimmed_input + 1..]
1357 .parse()
1358 .map_err(|_| SocketAddressParseError::InvalidPort)?;
1359 if host.ends_with(".onion") {
1360 return parse_onion_address(host, port);
1361 };
1362 if let Ok(hostname) = Hostname::try_from(s[..trimmed_input].to_string()) {
1363 return Ok(SocketAddress::Hostname { hostname, port });
1364 };
1365 return Err(SocketAddressParseError::SocketAddrParse);
1366 },
1367 }
1368 }
1369}
1370
1371pub enum UnsignedGossipMessage<'a> {
1373 ChannelAnnouncement(&'a UnsignedChannelAnnouncement),
1375 ChannelUpdate(&'a UnsignedChannelUpdate),
1377 NodeAnnouncement(&'a UnsignedNodeAnnouncement),
1379}
1380
1381impl<'a> Writeable for UnsignedGossipMessage<'a> {
1382 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1383 match self {
1384 UnsignedGossipMessage::ChannelAnnouncement(ref msg) => msg.write(writer),
1385 UnsignedGossipMessage::ChannelUpdate(ref msg) => msg.write(writer),
1386 UnsignedGossipMessage::NodeAnnouncement(ref msg) => msg.write(writer),
1387 }
1388 }
1389}
1390
1391#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1395pub struct UnsignedNodeAnnouncement {
1396 pub features: NodeFeatures,
1398 pub timestamp: u32,
1400 pub node_id: NodeId,
1403 pub rgb: [u8; 3],
1405 pub alias: NodeAlias,
1409 pub addresses: Vec<SocketAddress>,
1411 pub excess_address_data: Vec<u8>,
1416 pub excess_data: Vec<u8>,
1421}
1422#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1423pub struct NodeAnnouncement {
1427 pub signature: Signature,
1429 pub contents: UnsignedNodeAnnouncement,
1431}
1432
1433#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1437pub struct UnsignedChannelAnnouncement {
1438 pub features: ChannelFeatures,
1440 pub chain_hash: ChainHash,
1442 pub short_channel_id: u64,
1444 pub node_id_1: NodeId,
1446 pub node_id_2: NodeId,
1448 pub bitcoin_key_1: NodeId,
1450 pub bitcoin_key_2: NodeId,
1452 pub excess_data: Vec<u8>,
1457}
1458#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1462pub struct ChannelAnnouncement {
1463 pub node_signature_1: Signature,
1465 pub node_signature_2: Signature,
1467 pub bitcoin_signature_1: Signature,
1469 pub bitcoin_signature_2: Signature,
1471 pub contents: UnsignedChannelAnnouncement,
1473}
1474
1475#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1479pub struct UnsignedChannelUpdate {
1480 pub chain_hash: ChainHash,
1482 pub short_channel_id: u64,
1484 pub timestamp: u32,
1486 pub message_flags: u8,
1488 pub channel_flags: u8,
1491 pub cltv_expiry_delta: u16,
1500 pub htlc_minimum_msat: u64,
1502 pub htlc_maximum_msat: u64,
1506 pub fee_base_msat: u32,
1508 pub fee_proportional_millionths: u32,
1510 pub excess_data: Vec<u8>,
1515}
1516#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1520pub struct ChannelUpdate {
1521 pub signature: Signature,
1523 pub contents: UnsignedChannelUpdate,
1525}
1526
1527#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1534pub struct QueryChannelRange {
1535 pub chain_hash: ChainHash,
1537 pub first_blocknum: u32,
1539 pub number_of_blocks: u32,
1541}
1542
1543#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1555pub struct ReplyChannelRange {
1556 pub chain_hash: ChainHash,
1558 pub first_blocknum: u32,
1560 pub number_of_blocks: u32,
1562 pub sync_complete: bool,
1564 pub short_channel_ids: Vec<u64>,
1566}
1567
1568#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1580pub struct QueryShortChannelIds {
1581 pub chain_hash: ChainHash,
1583 pub short_channel_ids: Vec<u64>,
1585}
1586
1587#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1594pub struct ReplyShortChannelIdsEnd {
1595 pub chain_hash: ChainHash,
1597 pub full_information: bool,
1600}
1601
1602#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1608pub struct GossipTimestampFilter {
1609 pub chain_hash: ChainHash,
1611 pub first_timestamp: u32,
1613 pub timestamp_range: u32,
1615}
1616
1617enum EncodingType {
1622 Uncompressed = 0x00,
1623}
1624
1625#[derive(Clone, Debug, Hash, PartialEq)]
1627pub enum ErrorAction {
1628 DisconnectPeer {
1630 msg: Option<ErrorMessage>,
1632 },
1633 DisconnectPeerWithWarning {
1635 msg: WarningMessage,
1637 },
1638 IgnoreError,
1641 IgnoreAndLog(logger::Level),
1644 IgnoreDuplicateGossip,
1648 SendErrorMessage {
1650 msg: ErrorMessage,
1652 },
1653 SendWarningMessage {
1655 msg: WarningMessage,
1657 log_level: logger::Level,
1661 },
1662}
1663
1664#[derive(Clone, Debug)]
1666pub struct LightningError {
1667 pub err: String,
1669 pub action: ErrorAction,
1671}
1672
1673#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1676pub struct CommitmentUpdate {
1677 pub update_add_htlcs: Vec<UpdateAddHTLC>,
1679 pub update_fulfill_htlcs: Vec<UpdateFulfillHTLC>,
1681 pub update_fail_htlcs: Vec<UpdateFailHTLC>,
1683 pub update_fail_malformed_htlcs: Vec<UpdateFailMalformedHTLC>,
1685 pub update_fee: Option<UpdateFee>,
1687 pub commitment_signed: Vec<CommitmentSigned>,
1689}
1690
1691#[derive(Clone, Debug)]
1699#[cfg_attr(any(test, feature = "_test_utils"), derive(PartialEq))]
1700pub enum MessageSendEvent {
1701 SendAcceptChannel {
1704 node_id: PublicKey,
1706 msg: AcceptChannel,
1708 },
1709 SendAcceptChannelV2 {
1712 node_id: PublicKey,
1714 msg: AcceptChannelV2,
1716 },
1717 SendOpenChannel {
1720 node_id: PublicKey,
1722 msg: OpenChannel,
1724 },
1725 SendOpenChannelV2 {
1728 node_id: PublicKey,
1730 msg: OpenChannelV2,
1732 },
1733 SendFundingCreated {
1735 node_id: PublicKey,
1737 msg: FundingCreated,
1739 },
1740 SendFundingSigned {
1742 node_id: PublicKey,
1744 msg: FundingSigned,
1746 },
1747 SendStfu {
1749 node_id: PublicKey,
1751 msg: Stfu,
1753 },
1754 SendSpliceInit {
1756 node_id: PublicKey,
1758 msg: SpliceInit,
1760 },
1761 SendSpliceAck {
1763 node_id: PublicKey,
1765 msg: SpliceAck,
1767 },
1768 SendSpliceLocked {
1770 node_id: PublicKey,
1772 msg: SpliceLocked,
1774 },
1775 SendTxAddInput {
1777 node_id: PublicKey,
1779 msg: TxAddInput,
1781 },
1782 SendTxAddOutput {
1784 node_id: PublicKey,
1786 msg: TxAddOutput,
1788 },
1789 SendTxRemoveInput {
1791 node_id: PublicKey,
1793 msg: TxRemoveInput,
1795 },
1796 SendTxRemoveOutput {
1798 node_id: PublicKey,
1800 msg: TxRemoveOutput,
1802 },
1803 SendTxComplete {
1805 node_id: PublicKey,
1807 msg: TxComplete,
1809 },
1810 SendTxSignatures {
1812 node_id: PublicKey,
1814 msg: TxSignatures,
1816 },
1817 SendTxInitRbf {
1819 node_id: PublicKey,
1821 msg: TxInitRbf,
1823 },
1824 SendTxAckRbf {
1826 node_id: PublicKey,
1828 msg: TxAckRbf,
1830 },
1831 SendTxAbort {
1833 node_id: PublicKey,
1835 msg: TxAbort,
1837 },
1838 SendChannelReady {
1840 node_id: PublicKey,
1842 msg: ChannelReady,
1844 },
1845 SendAnnouncementSignatures {
1847 node_id: PublicKey,
1849 msg: AnnouncementSignatures,
1851 },
1852 UpdateHTLCs {
1855 node_id: PublicKey,
1857 channel_id: ChannelId,
1859 updates: CommitmentUpdate,
1861 },
1862 SendRevokeAndACK {
1864 node_id: PublicKey,
1866 msg: RevokeAndACK,
1868 },
1869 SendClosingSigned {
1871 node_id: PublicKey,
1873 msg: ClosingSigned,
1875 },
1876 #[cfg(simple_close)]
1878 SendClosingComplete {
1879 node_id: PublicKey,
1881 msg: ClosingComplete,
1883 },
1884 #[cfg(simple_close)]
1886 SendClosingSig {
1887 node_id: PublicKey,
1889 msg: ClosingSig,
1891 },
1892 SendShutdown {
1894 node_id: PublicKey,
1896 msg: Shutdown,
1898 },
1899 SendChannelReestablish {
1901 node_id: PublicKey,
1903 msg: ChannelReestablish,
1905 },
1906 SendChannelAnnouncement {
1909 node_id: PublicKey,
1911 msg: ChannelAnnouncement,
1913 update_msg: ChannelUpdate,
1915 },
1916 BroadcastChannelAnnouncement {
1927 msg: ChannelAnnouncement,
1929 update_msg: Option<ChannelUpdate>,
1931 },
1932 BroadcastChannelUpdate {
1934 msg: ChannelUpdate,
1936 node_id_1: NodeId,
1941 node_id_2: NodeId,
1946 },
1947 BroadcastNodeAnnouncement {
1949 msg: NodeAnnouncement,
1951 },
1952 SendChannelUpdate {
1956 node_id: PublicKey,
1958 msg: ChannelUpdate,
1960 },
1961 HandleError {
1963 node_id: PublicKey,
1965 action: ErrorAction,
1967 },
1968 SendChannelRangeQuery {
1970 node_id: PublicKey,
1972 msg: QueryChannelRange,
1974 },
1975 SendShortIdsQuery {
1978 node_id: PublicKey,
1980 msg: QueryShortChannelIds,
1982 },
1983 SendReplyChannelRange {
1986 node_id: PublicKey,
1988 msg: ReplyChannelRange,
1990 },
1991 SendGossipTimestampFilter {
1994 node_id: PublicKey,
1996 msg: GossipTimestampFilter,
1998 },
1999 SendPeerStorage {
2003 node_id: PublicKey,
2005 msg: PeerStorage,
2007 },
2008 SendPeerStorageRetrieval {
2011 node_id: PublicKey,
2013 msg: PeerStorageRetrieval,
2015 },
2016}
2017
2018pub trait BaseMessageHandler {
2024 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2027
2028 fn peer_disconnected(&self, their_node_id: PublicKey);
2030
2031 fn provided_node_features(&self) -> NodeFeatures;
2035
2036 fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures;
2042
2043 fn peer_connected(&self, their_node_id: PublicKey, msg: &Init, inbound: bool)
2053 -> Result<(), ()>;
2054}
2055
2056impl<T: BaseMessageHandler + ?Sized, B: Deref<Target = T>> BaseMessageHandler for B {
2057 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
2058 self.deref().get_and_clear_pending_msg_events()
2059 }
2060 fn peer_disconnected(&self, their_node_id: PublicKey) {
2061 self.deref().peer_disconnected(their_node_id)
2062 }
2063 fn provided_node_features(&self) -> NodeFeatures {
2064 self.deref().provided_node_features()
2065 }
2066 fn provided_init_features(&self, their_node_id: PublicKey) -> InitFeatures {
2067 self.deref().provided_init_features(their_node_id)
2068 }
2069 fn peer_connected(
2070 &self, their_node_id: PublicKey, msg: &Init, inbound: bool,
2071 ) -> Result<(), ()> {
2072 self.deref().peer_connected(their_node_id, msg, inbound)
2073 }
2074}
2075
2076pub trait ChannelMessageHandler: BaseMessageHandler {
2081 fn handle_open_channel(&self, their_node_id: PublicKey, msg: &OpenChannel);
2084 fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &OpenChannelV2);
2086 fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &AcceptChannel);
2088 fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &AcceptChannelV2);
2090 fn handle_funding_created(&self, their_node_id: PublicKey, msg: &FundingCreated);
2092 fn handle_funding_signed(&self, their_node_id: PublicKey, msg: &FundingSigned);
2094 fn handle_channel_ready(&self, their_node_id: PublicKey, msg: &ChannelReady);
2096
2097 fn handle_peer_storage(&self, their_node_id: PublicKey, msg: PeerStorage);
2100 fn handle_peer_storage_retrieval(&self, their_node_id: PublicKey, msg: PeerStorageRetrieval);
2102
2103 fn handle_shutdown(&self, their_node_id: PublicKey, msg: &Shutdown);
2106 fn handle_closing_signed(&self, their_node_id: PublicKey, msg: &ClosingSigned);
2108 #[cfg(simple_close)]
2110 fn handle_closing_complete(&self, their_node_id: PublicKey, msg: ClosingComplete);
2111 #[cfg(simple_close)]
2113 fn handle_closing_sig(&self, their_node_id: PublicKey, msg: ClosingSig);
2114
2115 fn handle_stfu(&self, their_node_id: PublicKey, msg: &Stfu);
2118
2119 fn handle_splice_init(&self, their_node_id: PublicKey, msg: &SpliceInit);
2122 fn handle_splice_ack(&self, their_node_id: PublicKey, msg: &SpliceAck);
2124 fn handle_splice_locked(&self, their_node_id: PublicKey, msg: &SpliceLocked);
2126
2127 fn handle_tx_add_input(&self, their_node_id: PublicKey, msg: &TxAddInput);
2130 fn handle_tx_add_output(&self, their_node_id: PublicKey, msg: &TxAddOutput);
2132 fn handle_tx_remove_input(&self, their_node_id: PublicKey, msg: &TxRemoveInput);
2134 fn handle_tx_remove_output(&self, their_node_id: PublicKey, msg: &TxRemoveOutput);
2136 fn handle_tx_complete(&self, their_node_id: PublicKey, msg: &TxComplete);
2138 fn handle_tx_signatures(&self, their_node_id: PublicKey, msg: &TxSignatures);
2140 fn handle_tx_init_rbf(&self, their_node_id: PublicKey, msg: &TxInitRbf);
2142 fn handle_tx_ack_rbf(&self, their_node_id: PublicKey, msg: &TxAckRbf);
2144 fn handle_tx_abort(&self, their_node_id: PublicKey, msg: &TxAbort);
2146
2147 fn handle_update_add_htlc(&self, their_node_id: PublicKey, msg: &UpdateAddHTLC);
2150 fn handle_update_fulfill_htlc(&self, their_node_id: PublicKey, msg: UpdateFulfillHTLC);
2152 fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailHTLC);
2154 fn handle_update_fail_malformed_htlc(
2156 &self, their_node_id: PublicKey, msg: &UpdateFailMalformedHTLC,
2157 );
2158 fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &CommitmentSigned);
2160 fn handle_commitment_signed_batch(
2162 &self, their_node_id: PublicKey, channel_id: ChannelId, batch: Vec<CommitmentSigned>,
2163 );
2164 fn handle_revoke_and_ack(&self, their_node_id: PublicKey, msg: &RevokeAndACK);
2166
2167 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
2168 fn handle_commitment_signed_batch_test(
2169 &self, their_node_id: PublicKey, batch: &Vec<CommitmentSigned>,
2170 ) {
2171 assert!(!batch.is_empty());
2172 if batch.len() == 1 {
2173 self.handle_commitment_signed(their_node_id, &batch[0]);
2174 } else {
2175 let channel_id = batch[0].channel_id;
2176 self.handle_commitment_signed_batch(their_node_id, channel_id, batch.clone());
2177 }
2178 }
2179
2180 fn handle_update_fee(&self, their_node_id: PublicKey, msg: &UpdateFee);
2182
2183 fn handle_announcement_signatures(
2186 &self, their_node_id: PublicKey, msg: &AnnouncementSignatures,
2187 );
2188
2189 fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &ChannelReestablish);
2192
2193 fn handle_channel_update(&self, their_node_id: PublicKey, msg: &ChannelUpdate);
2195
2196 fn handle_error(&self, their_node_id: PublicKey, msg: &ErrorMessage);
2199
2200 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>>;
2206
2207 fn message_received(&self);
2214}
2215
2216impl<T: ChannelMessageHandler + ?Sized, C: Deref<Target = T>> ChannelMessageHandler for C {
2217 fn handle_open_channel(&self, their_node_id: PublicKey, msg: &OpenChannel) {
2218 self.deref().handle_open_channel(their_node_id, msg)
2219 }
2220 fn handle_open_channel_v2(&self, their_node_id: PublicKey, msg: &OpenChannelV2) {
2221 self.deref().handle_open_channel_v2(their_node_id, msg)
2222 }
2223 fn handle_accept_channel(&self, their_node_id: PublicKey, msg: &AcceptChannel) {
2224 self.deref().handle_accept_channel(their_node_id, msg)
2225 }
2226 fn handle_accept_channel_v2(&self, their_node_id: PublicKey, msg: &AcceptChannelV2) {
2227 self.deref().handle_accept_channel_v2(their_node_id, msg)
2228 }
2229 fn handle_funding_created(&self, their_node_id: PublicKey, msg: &FundingCreated) {
2230 self.deref().handle_funding_created(their_node_id, msg)
2231 }
2232 fn handle_funding_signed(&self, their_node_id: PublicKey, msg: &FundingSigned) {
2233 self.deref().handle_funding_signed(their_node_id, msg)
2234 }
2235 fn handle_channel_ready(&self, their_node_id: PublicKey, msg: &ChannelReady) {
2236 self.deref().handle_channel_ready(their_node_id, msg)
2237 }
2238 fn handle_peer_storage(&self, their_node_id: PublicKey, msg: PeerStorage) {
2239 self.deref().handle_peer_storage(their_node_id, msg)
2240 }
2241 fn handle_peer_storage_retrieval(&self, their_node_id: PublicKey, msg: PeerStorageRetrieval) {
2242 self.deref().handle_peer_storage_retrieval(their_node_id, msg)
2243 }
2244 fn handle_shutdown(&self, their_node_id: PublicKey, msg: &Shutdown) {
2245 self.deref().handle_shutdown(their_node_id, msg)
2246 }
2247 fn handle_closing_signed(&self, their_node_id: PublicKey, msg: &ClosingSigned) {
2248 self.deref().handle_closing_signed(their_node_id, msg)
2249 }
2250 #[cfg(simple_close)]
2251 fn handle_closing_complete(&self, their_node_id: PublicKey, msg: ClosingComplete) {
2252 self.deref().handle_closing_complete(their_node_id, msg)
2253 }
2254 #[cfg(simple_close)]
2255 fn handle_closing_sig(&self, their_node_id: PublicKey, msg: ClosingSig) {
2256 self.deref().handle_closing_sig(their_node_id, msg)
2257 }
2258 fn handle_stfu(&self, their_node_id: PublicKey, msg: &Stfu) {
2259 self.deref().handle_stfu(their_node_id, msg)
2260 }
2261 fn handle_splice_init(&self, their_node_id: PublicKey, msg: &SpliceInit) {
2262 self.deref().handle_splice_init(their_node_id, msg)
2263 }
2264 fn handle_splice_ack(&self, their_node_id: PublicKey, msg: &SpliceAck) {
2265 self.deref().handle_splice_ack(their_node_id, msg)
2266 }
2267 fn handle_splice_locked(&self, their_node_id: PublicKey, msg: &SpliceLocked) {
2268 self.deref().handle_splice_locked(their_node_id, msg)
2269 }
2270 fn handle_tx_add_input(&self, their_node_id: PublicKey, msg: &TxAddInput) {
2271 self.deref().handle_tx_add_input(their_node_id, msg)
2272 }
2273 fn handle_tx_add_output(&self, their_node_id: PublicKey, msg: &TxAddOutput) {
2274 self.deref().handle_tx_add_output(their_node_id, msg)
2275 }
2276 fn handle_tx_remove_input(&self, their_node_id: PublicKey, msg: &TxRemoveInput) {
2277 self.deref().handle_tx_remove_input(their_node_id, msg)
2278 }
2279 fn handle_tx_remove_output(&self, their_node_id: PublicKey, msg: &TxRemoveOutput) {
2280 self.deref().handle_tx_remove_output(their_node_id, msg)
2281 }
2282 fn handle_tx_complete(&self, their_node_id: PublicKey, msg: &TxComplete) {
2283 self.deref().handle_tx_complete(their_node_id, msg)
2284 }
2285 fn handle_tx_signatures(&self, their_node_id: PublicKey, msg: &TxSignatures) {
2286 self.deref().handle_tx_signatures(their_node_id, msg)
2287 }
2288 fn handle_tx_init_rbf(&self, their_node_id: PublicKey, msg: &TxInitRbf) {
2289 self.deref().handle_tx_init_rbf(their_node_id, msg)
2290 }
2291 fn handle_tx_ack_rbf(&self, their_node_id: PublicKey, msg: &TxAckRbf) {
2292 self.deref().handle_tx_ack_rbf(their_node_id, msg)
2293 }
2294 fn handle_tx_abort(&self, their_node_id: PublicKey, msg: &TxAbort) {
2295 self.deref().handle_tx_abort(their_node_id, msg)
2296 }
2297 fn handle_update_add_htlc(&self, their_node_id: PublicKey, msg: &UpdateAddHTLC) {
2298 self.deref().handle_update_add_htlc(their_node_id, msg)
2299 }
2300 fn handle_update_fulfill_htlc(&self, their_node_id: PublicKey, msg: UpdateFulfillHTLC) {
2301 self.deref().handle_update_fulfill_htlc(their_node_id, msg)
2302 }
2303 fn handle_update_fail_htlc(&self, their_node_id: PublicKey, msg: &UpdateFailHTLC) {
2304 self.deref().handle_update_fail_htlc(their_node_id, msg)
2305 }
2306 fn handle_update_fail_malformed_htlc(
2307 &self, their_node_id: PublicKey, msg: &UpdateFailMalformedHTLC,
2308 ) {
2309 self.deref().handle_update_fail_malformed_htlc(their_node_id, msg)
2310 }
2311 fn handle_commitment_signed(&self, their_node_id: PublicKey, msg: &CommitmentSigned) {
2312 self.deref().handle_commitment_signed(their_node_id, msg)
2313 }
2314 fn handle_commitment_signed_batch(
2315 &self, their_node_id: PublicKey, channel_id: ChannelId, batch: Vec<CommitmentSigned>,
2316 ) {
2317 self.deref().handle_commitment_signed_batch(their_node_id, channel_id, batch)
2318 }
2319 fn handle_revoke_and_ack(&self, their_node_id: PublicKey, msg: &RevokeAndACK) {
2320 self.deref().handle_revoke_and_ack(their_node_id, msg)
2321 }
2322 fn handle_update_fee(&self, their_node_id: PublicKey, msg: &UpdateFee) {
2323 self.deref().handle_update_fee(their_node_id, msg)
2324 }
2325 fn handle_announcement_signatures(
2326 &self, their_node_id: PublicKey, msg: &AnnouncementSignatures,
2327 ) {
2328 self.deref().handle_announcement_signatures(their_node_id, msg)
2329 }
2330 fn handle_channel_reestablish(&self, their_node_id: PublicKey, msg: &ChannelReestablish) {
2331 self.deref().handle_channel_reestablish(their_node_id, msg)
2332 }
2333 fn handle_channel_update(&self, their_node_id: PublicKey, msg: &ChannelUpdate) {
2334 self.deref().handle_channel_update(their_node_id, msg)
2335 }
2336 fn handle_error(&self, their_node_id: PublicKey, msg: &ErrorMessage) {
2337 self.deref().handle_error(their_node_id, msg)
2338 }
2339 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
2340 self.deref().get_chain_hashes()
2341 }
2342 fn message_received(&self) {
2343 self.deref().message_received()
2344 }
2345}
2346
2347pub trait RoutingMessageHandler: BaseMessageHandler {
2355 fn handle_node_announcement(
2360 &self, their_node_id: Option<PublicKey>, msg: &NodeAnnouncement,
2361 ) -> Result<bool, LightningError>;
2362 fn handle_channel_announcement(
2367 &self, their_node_id: Option<PublicKey>, msg: &ChannelAnnouncement,
2368 ) -> Result<bool, LightningError>;
2369 fn handle_channel_update(
2374 &self, their_node_id: Option<PublicKey>, msg: &ChannelUpdate,
2375 ) -> Result<Option<(NodeId, NodeId)>, LightningError>;
2376 fn get_next_channel_announcement(
2380 &self, starting_point: u64,
2381 ) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)>;
2382 fn get_next_node_announcement(
2387 &self, starting_point: Option<&NodeId>,
2388 ) -> Option<NodeAnnouncement>;
2389 fn handle_reply_channel_range(
2393 &self, their_node_id: PublicKey, msg: ReplyChannelRange,
2394 ) -> Result<(), LightningError>;
2395 fn handle_reply_short_channel_ids_end(
2400 &self, their_node_id: PublicKey, msg: ReplyShortChannelIdsEnd,
2401 ) -> Result<(), LightningError>;
2402 fn handle_query_channel_range(
2405 &self, their_node_id: PublicKey, msg: QueryChannelRange,
2406 ) -> Result<(), LightningError>;
2407 fn handle_query_short_channel_ids(
2410 &self, their_node_id: PublicKey, msg: QueryShortChannelIds,
2411 ) -> Result<(), LightningError>;
2412
2413 fn processing_queue_high(&self) -> bool;
2419}
2420
2421impl<T: RoutingMessageHandler + ?Sized, R: Deref<Target = T>> RoutingMessageHandler for R {
2422 fn handle_node_announcement(
2423 &self, their_node_id: Option<PublicKey>, msg: &NodeAnnouncement,
2424 ) -> Result<bool, LightningError> {
2425 self.deref().handle_node_announcement(their_node_id, msg)
2426 }
2427 fn handle_channel_announcement(
2428 &self, their_node_id: Option<PublicKey>, msg: &ChannelAnnouncement,
2429 ) -> Result<bool, LightningError> {
2430 self.deref().handle_channel_announcement(their_node_id, msg)
2431 }
2432 fn handle_channel_update(
2433 &self, their_node_id: Option<PublicKey>, msg: &ChannelUpdate,
2434 ) -> Result<Option<(NodeId, NodeId)>, LightningError> {
2435 self.deref().handle_channel_update(their_node_id, msg)
2436 }
2437 fn get_next_channel_announcement(
2438 &self, starting_point: u64,
2439 ) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
2440 self.deref().get_next_channel_announcement(starting_point)
2441 }
2442 fn get_next_node_announcement(
2443 &self, starting_point: Option<&NodeId>,
2444 ) -> Option<NodeAnnouncement> {
2445 self.deref().get_next_node_announcement(starting_point)
2446 }
2447 fn handle_reply_channel_range(
2448 &self, their_node_id: PublicKey, msg: ReplyChannelRange,
2449 ) -> Result<(), LightningError> {
2450 self.deref().handle_reply_channel_range(their_node_id, msg)
2451 }
2452 fn handle_reply_short_channel_ids_end(
2453 &self, their_node_id: PublicKey, msg: ReplyShortChannelIdsEnd,
2454 ) -> Result<(), LightningError> {
2455 self.deref().handle_reply_short_channel_ids_end(their_node_id, msg)
2456 }
2457 fn handle_query_channel_range(
2458 &self, their_node_id: PublicKey, msg: QueryChannelRange,
2459 ) -> Result<(), LightningError> {
2460 self.deref().handle_query_channel_range(their_node_id, msg)
2461 }
2462 fn handle_query_short_channel_ids(
2463 &self, their_node_id: PublicKey, msg: QueryShortChannelIds,
2464 ) -> Result<(), LightningError> {
2465 self.deref().handle_query_short_channel_ids(their_node_id, msg)
2466 }
2467 fn processing_queue_high(&self) -> bool {
2468 self.deref().processing_queue_high()
2469 }
2470}
2471
2472pub trait OnionMessageHandler: BaseMessageHandler {
2474 fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage);
2476
2477 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage>;
2482
2483 fn timer_tick_occurred(&self);
2486}
2487
2488impl<T: OnionMessageHandler + ?Sized, O: Deref<Target = T>> OnionMessageHandler for O {
2489 fn handle_onion_message(&self, peer_node_id: PublicKey, msg: &OnionMessage) {
2490 self.deref().handle_onion_message(peer_node_id, msg)
2491 }
2492 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<OnionMessage> {
2493 self.deref().next_onion_message_for_peer(peer_node_id)
2494 }
2495 fn timer_tick_occurred(&self) {
2496 self.deref().timer_tick_occurred()
2497 }
2498}
2499
2500pub trait SendOnlyMessageHandler: BaseMessageHandler {}
2506
2507impl<T: SendOnlyMessageHandler + ?Sized, S: Deref<Target = T>> SendOnlyMessageHandler for S {}
2508
2509#[derive(Clone, Debug, PartialEq, Eq)]
2510pub struct FinalOnionHopData {
2513 pub payment_secret: PaymentSecret,
2517 pub total_msat: u64,
2521}
2522
2523mod fuzzy_internal_msgs {
2524 use super::{FinalOnionHopData, TrampolineOnionPacket};
2525 use crate::blinded_path::payment::{
2526 BlindedPaymentPath, PaymentConstraints, PaymentContext, PaymentRelay,
2527 };
2528 use crate::ln::onion_utils::AttributionData;
2529 use crate::offers::invoice_request::InvoiceRequest;
2530 use crate::types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
2531 use crate::types::payment::{PaymentPreimage, PaymentSecret};
2532 use bitcoin::secp256k1::PublicKey;
2533
2534 #[allow(unused_imports)]
2535 use crate::prelude::*;
2536
2537 pub struct InboundOnionForwardPayload {
2541 pub short_channel_id: u64,
2542 pub amt_to_forward: u64,
2544 pub outgoing_cltv_value: u32,
2545 }
2546
2547 #[allow(unused)]
2548 pub struct InboundTrampolineEntrypointPayload {
2549 pub amt_to_forward: u64,
2550 pub outgoing_cltv_value: u32,
2551 pub multipath_trampoline_data: Option<FinalOnionHopData>,
2552 pub trampoline_packet: TrampolineOnionPacket,
2553 pub current_path_key: Option<PublicKey>,
2556 }
2557
2558 pub struct InboundOnionReceivePayload {
2559 pub payment_data: Option<FinalOnionHopData>,
2560 pub payment_metadata: Option<Vec<u8>>,
2561 pub keysend_preimage: Option<PaymentPreimage>,
2562 pub custom_tlvs: Vec<(u64, Vec<u8>)>,
2563 pub sender_intended_htlc_amt_msat: u64,
2564 pub cltv_expiry_height: u32,
2565 }
2566 pub struct InboundOnionBlindedForwardPayload {
2567 pub short_channel_id: u64,
2568 pub payment_relay: PaymentRelay,
2569 pub payment_constraints: PaymentConstraints,
2570 pub features: BlindedHopFeatures,
2571 pub intro_node_blinding_point: Option<PublicKey>,
2572 pub next_blinding_override: Option<PublicKey>,
2573 }
2574 pub struct InboundOnionDummyPayload {
2575 pub payment_relay: PaymentRelay,
2576 pub payment_constraints: PaymentConstraints,
2577 pub intro_node_blinding_point: Option<PublicKey>,
2578 }
2579 pub struct InboundOnionBlindedReceivePayload {
2580 pub sender_intended_htlc_amt_msat: u64,
2581 pub total_msat: u64,
2582 pub cltv_expiry_height: u32,
2583 pub payment_secret: PaymentSecret,
2584 pub payment_constraints: PaymentConstraints,
2585 pub payment_context: PaymentContext,
2586 pub intro_node_blinding_point: Option<PublicKey>,
2587 pub keysend_preimage: Option<PaymentPreimage>,
2588 pub invoice_request: Option<InvoiceRequest>,
2589 pub custom_tlvs: Vec<(u64, Vec<u8>)>,
2590 }
2591
2592 pub enum InboundOnionPayload {
2593 Forward(InboundOnionForwardPayload),
2594 TrampolineEntrypoint(InboundTrampolineEntrypointPayload),
2595 Receive(InboundOnionReceivePayload),
2596 BlindedForward(InboundOnionBlindedForwardPayload),
2597 BlindedReceive(InboundOnionBlindedReceivePayload),
2598 Dummy(InboundOnionDummyPayload),
2599 }
2600
2601 pub struct InboundTrampolineForwardPayload {
2602 pub next_trampoline: PublicKey,
2603 pub amt_to_forward: u64,
2605 pub outgoing_cltv_value: u32,
2606 }
2607
2608 pub struct InboundTrampolineBlindedForwardPayload {
2609 pub next_trampoline: PublicKey,
2610 pub payment_relay: PaymentRelay,
2611 pub payment_constraints: PaymentConstraints,
2612 pub features: BlindedHopFeatures,
2613 pub intro_node_blinding_point: Option<PublicKey>,
2614 pub next_blinding_override: Option<PublicKey>,
2615 }
2616
2617 pub enum InboundTrampolinePayload {
2618 Forward(InboundTrampolineForwardPayload),
2619 BlindedForward(InboundTrampolineBlindedForwardPayload),
2620 Receive(InboundOnionReceivePayload),
2621 BlindedReceive(InboundOnionBlindedReceivePayload),
2622 }
2623
2624 pub(crate) enum OutboundOnionPayload<'a> {
2625 Forward {
2626 short_channel_id: u64,
2627 amt_to_forward: u64,
2629 outgoing_cltv_value: u32,
2630 },
2631 TrampolineEntrypoint {
2632 amt_to_forward: u64,
2633 outgoing_cltv_value: u32,
2634 multipath_trampoline_data: Option<FinalOnionHopData>,
2635 trampoline_packet: TrampolineOnionPacket,
2636 },
2637 #[allow(unused)]
2641 BlindedTrampolineEntrypoint {
2642 amt_to_forward: u64,
2643 outgoing_cltv_value: u32,
2644 multipath_trampoline_data: Option<FinalOnionHopData>,
2645 trampoline_packet: TrampolineOnionPacket,
2646 current_path_key: PublicKey,
2648 },
2649 Receive {
2650 payment_data: Option<FinalOnionHopData>,
2651 payment_metadata: Option<&'a Vec<u8>>,
2652 keysend_preimage: Option<PaymentPreimage>,
2653 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2654 sender_intended_htlc_amt_msat: u64,
2655 cltv_expiry_height: u32,
2656 },
2657 BlindedForward {
2658 encrypted_tlvs: &'a Vec<u8>,
2659 intro_node_blinding_point: Option<PublicKey>,
2660 },
2661 BlindedReceive {
2662 sender_intended_htlc_amt_msat: u64,
2663 total_msat: u64,
2664 cltv_expiry_height: u32,
2665 encrypted_tlvs: &'a Vec<u8>,
2666 intro_node_blinding_point: Option<PublicKey>, keysend_preimage: Option<PaymentPreimage>,
2668 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2669 invoice_request: Option<&'a InvoiceRequest>,
2670 },
2671 }
2672
2673 pub(crate) enum OutboundTrampolinePayload<'a> {
2674 Forward {
2675 amt_to_forward: u64,
2677 outgoing_cltv_value: u32,
2678 outgoing_node_id: PublicKey,
2680 },
2681 #[cfg(test)]
2682 Receive {
2686 payment_data: Option<FinalOnionHopData>,
2687 sender_intended_htlc_amt_msat: u64,
2688 cltv_expiry_height: u32,
2689 },
2690 #[allow(unused)]
2691 LegacyBlindedPathEntry {
2694 amt_to_forward: u64,
2696 outgoing_cltv_value: u32,
2697 payment_paths: Vec<BlindedPaymentPath>,
2699 invoice_features: Option<Bolt12InvoiceFeatures>,
2701 },
2702 BlindedForward {
2703 encrypted_tlvs: &'a Vec<u8>,
2704 intro_node_blinding_point: Option<PublicKey>,
2705 },
2706 BlindedReceive {
2707 sender_intended_htlc_amt_msat: u64,
2708 total_msat: u64,
2709 cltv_expiry_height: u32,
2710 encrypted_tlvs: &'a Vec<u8>,
2711 intro_node_blinding_point: Option<PublicKey>, keysend_preimage: Option<PaymentPreimage>,
2713 custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
2714 },
2715 }
2716
2717 pub struct DecodedOnionErrorPacket {
2718 pub(crate) hmac: [u8; 32],
2719 pub(crate) failuremsg: Vec<u8>,
2720 pub(crate) pad: Vec<u8>,
2721 }
2722
2723 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
2724 pub struct OnionErrorPacket {
2725 pub data: Vec<u8>,
2728 pub attribution_data: Option<AttributionData>,
2729 }
2730}
2731#[cfg(fuzzing)]
2732pub use self::fuzzy_internal_msgs::*;
2733#[cfg(not(fuzzing))]
2734pub(crate) use self::fuzzy_internal_msgs::*;
2735
2736use super::onion_utils::AttributionData;
2737
2738#[derive(Clone, Hash, PartialEq, Eq)]
2740pub struct OnionPacket {
2741 pub version: u8,
2743 pub public_key: Result<PublicKey, secp256k1::Error>,
2749 pub hop_data: [u8; 20 * 65],
2751 pub hmac: [u8; 32],
2753}
2754
2755impl onion_utils::Packet for OnionPacket {
2756 type Data = onion_utils::FixedSizeOnionPacket;
2757 fn new(pubkey: PublicKey, hop_data: onion_utils::FixedSizeOnionPacket, hmac: [u8; 32]) -> Self {
2758 Self { version: 0, public_key: Ok(pubkey), hop_data: hop_data.0, hmac }
2759 }
2760}
2761
2762impl fmt::Debug for OnionPacket {
2763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2764 f.write_fmt(format_args!(
2765 "OnionPacket version {} with hmac {:?}",
2766 self.version,
2767 &self.hmac[..]
2768 ))
2769 }
2770}
2771
2772#[derive(Clone, Hash, PartialEq, Eq)]
2774pub struct TrampolineOnionPacket {
2775 pub version: u8,
2777 pub public_key: PublicKey,
2779 pub hop_data: Vec<u8>,
2786 pub hmac: [u8; 32],
2788}
2789
2790impl onion_utils::Packet for TrampolineOnionPacket {
2791 type Data = Vec<u8>;
2792 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Self {
2793 Self { version: 0, public_key, hop_data, hmac }
2794 }
2795}
2796
2797impl Writeable for TrampolineOnionPacket {
2798 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2799 self.version.write(w)?;
2800 self.public_key.write(w)?;
2801 w.write_all(&self.hop_data)?;
2802 self.hmac.write(w)?;
2803 Ok(())
2804 }
2805}
2806
2807impl LengthReadable for TrampolineOnionPacket {
2808 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2809 let hop_data_len = r.remaining_bytes().saturating_sub(66); let version = Readable::read(r)?;
2812 let public_key = Readable::read(r)?;
2813
2814 let mut rd = FixedLengthReader::new(r, hop_data_len);
2815 let hop_data = WithoutLength::<Vec<u8>>::read_from_fixed_length_buffer(&mut rd)?.0;
2816
2817 let hmac = Readable::read(r)?;
2818
2819 Ok(TrampolineOnionPacket { version, public_key, hop_data, hmac })
2820 }
2821}
2822
2823impl Debug for TrampolineOnionPacket {
2824 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2825 f.write_fmt(format_args!(
2826 "TrampolineOnionPacket version {} with hmac {:?}",
2827 self.version,
2828 &self.hmac[..]
2829 ))
2830 }
2831}
2832
2833impl From<UpdateFailHTLC> for OnionErrorPacket {
2834 fn from(msg: UpdateFailHTLC) -> Self {
2835 OnionErrorPacket { data: msg.reason, attribution_data: msg.attribution_data }
2836 }
2837}
2838
2839impl fmt::Display for DecodeError {
2840 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2841 match *self {
2842 DecodeError::UnknownVersion => f.write_str("Unknown realm byte in Onion packet"),
2843 DecodeError::UnknownRequiredFeature => {
2844 f.write_str("Unknown required feature preventing decode")
2845 },
2846 DecodeError::InvalidValue => {
2847 f.write_str("Nonsense bytes didn't map to the type they were interpreted as")
2848 },
2849 DecodeError::ShortRead => f.write_str("Packet extended beyond the provided bytes"),
2850 DecodeError::BadLengthDescriptor => f.write_str(
2851 "A length descriptor in the packet didn't describe the later data correctly",
2852 ),
2853 DecodeError::Io(ref e) => fmt::Debug::fmt(e, f),
2854 DecodeError::UnsupportedCompression => {
2855 f.write_str("We don't support receiving messages with zlib-compressed fields")
2856 },
2857 DecodeError::DangerousValue => {
2858 f.write_str("Value would be dangerous to continue execution with")
2859 },
2860 }
2861 }
2862}
2863
2864impl From<io::Error> for DecodeError {
2865 fn from(e: io::Error) -> Self {
2866 if e.kind() == io::ErrorKind::UnexpectedEof {
2867 DecodeError::ShortRead
2868 } else {
2869 DecodeError::Io(e.kind())
2870 }
2871 }
2872}
2873
2874impl Writeable for AcceptChannel {
2875 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2876 self.common_fields.temporary_channel_id.write(w)?;
2877 self.common_fields.dust_limit_satoshis.write(w)?;
2878 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2879 self.channel_reserve_satoshis.write(w)?;
2880 self.common_fields.htlc_minimum_msat.write(w)?;
2881 self.common_fields.minimum_depth.write(w)?;
2882 self.common_fields.to_self_delay.write(w)?;
2883 self.common_fields.max_accepted_htlcs.write(w)?;
2884 self.common_fields.funding_pubkey.write(w)?;
2885 self.common_fields.revocation_basepoint.write(w)?;
2886 self.common_fields.payment_basepoint.write(w)?;
2887 self.common_fields.delayed_payment_basepoint.write(w)?;
2888 self.common_fields.htlc_basepoint.write(w)?;
2889 self.common_fields.first_per_commitment_point.write(w)?;
2890 encode_tlv_stream!(w, {
2891 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2893 });
2894 Ok(())
2895 }
2896}
2897
2898impl LengthReadable for AcceptChannel {
2899 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2900 let temporary_channel_id: ChannelId = Readable::read(r)?;
2901 let dust_limit_satoshis: u64 = Readable::read(r)?;
2902 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2903 let channel_reserve_satoshis: u64 = Readable::read(r)?;
2904 let htlc_minimum_msat: u64 = Readable::read(r)?;
2905 let minimum_depth: u32 = Readable::read(r)?;
2906 let to_self_delay: u16 = Readable::read(r)?;
2907 let max_accepted_htlcs: u16 = Readable::read(r)?;
2908 let funding_pubkey: PublicKey = Readable::read(r)?;
2909 let revocation_basepoint: PublicKey = Readable::read(r)?;
2910 let payment_basepoint: PublicKey = Readable::read(r)?;
2911 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2912 let htlc_basepoint: PublicKey = Readable::read(r)?;
2913 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2914
2915 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2916 let mut channel_type: Option<ChannelTypeFeatures> = None;
2917 decode_tlv_stream!(r, {
2918 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2919 (1, channel_type, option),
2920 });
2921
2922 Ok(AcceptChannel {
2923 common_fields: CommonAcceptChannelFields {
2924 temporary_channel_id,
2925 dust_limit_satoshis,
2926 max_htlc_value_in_flight_msat,
2927 htlc_minimum_msat,
2928 minimum_depth,
2929 to_self_delay,
2930 max_accepted_htlcs,
2931 funding_pubkey,
2932 revocation_basepoint,
2933 payment_basepoint,
2934 delayed_payment_basepoint,
2935 htlc_basepoint,
2936 first_per_commitment_point,
2937 shutdown_scriptpubkey,
2938 channel_type,
2939 },
2940 channel_reserve_satoshis,
2941 })
2942 }
2943}
2944
2945impl Writeable for AcceptChannelV2 {
2946 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2947 self.common_fields.temporary_channel_id.write(w)?;
2948 self.funding_satoshis.write(w)?;
2949 self.common_fields.dust_limit_satoshis.write(w)?;
2950 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
2951 self.common_fields.htlc_minimum_msat.write(w)?;
2952 self.common_fields.minimum_depth.write(w)?;
2953 self.common_fields.to_self_delay.write(w)?;
2954 self.common_fields.max_accepted_htlcs.write(w)?;
2955 self.common_fields.funding_pubkey.write(w)?;
2956 self.common_fields.revocation_basepoint.write(w)?;
2957 self.common_fields.payment_basepoint.write(w)?;
2958 self.common_fields.delayed_payment_basepoint.write(w)?;
2959 self.common_fields.htlc_basepoint.write(w)?;
2960 self.common_fields.first_per_commitment_point.write(w)?;
2961 self.second_per_commitment_point.write(w)?;
2962
2963 encode_tlv_stream!(w, {
2964 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
2966 (2, self.require_confirmed_inputs, option),
2967 (103, self.disable_channel_reserve, option),
2968 });
2969 Ok(())
2970 }
2971}
2972
2973impl LengthReadable for AcceptChannelV2 {
2974 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
2975 let temporary_channel_id: ChannelId = Readable::read(r)?;
2976 let funding_satoshis: u64 = Readable::read(r)?;
2977 let dust_limit_satoshis: u64 = Readable::read(r)?;
2978 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
2979 let htlc_minimum_msat: u64 = Readable::read(r)?;
2980 let minimum_depth: u32 = Readable::read(r)?;
2981 let to_self_delay: u16 = Readable::read(r)?;
2982 let max_accepted_htlcs: u16 = Readable::read(r)?;
2983 let funding_pubkey: PublicKey = Readable::read(r)?;
2984 let revocation_basepoint: PublicKey = Readable::read(r)?;
2985 let payment_basepoint: PublicKey = Readable::read(r)?;
2986 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
2987 let htlc_basepoint: PublicKey = Readable::read(r)?;
2988 let first_per_commitment_point: PublicKey = Readable::read(r)?;
2989 let second_per_commitment_point: PublicKey = Readable::read(r)?;
2990
2991 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
2992 let mut channel_type: Option<ChannelTypeFeatures> = None;
2993 let mut require_confirmed_inputs: Option<()> = None;
2994 let mut disable_channel_reserve: Option<()> = None;
2995 decode_tlv_stream!(r, {
2996 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
2997 (1, channel_type, option),
2998 (2, require_confirmed_inputs, option),
2999 (103, disable_channel_reserve, option),
3000 });
3001
3002 Ok(AcceptChannelV2 {
3003 common_fields: CommonAcceptChannelFields {
3004 temporary_channel_id,
3005 dust_limit_satoshis,
3006 max_htlc_value_in_flight_msat,
3007 htlc_minimum_msat,
3008 minimum_depth,
3009 to_self_delay,
3010 max_accepted_htlcs,
3011 funding_pubkey,
3012 revocation_basepoint,
3013 payment_basepoint,
3014 delayed_payment_basepoint,
3015 htlc_basepoint,
3016 first_per_commitment_point,
3017 shutdown_scriptpubkey,
3018 channel_type,
3019 },
3020 funding_satoshis,
3021 second_per_commitment_point,
3022 require_confirmed_inputs,
3023 disable_channel_reserve,
3024 })
3025 }
3026}
3027
3028impl_writeable_msg!(Stfu, {
3029 channel_id,
3030 initiator,
3031}, {});
3032
3033impl_writeable_msg!(SpliceInit, {
3034 channel_id,
3035 funding_contribution_satoshis,
3036 funding_feerate_per_kw,
3037 locktime,
3038 funding_pubkey,
3039}, {
3040 (2, require_confirmed_inputs, option), });
3042
3043impl_writeable_msg!(SpliceAck, {
3044 channel_id,
3045 funding_contribution_satoshis,
3046 funding_pubkey,
3047}, {
3048 (2, require_confirmed_inputs, option), });
3050
3051impl_writeable_msg!(SpliceLocked, {
3052 channel_id,
3053 splice_txid,
3054}, {});
3055
3056impl Writeable for TxAddInput {
3057 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3058 self.channel_id.write(w)?;
3059 self.serial_id.write(w)?;
3060
3061 match &self.prevtx {
3062 Some(tx) => {
3063 (tx.serialized_length() as u16).write(w)?;
3064 tx.write(w)?;
3065 },
3066 None => 0u16.write(w)?,
3067 }
3068
3069 self.prevtx_out.write(w)?;
3070 self.sequence.write(w)?;
3071
3072 encode_tlv_stream!(w, {
3073 (0, self.shared_input_txid, option),
3074 });
3075 Ok(())
3076 }
3077}
3078
3079impl LengthReadable for TxAddInput {
3080 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3081 let channel_id: ChannelId = Readable::read(r)?;
3082 let serial_id: SerialId = Readable::read(r)?;
3083
3084 let prevtx_len: u16 = Readable::read(r)?;
3085 let prevtx = if prevtx_len > 0 {
3086 let mut tx_reader = FixedLengthReader::new(r, prevtx_len as u64);
3087 let tx: Transaction = Readable::read(&mut tx_reader)?;
3088 if tx_reader.bytes_remain() {
3089 return Err(DecodeError::BadLengthDescriptor);
3090 }
3091
3092 Some(tx)
3093 } else {
3094 None
3095 };
3096
3097 let prevtx_out: u32 = Readable::read(r)?;
3098 let sequence: u32 = Readable::read(r)?;
3099
3100 let mut shared_input_txid: Option<Txid> = None;
3101 decode_tlv_stream!(r, {
3102 (0, shared_input_txid, option),
3103 });
3104
3105 Ok(TxAddInput { channel_id, serial_id, prevtx, prevtx_out, sequence, shared_input_txid })
3106 }
3107}
3108impl_writeable_msg!(TxAddOutput, {
3109 channel_id,
3110 serial_id,
3111 sats,
3112 script,
3113}, {});
3114
3115impl_writeable_msg!(TxRemoveInput, {
3116 channel_id,
3117 serial_id,
3118}, {});
3119
3120impl_writeable_msg!(TxRemoveOutput, {
3121 channel_id,
3122 serial_id,
3123}, {});
3124
3125impl_writeable_msg!(TxComplete, {
3126 channel_id,
3127}, {});
3128
3129impl_writeable_msg!(TxSignatures, {
3130 channel_id,
3131 tx_hash,
3132 witnesses,
3133}, {
3134 (0, shared_input_signature, option), });
3136
3137impl_writeable_msg!(TxInitRbf, {
3138 channel_id,
3139 locktime,
3140 feerate_sat_per_1000_weight,
3141}, {
3142 (0, funding_output_contribution, option),
3143});
3144
3145impl_writeable_msg!(TxAckRbf, {
3146 channel_id,
3147}, {
3148 (0, funding_output_contribution, option),
3149});
3150
3151impl_writeable_msg!(TxAbort, {
3152 channel_id,
3153 data,
3154}, {});
3155
3156impl_writeable_msg!(AnnouncementSignatures, {
3157 channel_id,
3158 short_channel_id,
3159 node_signature,
3160 bitcoin_signature
3161}, {});
3162
3163impl_writeable_msg!(ChannelReestablish, {
3164 channel_id,
3165 next_local_commitment_number,
3166 next_remote_commitment_number,
3167 your_last_per_commitment_secret,
3168 my_current_per_commitment_point,
3169}, {
3170 (1, next_funding, option),
3171 (5, my_current_funding_locked, option),
3172});
3173
3174impl_writeable!(NextFunding, {
3175 txid,
3176 retransmit_flags
3177});
3178
3179impl_writeable!(FundingLocked, {
3180 txid,
3181 retransmit_flags
3182});
3183
3184impl_writeable_msg!(ClosingSigned,
3185 { channel_id, fee_satoshis, signature },
3186 { (1, fee_range, option) }
3187);
3188
3189impl_writeable_msg!(ClosingComplete,
3190 { channel_id, closer_scriptpubkey, closee_scriptpubkey, fee_satoshis, locktime },
3191 {
3192 (1, closer_output_only, option),
3193 (2, closee_output_only, option),
3194 (3, closer_and_closee_outputs, option)
3195 }
3196);
3197
3198impl_writeable_msg!(ClosingSig,
3199 { channel_id, closer_scriptpubkey, closee_scriptpubkey, fee_satoshis, locktime },
3200 {
3201 (1, closer_output_only, option),
3202 (2, closee_output_only, option),
3203 (3, closer_and_closee_outputs, option)
3204 }
3205);
3206
3207impl_writeable!(ClosingSignedFeeRange, {
3208 min_fee_satoshis,
3209 max_fee_satoshis
3210});
3211
3212impl_writeable_msg!(CommitmentSigned, {
3213 channel_id,
3214 signature,
3215 htlc_signatures
3216}, {
3217 (1, funding_txid, option),
3218});
3219
3220impl_writeable!(DecodedOnionErrorPacket, {
3221 hmac,
3222 failuremsg,
3223 pad
3224});
3225
3226impl_writeable_msg!(FundingCreated, {
3227 temporary_channel_id,
3228 funding_txid,
3229 funding_output_index,
3230 signature
3231}, {});
3232
3233impl_writeable_msg!(FundingSigned, {
3234 channel_id,
3235 signature
3236}, {});
3237
3238impl_writeable_msg!(ChannelReady, {
3239 channel_id,
3240 next_per_commitment_point,
3241}, {
3242 (1, short_channel_id_alias, option),
3243});
3244
3245pub(crate) fn write_features_up_to_13<W: Writer>(
3246 w: &mut W, le_flags: &[u8],
3247) -> Result<(), io::Error> {
3248 let len = core::cmp::min(2, le_flags.len());
3249 (len as u16).write(w)?;
3250 for i in (0..len).rev() {
3251 if i == 0 {
3252 le_flags[i].write(w)?;
3253 } else {
3254 (le_flags[i] & 0b00_11_11_11).write(w)?;
3257 }
3258 }
3259 Ok(())
3260}
3261
3262impl Writeable for Init {
3263 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3264 write_features_up_to_13(w, self.features.le_flags())?;
3267 self.features.write(w)?;
3268 encode_tlv_stream!(w, {
3269 (1, self.networks.as_ref().map(|n| WithoutLength(n)), option),
3270 (3, self.remote_network_address, option),
3271 });
3272 Ok(())
3273 }
3274}
3275
3276impl LengthReadable for Init {
3277 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3278 let global_features: InitFeatures = Readable::read(r)?;
3279 let features: InitFeatures = Readable::read(r)?;
3280 let mut remote_network_address: Option<SocketAddress> = None;
3281 let mut networks: Option<WithoutLength<Vec<ChainHash>>> = None;
3282 decode_tlv_stream!(r, {
3283 (1, networks, option),
3284 (3, remote_network_address, option)
3285 });
3286 Ok(Init {
3287 features: features | global_features,
3288 networks: networks.map(|n| n.0),
3289 remote_network_address,
3290 })
3291 }
3292}
3293
3294impl Writeable for OpenChannel {
3295 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3296 self.common_fields.chain_hash.write(w)?;
3297 self.common_fields.temporary_channel_id.write(w)?;
3298 self.common_fields.funding_satoshis.write(w)?;
3299 self.push_msat.write(w)?;
3300 self.common_fields.dust_limit_satoshis.write(w)?;
3301 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
3302 self.channel_reserve_satoshis.write(w)?;
3303 self.common_fields.htlc_minimum_msat.write(w)?;
3304 self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
3305 self.common_fields.to_self_delay.write(w)?;
3306 self.common_fields.max_accepted_htlcs.write(w)?;
3307 self.common_fields.funding_pubkey.write(w)?;
3308 self.common_fields.revocation_basepoint.write(w)?;
3309 self.common_fields.payment_basepoint.write(w)?;
3310 self.common_fields.delayed_payment_basepoint.write(w)?;
3311 self.common_fields.htlc_basepoint.write(w)?;
3312 self.common_fields.first_per_commitment_point.write(w)?;
3313 self.common_fields.channel_flags.write(w)?;
3314 encode_tlv_stream!(w, {
3315 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
3317 });
3318 Ok(())
3319 }
3320}
3321
3322impl LengthReadable for OpenChannel {
3323 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3324 let chain_hash: ChainHash = Readable::read(r)?;
3325 let temporary_channel_id: ChannelId = Readable::read(r)?;
3326 let funding_satoshis: u64 = Readable::read(r)?;
3327 let push_msat: u64 = Readable::read(r)?;
3328 let dust_limit_satoshis: u64 = Readable::read(r)?;
3329 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
3330 let channel_reserve_satoshis: u64 = Readable::read(r)?;
3331 let htlc_minimum_msat: u64 = Readable::read(r)?;
3332 let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3333 let to_self_delay: u16 = Readable::read(r)?;
3334 let max_accepted_htlcs: u16 = Readable::read(r)?;
3335 let funding_pubkey: PublicKey = Readable::read(r)?;
3336 let revocation_basepoint: PublicKey = Readable::read(r)?;
3337 let payment_basepoint: PublicKey = Readable::read(r)?;
3338 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
3339 let htlc_basepoint: PublicKey = Readable::read(r)?;
3340 let first_per_commitment_point: PublicKey = Readable::read(r)?;
3341 let channel_flags: u8 = Readable::read(r)?;
3342
3343 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
3344 let mut channel_type: Option<ChannelTypeFeatures> = None;
3345 decode_tlv_stream!(r, {
3346 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
3347 (1, channel_type, option),
3348 });
3349 Ok(OpenChannel {
3350 common_fields: CommonOpenChannelFields {
3351 chain_hash,
3352 temporary_channel_id,
3353 funding_satoshis,
3354 dust_limit_satoshis,
3355 max_htlc_value_in_flight_msat,
3356 htlc_minimum_msat,
3357 commitment_feerate_sat_per_1000_weight,
3358 to_self_delay,
3359 max_accepted_htlcs,
3360 funding_pubkey,
3361 revocation_basepoint,
3362 payment_basepoint,
3363 delayed_payment_basepoint,
3364 htlc_basepoint,
3365 first_per_commitment_point,
3366 channel_flags,
3367 shutdown_scriptpubkey,
3368 channel_type,
3369 },
3370 push_msat,
3371 channel_reserve_satoshis,
3372 })
3373 }
3374}
3375
3376impl Writeable for OpenChannelV2 {
3377 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3378 self.common_fields.chain_hash.write(w)?;
3379 self.common_fields.temporary_channel_id.write(w)?;
3380 self.funding_feerate_sat_per_1000_weight.write(w)?;
3381 self.common_fields.commitment_feerate_sat_per_1000_weight.write(w)?;
3382 self.common_fields.funding_satoshis.write(w)?;
3383 self.common_fields.dust_limit_satoshis.write(w)?;
3384 self.common_fields.max_htlc_value_in_flight_msat.write(w)?;
3385 self.common_fields.htlc_minimum_msat.write(w)?;
3386 self.common_fields.to_self_delay.write(w)?;
3387 self.common_fields.max_accepted_htlcs.write(w)?;
3388 self.locktime.write(w)?;
3389 self.common_fields.funding_pubkey.write(w)?;
3390 self.common_fields.revocation_basepoint.write(w)?;
3391 self.common_fields.payment_basepoint.write(w)?;
3392 self.common_fields.delayed_payment_basepoint.write(w)?;
3393 self.common_fields.htlc_basepoint.write(w)?;
3394 self.common_fields.first_per_commitment_point.write(w)?;
3395 self.second_per_commitment_point.write(w)?;
3396 self.common_fields.channel_flags.write(w)?;
3397 encode_tlv_stream!(w, {
3398 (0, self.common_fields.shutdown_scriptpubkey.as_ref().map(|s| WithoutLength(s)), option), (1, self.common_fields.channel_type, option),
3400 (2, self.require_confirmed_inputs, option),
3401 (103, self.disable_channel_reserve, option),
3402 });
3403 Ok(())
3404 }
3405}
3406
3407impl LengthReadable for OpenChannelV2 {
3408 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3409 let chain_hash: ChainHash = Readable::read(r)?;
3410 let temporary_channel_id: ChannelId = Readable::read(r)?;
3411 let funding_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3412 let commitment_feerate_sat_per_1000_weight: u32 = Readable::read(r)?;
3413 let funding_satoshis: u64 = Readable::read(r)?;
3414 let dust_limit_satoshis: u64 = Readable::read(r)?;
3415 let max_htlc_value_in_flight_msat: u64 = Readable::read(r)?;
3416 let htlc_minimum_msat: u64 = Readable::read(r)?;
3417 let to_self_delay: u16 = Readable::read(r)?;
3418 let max_accepted_htlcs: u16 = Readable::read(r)?;
3419 let locktime: u32 = Readable::read(r)?;
3420 let funding_pubkey: PublicKey = Readable::read(r)?;
3421 let revocation_basepoint: PublicKey = Readable::read(r)?;
3422 let payment_basepoint: PublicKey = Readable::read(r)?;
3423 let delayed_payment_basepoint: PublicKey = Readable::read(r)?;
3424 let htlc_basepoint: PublicKey = Readable::read(r)?;
3425 let first_per_commitment_point: PublicKey = Readable::read(r)?;
3426 let second_per_commitment_point: PublicKey = Readable::read(r)?;
3427 let channel_flags: u8 = Readable::read(r)?;
3428
3429 let mut shutdown_scriptpubkey: Option<ScriptBuf> = None;
3430 let mut channel_type: Option<ChannelTypeFeatures> = None;
3431 let mut require_confirmed_inputs: Option<()> = None;
3432 let mut disable_channel_reserve: Option<()> = None;
3433 decode_tlv_stream!(r, {
3434 (0, shutdown_scriptpubkey, (option, encoding: (ScriptBuf, WithoutLength))),
3435 (1, channel_type, option),
3436 (2, require_confirmed_inputs, option),
3437 (103, disable_channel_reserve, option),
3438 });
3439 Ok(OpenChannelV2 {
3440 common_fields: CommonOpenChannelFields {
3441 chain_hash,
3442 temporary_channel_id,
3443 funding_satoshis,
3444 dust_limit_satoshis,
3445 max_htlc_value_in_flight_msat,
3446 htlc_minimum_msat,
3447 commitment_feerate_sat_per_1000_weight,
3448 to_self_delay,
3449 max_accepted_htlcs,
3450 funding_pubkey,
3451 revocation_basepoint,
3452 payment_basepoint,
3453 delayed_payment_basepoint,
3454 htlc_basepoint,
3455 first_per_commitment_point,
3456 channel_flags,
3457 shutdown_scriptpubkey,
3458 channel_type,
3459 },
3460 funding_feerate_sat_per_1000_weight,
3461 locktime,
3462 second_per_commitment_point,
3463 require_confirmed_inputs,
3464 disable_channel_reserve,
3465 })
3466 }
3467}
3468
3469impl_writeable_msg!(RevokeAndACK, {
3470 channel_id,
3471 per_commitment_secret,
3472 next_per_commitment_point
3473}, {
3474 (75537, release_htlc_message_paths, optional_vec)
3475});
3476
3477impl_writeable_msg!(Shutdown, {
3478 channel_id,
3479 scriptpubkey
3480}, {});
3481
3482impl_writeable_msg!(UpdateFailHTLC, {
3483 channel_id,
3484 htlc_id,
3485 reason
3486}, {
3487 (1, attribution_data, option)
3488});
3489
3490impl_writeable_msg!(UpdateFailMalformedHTLC, {
3491 channel_id,
3492 htlc_id,
3493 sha256_of_onion,
3494 failure_code
3495}, {});
3496
3497impl_writeable_msg!(UpdateFee, {
3498 channel_id,
3499 feerate_per_kw
3500}, {});
3501
3502impl_writeable_msg!(UpdateFulfillHTLC, {
3503 channel_id,
3504 htlc_id,
3505 payment_preimage
3506}, {
3507 (1, attribution_data, option)
3508});
3509
3510impl_writeable_msg!(PeerStorage, { data }, {});
3511
3512impl_writeable_msg!(PeerStorageRetrieval, { data }, {});
3513
3514impl_writeable_msg!(StartBatch, {
3515 channel_id,
3516 batch_size
3517}, {
3518 (1, message_type, option)
3519});
3520
3521impl Writeable for OnionPacket {
3525 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3526 self.version.write(w)?;
3527 match self.public_key {
3528 Ok(pubkey) => pubkey.write(w)?,
3529 Err(_) => [0u8; 33].write(w)?,
3530 }
3531 w.write_all(&self.hop_data)?;
3532 self.hmac.write(w)?;
3533 Ok(())
3534 }
3535}
3536
3537impl Readable for OnionPacket {
3538 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3539 Ok(OnionPacket {
3540 version: Readable::read(r)?,
3541 public_key: {
3542 let mut buf = [0u8; 33];
3543 r.read_exact(&mut buf)?;
3544 PublicKey::from_slice(&buf)
3545 },
3546 hop_data: Readable::read(r)?,
3547 hmac: Readable::read(r)?,
3548 })
3549 }
3550}
3551
3552impl_writeable_msg!(UpdateAddHTLC, {
3553 channel_id,
3554 htlc_id,
3555 amount_msat,
3556 payment_hash,
3557 cltv_expiry,
3558 onion_routing_packet,
3559}, {
3560 (0, blinding_point, option),
3561 (65537, skimmed_fee_msat, option),
3562 (75537, hold_htlc, option),
3565 (106823, accountable, (option, encoding: (bool, AccountableBool))),
3566});
3567
3568impl LengthReadable for OnionMessage {
3569 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
3570 let blinding_point: PublicKey = Readable::read(r)?;
3571 let len: u16 = Readable::read(r)?;
3572 let mut packet_reader = FixedLengthReader::new(r, len as u64);
3573 let onion_routing_packet: onion_message::packet::Packet =
3574 <onion_message::packet::Packet as LengthReadable>::read_from_fixed_length_buffer(
3575 &mut packet_reader,
3576 )?;
3577 Ok(Self { blinding_point, onion_routing_packet })
3578 }
3579}
3580
3581impl Writeable for OnionMessage {
3582 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3583 self.blinding_point.write(w)?;
3584 let onion_packet_len = self.onion_routing_packet.serialized_length();
3585 (onion_packet_len as u16).write(w)?;
3586 self.onion_routing_packet.write(w)?;
3587 Ok(())
3588 }
3589}
3590
3591impl Writeable for FinalOnionHopData {
3592 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3593 self.payment_secret.0.write(w)?;
3594 HighZeroBytesDroppedBigSize(self.total_msat).write(w)
3595 }
3596}
3597
3598impl Readable for FinalOnionHopData {
3599 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
3600 let secret: [u8; 32] = Readable::read(r)?;
3601 let amt: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
3602 Ok(Self { payment_secret: PaymentSecret(secret), total_msat: amt.0 })
3603 }
3604}
3605
3606impl<'a> Writeable for OutboundOnionPayload<'a> {
3607 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3608 match self {
3609 Self::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } => {
3610 _encode_varint_length_prefixed_tlv!(w, {
3611 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3612 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3613 (6, short_channel_id, required)
3614 });
3615 },
3616 Self::TrampolineEntrypoint {
3617 amt_to_forward,
3618 outgoing_cltv_value,
3619 ref multipath_trampoline_data,
3620 ref trampoline_packet,
3621 } => {
3622 _encode_varint_length_prefixed_tlv!(w, {
3623 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3624 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3625 (8, multipath_trampoline_data, option),
3626 (20, trampoline_packet, required)
3627 });
3628 },
3629 Self::BlindedTrampolineEntrypoint {
3630 amt_to_forward,
3631 outgoing_cltv_value,
3632 current_path_key,
3633 ref multipath_trampoline_data,
3634 ref trampoline_packet,
3635 } => {
3636 _encode_varint_length_prefixed_tlv!(w, {
3637 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3638 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3639 (8, multipath_trampoline_data, option),
3640 (12, current_path_key, required),
3641 (20, trampoline_packet, required)
3642 });
3643 },
3644 Self::Receive {
3645 ref payment_data,
3646 ref payment_metadata,
3647 ref keysend_preimage,
3648 sender_intended_htlc_amt_msat,
3649 cltv_expiry_height,
3650 ref custom_tlvs,
3651 } => {
3652 let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
3656 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> =
3657 custom_tlvs.iter().chain(keysend_tlv.iter()).collect();
3658 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
3659 _encode_varint_length_prefixed_tlv!(w, {
3660 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3661 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3662 (8, payment_data, option),
3663 (16, payment_metadata.map(|m| WithoutLength(m)), option)
3664 }, custom_tlvs.iter());
3665 },
3666 Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
3667 _encode_varint_length_prefixed_tlv!(w, {
3668 (10, *encrypted_tlvs, required_vec),
3669 (12, intro_node_blinding_point, option)
3670 });
3671 },
3672 Self::BlindedReceive {
3673 sender_intended_htlc_amt_msat,
3674 total_msat,
3675 cltv_expiry_height,
3676 encrypted_tlvs,
3677 intro_node_blinding_point,
3678 keysend_preimage,
3679 ref invoice_request,
3680 ref custom_tlvs,
3681 } => {
3682 let invoice_request_tlv = invoice_request.map(|invreq| (77_777, invreq.encode())); let keysend_tlv = keysend_preimage.map(|preimage| (5482373484, preimage.encode()));
3687 let mut custom_tlvs: Vec<&(u64, Vec<u8>)> = custom_tlvs
3688 .iter()
3689 .chain(invoice_request_tlv.iter())
3690 .chain(keysend_tlv.iter())
3691 .collect();
3692 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
3693 _encode_varint_length_prefixed_tlv!(w, {
3694 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3695 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3696 (10, *encrypted_tlvs, required_vec),
3697 (12, intro_node_blinding_point, option),
3698 (18, HighZeroBytesDroppedBigSize(*total_msat), required)
3699 }, custom_tlvs.iter());
3700 },
3701 }
3702 Ok(())
3703 }
3704}
3705
3706impl<'a> Writeable for OutboundTrampolinePayload<'a> {
3707 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
3708 match self {
3709 Self::Forward { amt_to_forward, outgoing_cltv_value, outgoing_node_id } => {
3710 _encode_varint_length_prefixed_tlv!(w, {
3711 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3712 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3713 (14, outgoing_node_id, required)
3714 });
3715 },
3716 #[cfg(test)]
3717 Self::Receive {
3718 ref payment_data,
3719 sender_intended_htlc_amt_msat,
3720 cltv_expiry_height,
3721 } => {
3722 _encode_varint_length_prefixed_tlv!(w, {
3723 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3724 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3725 (8, payment_data, option)
3726 });
3727 },
3728 Self::LegacyBlindedPathEntry {
3729 amt_to_forward,
3730 outgoing_cltv_value,
3731 payment_paths,
3732 invoice_features,
3733 } => {
3734 let mut blinded_path_serialization = [0u8; 2048]; let serialization_length = {
3736 let buffer_size = blinded_path_serialization.len();
3737 let mut blinded_path_slice = &mut blinded_path_serialization[..];
3738 for current_payment_path in payment_paths {
3739 current_payment_path.inner_blinded_path().write(&mut blinded_path_slice)?;
3740 current_payment_path.payinfo.write(&mut blinded_path_slice)?;
3741 }
3742 buffer_size - blinded_path_slice.len()
3743 };
3744 let blinded_path_serialization =
3745 &blinded_path_serialization[..serialization_length];
3746 _encode_varint_length_prefixed_tlv!(w, {
3747 (2, HighZeroBytesDroppedBigSize(*amt_to_forward), required),
3748 (4, HighZeroBytesDroppedBigSize(*outgoing_cltv_value), required),
3749 (21, invoice_features.as_ref().map(|m| WithoutLength(m)), option),
3750 (22, WithoutLength(blinded_path_serialization), required)
3751 });
3752 },
3753 Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point } => {
3754 _encode_varint_length_prefixed_tlv!(w, {
3755 (10, *encrypted_tlvs, required_vec),
3756 (12, intro_node_blinding_point, option)
3757 });
3758 },
3759 Self::BlindedReceive {
3760 sender_intended_htlc_amt_msat,
3761 total_msat,
3762 cltv_expiry_height,
3763 encrypted_tlvs,
3764 intro_node_blinding_point,
3765 keysend_preimage,
3766 custom_tlvs,
3767 } => {
3768 _encode_varint_length_prefixed_tlv!(w, {
3769 (2, HighZeroBytesDroppedBigSize(*sender_intended_htlc_amt_msat), required),
3770 (4, HighZeroBytesDroppedBigSize(*cltv_expiry_height), required),
3771 (10, *encrypted_tlvs, required_vec),
3772 (12, intro_node_blinding_point, option),
3773 (18, HighZeroBytesDroppedBigSize(*total_msat), required),
3774 (20, keysend_preimage, option)
3775 }, custom_tlvs.iter());
3776 },
3777 }
3778 Ok(())
3779 }
3780}
3781
3782impl<NS: NodeSigner> ReadableArgs<(Option<PublicKey>, NS)> for InboundOnionPayload {
3783 fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
3784 let (update_add_blinding_point, node_signer) = args;
3785
3786 let mut amt = None;
3787 let mut cltv_value = None;
3788 let mut short_id: Option<u64> = None;
3789 let mut payment_data: Option<FinalOnionHopData> = None;
3790 let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
3791 let mut intro_node_blinding_point = None;
3792 let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
3793 let mut total_msat = None;
3794 let mut keysend_preimage: Option<PaymentPreimage> = None;
3795 let mut trampoline_onion_packet: Option<TrampolineOnionPacket> = None;
3796 let mut invoice_request: Option<InvoiceRequest> = None;
3797 let mut custom_tlvs = Vec::new();
3798
3799 let tlv_len = BigSize::read(r)?;
3800 let mut rd = FixedLengthReader::new(r, tlv_len.0);
3801
3802 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
3803 (2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3804 (4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
3805 (6, short_id, option),
3806 (8, payment_data, option),
3807 (10, encrypted_tlvs_opt, option),
3808 (12, intro_node_blinding_point, option),
3809 (16, payment_metadata, option),
3810 (18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3811 (20, trampoline_onion_packet, option),
3812 (77_777, invoice_request, option),
3813 (5482373484, keysend_preimage, option)
3815 }, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
3816 if msg_type < 1 << 16 { return Ok(false) }
3817 let mut value = Vec::new();
3818 msg_reader.read_to_limit(&mut value, u64::MAX)?;
3819 custom_tlvs.push((msg_type, value));
3820 Ok(true)
3821 });
3822
3823 if amt.unwrap_or(0) > MAX_VALUE_MSAT {
3824 return Err(DecodeError::InvalidValue);
3825 }
3826 if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
3827 return Err(DecodeError::InvalidValue);
3828 }
3829
3830 if let Some(trampoline_onion_packet) = trampoline_onion_packet {
3831 if payment_metadata.is_some() || encrypted_tlvs_opt.is_some() || total_msat.is_some() {
3832 return Err(DecodeError::InvalidValue);
3833 }
3834 return Ok(Self::TrampolineEntrypoint(InboundTrampolineEntrypointPayload {
3835 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3836 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3837 multipath_trampoline_data: payment_data,
3838 trampoline_packet: trampoline_onion_packet,
3839 current_path_key: intro_node_blinding_point,
3840 }));
3841 }
3842
3843 if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
3844 if short_id.is_some() || payment_data.is_some() || payment_metadata.is_some() {
3845 return Err(DecodeError::InvalidValue);
3846 }
3847 let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
3848 let enc_tlvs_ss = node_signer
3849 .ecdh(Recipient::Node, &blinding_point, None)
3850 .map_err(|_| DecodeError::InvalidValue)?;
3851 let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
3852 let receive_auth_key = node_signer.get_receive_auth_key();
3853 let phantom_auth_key = node_signer.get_expanded_key().phantom_node_blinded_path_key;
3854 let read_args = (rho, receive_auth_key.0, phantom_auth_key);
3855
3856 let mut s = Cursor::new(&enc_tlvs);
3857 let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
3858 match ChaChaTriPolyReadAdapter::read(&mut reader, read_args)? {
3859 ChaChaTriPolyReadAdapter {
3860 readable:
3861 BlindedPaymentTlvs::Forward(ForwardTlvs {
3862 short_channel_id,
3863 payment_relay,
3864 payment_constraints,
3865 features,
3866 next_blinding_override,
3867 }),
3868 used_aad,
3869 } => {
3870 if amt.is_some()
3871 || cltv_value.is_some() || total_msat.is_some()
3872 || keysend_preimage.is_some()
3873 || invoice_request.is_some()
3874 || used_aad != TriPolyAADUsed::None
3875 {
3876 return Err(DecodeError::InvalidValue);
3877 }
3878 Ok(Self::BlindedForward(InboundOnionBlindedForwardPayload {
3879 short_channel_id,
3880 payment_relay,
3881 payment_constraints,
3882 features,
3883 intro_node_blinding_point,
3884 next_blinding_override,
3885 }))
3886 },
3887 ChaChaTriPolyReadAdapter {
3888 readable:
3889 BlindedPaymentTlvs::Dummy(DummyTlvs { payment_relay, payment_constraints }),
3890 used_aad,
3891 } => {
3892 if amt.is_some()
3893 || cltv_value.is_some() || total_msat.is_some()
3894 || keysend_preimage.is_some()
3895 || invoice_request.is_some()
3896 || used_aad == TriPolyAADUsed::None
3897 {
3898 return Err(DecodeError::InvalidValue);
3899 }
3900 Ok(Self::Dummy(InboundOnionDummyPayload {
3901 payment_relay,
3902 payment_constraints,
3903 intro_node_blinding_point,
3904 }))
3905 },
3906 ChaChaTriPolyReadAdapter {
3907 readable: BlindedPaymentTlvs::Receive(receive_tlvs),
3908 used_aad,
3909 } => {
3910 if used_aad == TriPolyAADUsed::None {
3911 return Err(DecodeError::InvalidValue);
3912 }
3913
3914 let ReceiveTlvs { payment_secret, payment_constraints, payment_context } =
3915 receive_tlvs;
3916
3917 if total_msat.unwrap_or(0) > MAX_VALUE_MSAT {
3918 return Err(DecodeError::InvalidValue);
3919 }
3920 Ok(Self::BlindedReceive(InboundOnionBlindedReceivePayload {
3921 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3922 total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
3923 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3924 payment_secret,
3925 payment_constraints,
3926 payment_context,
3927 intro_node_blinding_point,
3928 keysend_preimage,
3929 invoice_request,
3930 custom_tlvs,
3931 }))
3932 },
3933 }
3934 } else if let Some(short_channel_id) = short_id {
3935 if payment_data.is_some()
3936 || payment_metadata.is_some()
3937 || encrypted_tlvs_opt.is_some()
3938 || total_msat.is_some()
3939 || invoice_request.is_some()
3940 {
3941 return Err(DecodeError::InvalidValue);
3942 }
3943 Ok(Self::Forward(InboundOnionForwardPayload {
3944 short_channel_id,
3945 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
3946 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
3947 }))
3948 } else {
3949 if encrypted_tlvs_opt.is_some() || total_msat.is_some() || invoice_request.is_some() {
3950 return Err(DecodeError::InvalidValue);
3951 }
3952 if let Some(data) = &payment_data {
3953 if data.total_msat > MAX_VALUE_MSAT {
3954 return Err(DecodeError::InvalidValue);
3955 }
3956 }
3957 Ok(Self::Receive(InboundOnionReceivePayload {
3958 payment_data,
3959 payment_metadata: payment_metadata.map(|w| w.0),
3960 keysend_preimage,
3961 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
3962 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
3963 custom_tlvs,
3964 }))
3965 }
3966 }
3967}
3968
3969impl<NS: NodeSigner> ReadableArgs<(Option<PublicKey>, NS)> for InboundTrampolinePayload {
3970 fn read<R: Read>(r: &mut R, args: (Option<PublicKey>, NS)) -> Result<Self, DecodeError> {
3971 let (update_add_blinding_point, node_signer) = args;
3972 let receive_auth_key = node_signer.get_receive_auth_key();
3973 let phantom_auth_key = node_signer.get_expanded_key().phantom_node_blinded_path_key;
3974
3975 let mut amt = None;
3976 let mut cltv_value = None;
3977 let mut payment_data: Option<FinalOnionHopData> = None;
3978 let mut encrypted_tlvs_opt: Option<WithoutLength<Vec<u8>>> = None;
3979 let mut intro_node_blinding_point = None;
3980 let mut next_trampoline: Option<PublicKey> = None;
3981 let mut payment_metadata: Option<WithoutLength<Vec<u8>>> = None;
3982 let mut total_msat = None;
3983 let mut keysend_preimage: Option<PaymentPreimage> = None;
3984 let mut invoice_request: Option<InvoiceRequest> = None;
3985 let mut custom_tlvs = Vec::new();
3986
3987 let tlv_len = BigSize::read(r)?;
3988 let mut rd = FixedLengthReader::new(r, tlv_len.0);
3989 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
3990 (2, amt, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3991 (4, cltv_value, (option, encoding: (u32, HighZeroBytesDroppedBigSize))),
3992 (8, payment_data, option),
3993 (10, encrypted_tlvs_opt, option),
3994 (12, intro_node_blinding_point, option),
3995 (14, next_trampoline, option),
3996 (16, payment_metadata, option),
3997 (18, total_msat, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
3998 (77_777, invoice_request, option),
3999 (5482373484, keysend_preimage, option)
4001 }, |msg_type: u64, msg_reader: &mut FixedLengthReader<_>| -> Result<bool, DecodeError> {
4002 if msg_type < 1 << 16 { return Ok(false) }
4003 let mut value = Vec::new();
4004 msg_reader.read_to_limit(&mut value, u64::MAX)?;
4005 custom_tlvs.push((msg_type, value));
4006 Ok(true)
4007 });
4008
4009 if amt.unwrap_or(0) > MAX_VALUE_MSAT {
4010 return Err(DecodeError::InvalidValue);
4011 }
4012 if intro_node_blinding_point.is_some() && update_add_blinding_point.is_some() {
4013 return Err(DecodeError::InvalidValue);
4014 }
4015
4016 if let Some(blinding_point) = intro_node_blinding_point.or(update_add_blinding_point) {
4017 if next_trampoline.is_some() || payment_data.is_some() || payment_metadata.is_some() {
4018 return Err(DecodeError::InvalidValue);
4019 }
4020 let enc_tlvs = encrypted_tlvs_opt.ok_or(DecodeError::InvalidValue)?.0;
4021 let enc_tlvs_ss = node_signer
4022 .ecdh(Recipient::Node, &blinding_point, None)
4023 .map_err(|_| DecodeError::InvalidValue)?;
4024 let rho = onion_utils::gen_rho_from_shared_secret(&enc_tlvs_ss.secret_bytes());
4025 let mut s = Cursor::new(&enc_tlvs);
4026 let mut reader = FixedLengthReader::new(&mut s, enc_tlvs.len() as u64);
4027 let read_args = (rho, receive_auth_key.0, phantom_auth_key);
4028 match ChaChaTriPolyReadAdapter::read(&mut reader, read_args)? {
4029 ChaChaTriPolyReadAdapter {
4030 readable:
4031 BlindedTrampolineTlvs::Forward(TrampolineForwardTlvs {
4032 next_trampoline,
4033 payment_relay,
4034 payment_constraints,
4035 features,
4036 next_blinding_override,
4037 }),
4038 used_aad,
4039 } => {
4040 if amt.is_some()
4041 || cltv_value.is_some() || total_msat.is_some()
4042 || keysend_preimage.is_some()
4043 || invoice_request.is_some()
4044 || used_aad != TriPolyAADUsed::None
4045 {
4046 return Err(DecodeError::InvalidValue);
4047 }
4048 Ok(Self::BlindedForward(InboundTrampolineBlindedForwardPayload {
4049 next_trampoline,
4050 payment_relay,
4051 payment_constraints,
4052 features,
4053 intro_node_blinding_point,
4054 next_blinding_override,
4055 }))
4056 },
4057 ChaChaTriPolyReadAdapter {
4058 readable: BlindedTrampolineTlvs::Receive(receive_tlvs),
4059 used_aad,
4060 } => {
4061 if used_aad == TriPolyAADUsed::None {
4062 return Err(DecodeError::InvalidValue);
4063 }
4064
4065 let ReceiveTlvs { payment_secret, payment_constraints, payment_context } =
4066 receive_tlvs;
4067
4068 if total_msat.unwrap_or(0) > MAX_VALUE_MSAT {
4069 return Err(DecodeError::InvalidValue);
4070 }
4071 Ok(Self::BlindedReceive(InboundOnionBlindedReceivePayload {
4072 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
4073 total_msat: total_msat.ok_or(DecodeError::InvalidValue)?,
4074 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
4075 payment_secret,
4076 payment_constraints,
4077 payment_context,
4078 intro_node_blinding_point,
4079 keysend_preimage,
4080 invoice_request,
4081 custom_tlvs,
4082 }))
4083 },
4084 }
4085 } else if let Some(next_trampoline) = next_trampoline {
4086 if payment_data.is_some()
4087 || payment_metadata.is_some()
4088 || encrypted_tlvs_opt.is_some()
4089 || total_msat.is_some()
4090 || invoice_request.is_some()
4091 {
4092 return Err(DecodeError::InvalidValue);
4093 }
4094 Ok(Self::Forward(InboundTrampolineForwardPayload {
4095 next_trampoline,
4096 amt_to_forward: amt.ok_or(DecodeError::InvalidValue)?,
4097 outgoing_cltv_value: cltv_value.ok_or(DecodeError::InvalidValue)?,
4098 }))
4099 } else {
4100 if encrypted_tlvs_opt.is_some() || total_msat.is_some() || invoice_request.is_some() {
4101 return Err(DecodeError::InvalidValue);
4102 }
4103 if let Some(data) = &payment_data {
4104 if data.total_msat > MAX_VALUE_MSAT {
4105 return Err(DecodeError::InvalidValue);
4106 }
4107 }
4108 Ok(Self::Receive(InboundOnionReceivePayload {
4109 payment_data,
4110 payment_metadata: payment_metadata.map(|w| w.0),
4111 keysend_preimage,
4112 sender_intended_htlc_amt_msat: amt.ok_or(DecodeError::InvalidValue)?,
4113 cltv_expiry_height: cltv_value.ok_or(DecodeError::InvalidValue)?,
4114 custom_tlvs,
4115 }))
4116 }
4117 }
4118}
4119
4120impl Writeable for Ping {
4121 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4122 self.ponglen.write(w)?;
4123 vec![0u8; self.byteslen as usize].write(w)?; Ok(())
4125 }
4126}
4127
4128impl LengthReadable for Ping {
4129 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4130 Ok(Ping {
4131 ponglen: Readable::read(r)?,
4132 byteslen: {
4133 let byteslen = Readable::read(r)?;
4134 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
4135 byteslen
4136 },
4137 })
4138 }
4139}
4140
4141impl Writeable for Pong {
4142 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4143 vec![0u8; self.byteslen as usize].write(w)?; Ok(())
4145 }
4146}
4147
4148impl LengthReadable for Pong {
4149 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4150 Ok(Pong {
4151 byteslen: {
4152 let byteslen = Readable::read(r)?;
4153 r.read_exact(&mut vec![0u8; byteslen as usize][..])?;
4154 byteslen
4155 },
4156 })
4157 }
4158}
4159
4160impl Writeable for UnsignedChannelAnnouncement {
4161 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4162 self.features.write(w)?;
4163 self.chain_hash.write(w)?;
4164 self.short_channel_id.write(w)?;
4165 self.node_id_1.write(w)?;
4166 self.node_id_2.write(w)?;
4167 self.bitcoin_key_1.write(w)?;
4168 self.bitcoin_key_2.write(w)?;
4169 w.write_all(&self.excess_data[..])?;
4170 Ok(())
4171 }
4172}
4173
4174impl LengthReadable for UnsignedChannelAnnouncement {
4175 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4176 Ok(Self {
4177 features: Readable::read(r)?,
4178 chain_hash: Readable::read(r)?,
4179 short_channel_id: Readable::read(r)?,
4180 node_id_1: Readable::read(r)?,
4181 node_id_2: Readable::read(r)?,
4182 bitcoin_key_1: Readable::read(r)?,
4183 bitcoin_key_2: Readable::read(r)?,
4184 excess_data: read_to_end(r)?,
4185 })
4186 }
4187}
4188
4189impl Writeable for ChannelAnnouncement {
4190 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4191 self.node_signature_1.write(w)?;
4192 self.node_signature_2.write(w)?;
4193 self.bitcoin_signature_1.write(w)?;
4194 self.bitcoin_signature_2.write(w)?;
4195 self.contents.write(w)?;
4196 Ok(())
4197 }
4198}
4199
4200impl LengthReadable for ChannelAnnouncement {
4201 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4202 Ok(Self {
4203 node_signature_1: Readable::read(r)?,
4204 node_signature_2: Readable::read(r)?,
4205 bitcoin_signature_1: Readable::read(r)?,
4206 bitcoin_signature_2: Readable::read(r)?,
4207 contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4208 })
4209 }
4210}
4211
4212impl Writeable for UnsignedChannelUpdate {
4213 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4214 self.chain_hash.write(w)?;
4215 self.short_channel_id.write(w)?;
4216 self.timestamp.write(w)?;
4217 (self.message_flags | 1).write(w)?;
4220 self.channel_flags.write(w)?;
4221 self.cltv_expiry_delta.write(w)?;
4222 self.htlc_minimum_msat.write(w)?;
4223 self.fee_base_msat.write(w)?;
4224 self.fee_proportional_millionths.write(w)?;
4225 self.htlc_maximum_msat.write(w)?;
4226 w.write_all(&self.excess_data[..])?;
4227 Ok(())
4228 }
4229}
4230
4231impl LengthReadable for UnsignedChannelUpdate {
4232 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4233 let res = Self {
4234 chain_hash: Readable::read(r)?,
4235 short_channel_id: Readable::read(r)?,
4236 timestamp: Readable::read(r)?,
4237 message_flags: Readable::read(r)?,
4238 channel_flags: Readable::read(r)?,
4239 cltv_expiry_delta: Readable::read(r)?,
4240 htlc_minimum_msat: Readable::read(r)?,
4241 fee_base_msat: Readable::read(r)?,
4242 fee_proportional_millionths: Readable::read(r)?,
4243 htlc_maximum_msat: Readable::read(r)?,
4244 excess_data: read_to_end(r)?,
4245 };
4246 if res.message_flags & 1 != 1 {
4247 Err(DecodeError::InvalidValue)
4250 } else {
4251 Ok(res)
4252 }
4253 }
4254}
4255
4256impl Writeable for ChannelUpdate {
4257 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4258 self.signature.write(w)?;
4259 self.contents.write(w)?;
4260 Ok(())
4261 }
4262}
4263
4264impl LengthReadable for ChannelUpdate {
4265 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4266 Ok(Self {
4267 signature: Readable::read(r)?,
4268 contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4269 })
4270 }
4271}
4272
4273impl Writeable for ErrorMessage {
4274 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4275 self.channel_id.write(w)?;
4276 (self.data.len() as u16).write(w)?;
4277 w.write_all(self.data.as_bytes())?;
4278 Ok(())
4279 }
4280}
4281
4282impl LengthReadable for ErrorMessage {
4283 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4284 Ok(Self {
4285 channel_id: Readable::read(r)?,
4286 data: {
4287 let sz: usize = <u16 as Readable>::read(r)? as usize;
4288 let mut data = Vec::with_capacity(sz);
4289 data.resize(sz, 0);
4290 r.read_exact(&mut data)?;
4291 match String::from_utf8(data) {
4292 Ok(s) => s,
4293 Err(_) => return Err(DecodeError::InvalidValue),
4294 }
4295 },
4296 })
4297 }
4298}
4299
4300impl Writeable for WarningMessage {
4301 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4302 self.channel_id.write(w)?;
4303 (self.data.len() as u16).write(w)?;
4304 w.write_all(self.data.as_bytes())?;
4305 Ok(())
4306 }
4307}
4308
4309impl LengthReadable for WarningMessage {
4310 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4311 Ok(Self {
4312 channel_id: Readable::read(r)?,
4313 data: {
4314 let sz: usize = <u16 as Readable>::read(r)? as usize;
4315 let mut data = Vec::with_capacity(sz);
4316 data.resize(sz, 0);
4317 r.read_exact(&mut data)?;
4318 match String::from_utf8(data) {
4319 Ok(s) => s,
4320 Err(_) => return Err(DecodeError::InvalidValue),
4321 }
4322 },
4323 })
4324 }
4325}
4326
4327impl Writeable for UnsignedNodeAnnouncement {
4328 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4329 self.features.write(w)?;
4330 self.timestamp.write(w)?;
4331 self.node_id.write(w)?;
4332 w.write_all(&self.rgb)?;
4333 self.alias.write(w)?;
4334
4335 let mut addr_len = 0;
4336 for addr in self.addresses.iter() {
4337 addr_len += 1 + addr.len();
4338 }
4339 (addr_len + self.excess_address_data.len() as u16).write(w)?;
4340 for addr in self.addresses.iter() {
4341 addr.write(w)?;
4342 }
4343 w.write_all(&self.excess_address_data[..])?;
4344 w.write_all(&self.excess_data[..])?;
4345 Ok(())
4346 }
4347}
4348
4349impl LengthReadable for UnsignedNodeAnnouncement {
4350 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4351 let features: NodeFeatures = Readable::read(r)?;
4352 let timestamp: u32 = Readable::read(r)?;
4353 let node_id: NodeId = Readable::read(r)?;
4354 let mut rgb = [0; 3];
4355 r.read_exact(&mut rgb)?;
4356 let alias: NodeAlias = Readable::read(r)?;
4357
4358 let addr_len: u16 = Readable::read(r)?;
4359 let mut addresses: Vec<SocketAddress> = Vec::new();
4360 let mut addr_readpos = 0;
4361 let mut excess = false;
4362 let mut excess_byte = 0;
4363 loop {
4364 if addr_len <= addr_readpos {
4365 break;
4366 }
4367 match Readable::read(r) {
4368 Ok(Ok(addr)) => {
4369 if addr_len < addr_readpos + 1 + addr.len() {
4370 return Err(DecodeError::BadLengthDescriptor);
4371 }
4372 addr_readpos += (1 + addr.len()) as u16;
4373 addresses.push(addr);
4374 },
4375 Ok(Err(unknown_descriptor)) => {
4376 excess = true;
4377 excess_byte = unknown_descriptor;
4378 break;
4379 },
4380 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
4381 Err(e) => return Err(e),
4382 }
4383 }
4384
4385 let mut excess_data = vec![];
4386 let excess_address_data = if addr_readpos < addr_len {
4387 let mut excess_address_data = vec![0; (addr_len - addr_readpos) as usize];
4388 r.read_exact(&mut excess_address_data[if excess { 1 } else { 0 }..])?;
4389 if excess {
4390 excess_address_data[0] = excess_byte;
4391 }
4392 excess_address_data
4393 } else {
4394 if excess {
4395 excess_data.push(excess_byte);
4396 }
4397 Vec::new()
4398 };
4399 excess_data.extend(read_to_end(r)?.iter());
4400 Ok(UnsignedNodeAnnouncement {
4401 features,
4402 timestamp,
4403 node_id,
4404 rgb,
4405 alias,
4406 addresses,
4407 excess_address_data,
4408 excess_data,
4409 })
4410 }
4411}
4412
4413impl Writeable for NodeAnnouncement {
4414 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4415 self.signature.write(w)?;
4416 self.contents.write(w)?;
4417 Ok(())
4418 }
4419}
4420
4421impl LengthReadable for NodeAnnouncement {
4422 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4423 Ok(Self {
4424 signature: Readable::read(r)?,
4425 contents: LengthReadable::read_from_fixed_length_buffer(r)?,
4426 })
4427 }
4428}
4429
4430impl LengthReadable for QueryShortChannelIds {
4431 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4432 let chain_hash: ChainHash = Readable::read(r)?;
4433
4434 let encoding_len: u16 = Readable::read(r)?;
4435 let encoding_type: u8 = Readable::read(r)?;
4436
4437 if encoding_type != EncodingType::Uncompressed as u8 {
4440 return Err(DecodeError::UnsupportedCompression);
4441 }
4442
4443 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
4446 return Err(DecodeError::InvalidValue);
4447 }
4448
4449 let short_channel_id_count: u16 = (encoding_len - 1) / 8;
4452 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
4453 for _ in 0..short_channel_id_count {
4454 short_channel_ids.push(Readable::read(r)?);
4455 }
4456
4457 Ok(QueryShortChannelIds { chain_hash, short_channel_ids })
4458 }
4459}
4460
4461impl Writeable for QueryShortChannelIds {
4462 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4463 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
4465
4466 self.chain_hash.write(w)?;
4467 encoding_len.write(w)?;
4468
4469 (EncodingType::Uncompressed as u8).write(w)?;
4471
4472 for scid in self.short_channel_ids.iter() {
4473 scid.write(w)?;
4474 }
4475
4476 Ok(())
4477 }
4478}
4479
4480impl_writeable_msg!(ReplyShortChannelIdsEnd, {
4481 chain_hash,
4482 full_information,
4483}, {});
4484
4485impl QueryChannelRange {
4486 pub fn end_blocknum(&self) -> u32 {
4490 match self.first_blocknum.checked_add(self.number_of_blocks) {
4491 Some(block) => block,
4492 None => u32::max_value(),
4493 }
4494 }
4495}
4496
4497impl_writeable_msg!(QueryChannelRange, {
4498 chain_hash,
4499 first_blocknum,
4500 number_of_blocks
4501}, {});
4502
4503impl LengthReadable for ReplyChannelRange {
4504 fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
4505 let chain_hash: ChainHash = Readable::read(r)?;
4506 let first_blocknum: u32 = Readable::read(r)?;
4507 let number_of_blocks: u32 = Readable::read(r)?;
4508 let sync_complete: bool = Readable::read(r)?;
4509
4510 let encoding_len: u16 = Readable::read(r)?;
4511 let encoding_type: u8 = Readable::read(r)?;
4512
4513 if encoding_type != EncodingType::Uncompressed as u8 {
4516 return Err(DecodeError::UnsupportedCompression);
4517 }
4518
4519 if encoding_len == 0 || (encoding_len - 1) % 8 != 0 {
4522 return Err(DecodeError::InvalidValue);
4523 }
4524
4525 let short_channel_id_count: u16 = (encoding_len - 1) / 8;
4528 let mut short_channel_ids = Vec::with_capacity(short_channel_id_count as usize);
4529 for _ in 0..short_channel_id_count {
4530 short_channel_ids.push(Readable::read(r)?);
4531 }
4532
4533 Ok(ReplyChannelRange {
4534 chain_hash,
4535 first_blocknum,
4536 number_of_blocks,
4537 sync_complete,
4538 short_channel_ids,
4539 })
4540 }
4541}
4542
4543impl Writeable for ReplyChannelRange {
4544 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
4545 let encoding_len: u16 = 1 + self.short_channel_ids.len() as u16 * 8;
4546 self.chain_hash.write(w)?;
4547 self.first_blocknum.write(w)?;
4548 self.number_of_blocks.write(w)?;
4549 self.sync_complete.write(w)?;
4550
4551 encoding_len.write(w)?;
4552 (EncodingType::Uncompressed as u8).write(w)?;
4553 for scid in self.short_channel_ids.iter() {
4554 scid.write(w)?;
4555 }
4556
4557 Ok(())
4558 }
4559}
4560
4561impl_writeable_msg!(GossipTimestampFilter, {
4562 chain_hash,
4563 first_timestamp,
4564 timestamp_range,
4565}, {});
4566
4567#[cfg(test)]
4568mod tests {
4569 use crate::ln::msgs::SocketAddress;
4570 use crate::ln::msgs::{
4571 self, CommonAcceptChannelFields, CommonOpenChannelFields, FinalOnionHopData,
4572 InboundOnionForwardPayload, InboundOnionReceivePayload, OutboundTrampolinePayload,
4573 TrampolineOnionPacket,
4574 };
4575 use crate::ln::onion_utils::AttributionData;
4576 use crate::ln::types::ChannelId;
4577 use crate::routing::gossip::{NodeAlias, NodeId};
4578 use crate::types::features::{
4579 ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures,
4580 };
4581 use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
4582 use crate::util::ser::{BigSize, Hostname, LengthReadable, Readable, ReadableArgs, Writeable};
4583 use crate::util::test_utils::{self, pubkey};
4584 use bitcoin::hex::DisplayHex;
4585 use bitcoin::{Amount, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness};
4586
4587 use bitcoin::address::Address;
4588 use bitcoin::constants::ChainHash;
4589 use bitcoin::hash_types::Txid;
4590 use bitcoin::hex::FromHex;
4591 use bitcoin::locktime::absolute::LockTime;
4592 use bitcoin::network::Network;
4593 use bitcoin::opcodes;
4594 use bitcoin::script::Builder;
4595 use bitcoin::transaction::Version;
4596
4597 use bitcoin::secp256k1::{Message, Secp256k1};
4598 use bitcoin::secp256k1::{PublicKey, SecretKey};
4599
4600 use crate::chain::transaction::OutPoint;
4601 use crate::io::{self, Cursor};
4602 use crate::prelude::*;
4603 use core::str::FromStr;
4604
4605 use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
4606 #[cfg(feature = "std")]
4607 use crate::ln::msgs::SocketAddressParseError;
4608 #[cfg(feature = "std")]
4609 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
4610 use types::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
4611
4612 #[test]
4613 fn encoding_channel_reestablish() {
4614 let public_key = {
4615 let secp_ctx = Secp256k1::new();
4616 PublicKey::from_secret_key(
4617 &secp_ctx,
4618 &SecretKey::from_slice(
4619 &<Vec<u8>>::from_hex(
4620 "0101010101010101010101010101010101010101010101010101010101010101",
4621 )
4622 .unwrap()[..],
4623 )
4624 .unwrap(),
4625 )
4626 };
4627
4628 let cr = msgs::ChannelReestablish {
4629 channel_id: ChannelId::from_bytes([
4630 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,
4631 0, 0, 0, 0,
4632 ]),
4633 next_local_commitment_number: 3,
4634 next_remote_commitment_number: 4,
4635 your_last_per_commitment_secret: [9; 32],
4636 my_current_per_commitment_point: public_key,
4637 next_funding: None,
4638 my_current_funding_locked: None,
4639 };
4640
4641 let encoded_value = cr.encode();
4642 assert_eq!(
4643 encoded_value,
4644 vec![
4645 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,
4646 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,
4650 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4652 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4653 143, ]
4655 );
4656 }
4657
4658 #[test]
4659 fn encoding_channel_reestablish_with_next_funding_txid() {
4660 let public_key = {
4661 let secp_ctx = Secp256k1::new();
4662 PublicKey::from_secret_key(
4663 &secp_ctx,
4664 &SecretKey::from_slice(
4665 &<Vec<u8>>::from_hex(
4666 "0101010101010101010101010101010101010101010101010101010101010101",
4667 )
4668 .unwrap()[..],
4669 )
4670 .unwrap(),
4671 )
4672 };
4673
4674 let cr = msgs::ChannelReestablish {
4675 channel_id: ChannelId::from_bytes([
4676 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,
4677 0, 0, 0, 0,
4678 ]),
4679 next_local_commitment_number: 3,
4680 next_remote_commitment_number: 4,
4681 your_last_per_commitment_secret: [9; 32],
4682 my_current_per_commitment_point: public_key,
4683 next_funding: Some(msgs::NextFunding {
4684 txid: Txid::from_raw_hash(
4685 bitcoin::hashes::Hash::from_slice(&[
4686 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15,
4687 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
4688 ])
4689 .unwrap(),
4690 ),
4691 retransmit_flags: 1,
4692 }),
4693 my_current_funding_locked: None,
4694 };
4695
4696 let encoded_value = cr.encode();
4697 assert_eq!(
4698 encoded_value,
4699 vec![
4700 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,
4701 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,
4705 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4707 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4708 143, 1, 33, 48, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4,
4712 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, 1, ]
4714 );
4715 }
4716
4717 #[test]
4718 fn encoding_channel_reestablish_with_funding_locked_txid() {
4719 let public_key = {
4720 let secp_ctx = Secp256k1::new();
4721 PublicKey::from_secret_key(
4722 &secp_ctx,
4723 &SecretKey::from_slice(
4724 &<Vec<u8>>::from_hex(
4725 "0101010101010101010101010101010101010101010101010101010101010101",
4726 )
4727 .unwrap()[..],
4728 )
4729 .unwrap(),
4730 )
4731 };
4732
4733 let cr = msgs::ChannelReestablish {
4734 channel_id: ChannelId::from_bytes([
4735 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,
4736 0, 0, 0, 0,
4737 ]),
4738 next_local_commitment_number: 3,
4739 next_remote_commitment_number: 4,
4740 your_last_per_commitment_secret: [9; 32],
4741 my_current_per_commitment_point: public_key,
4742 next_funding: None,
4743 my_current_funding_locked: Some(msgs::FundingLocked {
4744 txid: Txid::from_raw_hash(
4745 bitcoin::hashes::Hash::from_slice(&[
4746 21, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15,
4747 80, 4, 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124,
4748 ])
4749 .unwrap(),
4750 ),
4751 retransmit_flags: 1,
4752 }),
4753 };
4754
4755 let encoded_value = cr.encode();
4756 assert_eq!(
4757 encoded_value,
4758 vec![
4759 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,
4760 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,
4764 9, 9, 9, 9, 3, 27, 132, 197, 86, 123, 18, 100, 64, 153, 93, 62, 213, 170, 186, 5, 101, 215, 30,
4766 24, 52, 96, 72, 25, 255, 156, 23, 245, 233, 213, 221, 7,
4767 143, 5, 33, 21, 167, 250, 69, 152, 48, 103, 172, 164, 99, 59, 19, 23, 11, 92, 84, 15, 80, 4,
4771 12, 98, 82, 75, 31, 201, 11, 91, 23, 98, 23, 53, 124, 1, ]
4773 );
4774 }
4775
4776 macro_rules! get_keys_from {
4777 ($slice: expr, $secp_ctx: expr) => {{
4778 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex($slice).unwrap()[..]).unwrap();
4779 let pubkey = PublicKey::from_secret_key(&$secp_ctx, &privkey);
4780 (privkey, pubkey)
4781 }};
4782 }
4783
4784 macro_rules! get_sig_on {
4785 ($privkey: expr, $ctx: expr, $string: expr) => {{
4786 let sighash = Message::from_digest_slice(&$string.into_bytes()[..]).unwrap();
4787 $ctx.sign_ecdsa(&sighash, &$privkey)
4788 }};
4789 }
4790
4791 #[test]
4792 fn encoding_announcement_signatures() {
4793 let secp_ctx = Secp256k1::new();
4794 let (privkey, _) = get_keys_from!(
4795 "0101010101010101010101010101010101010101010101010101010101010101",
4796 secp_ctx
4797 );
4798 let sig_1 =
4799 get_sig_on!(privkey, secp_ctx, String::from("01010101010101010101010101010101"));
4800 let sig_2 =
4801 get_sig_on!(privkey, secp_ctx, String::from("02020202020202020202020202020202"));
4802 let announcement_signatures = msgs::AnnouncementSignatures {
4803 channel_id: ChannelId::from_bytes([
4804 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,
4805 0, 0, 0, 0,
4806 ]),
4807 short_channel_id: 2316138423780173,
4808 node_signature: sig_1,
4809 bitcoin_signature: sig_2,
4810 };
4811
4812 let encoded_value = announcement_signatures.encode();
4813 assert_eq!(encoded_value, <Vec<u8>>::from_hex("040000000000000005000000000000000600000000000000070000000000000000083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073acf9953cef4700860f5967838eba2bae89288ad188ebf8b20bf995c3ea53a26df1876d0a3a0e13172ba286a673140190c02ba9da60a2e43a745188c8a83c7f3ef").unwrap());
4814 }
4815
4816 fn do_encoding_channel_announcement(unknown_features_bits: bool, excess_data: bool) {
4817 let secp_ctx = Secp256k1::new();
4818 let (privkey_1, pubkey_1) = get_keys_from!(
4819 "0101010101010101010101010101010101010101010101010101010101010101",
4820 secp_ctx
4821 );
4822 let (privkey_2, pubkey_2) = get_keys_from!(
4823 "0202020202020202020202020202020202020202020202020202020202020202",
4824 secp_ctx
4825 );
4826 let (privkey_3, pubkey_3) = get_keys_from!(
4827 "0303030303030303030303030303030303030303030303030303030303030303",
4828 secp_ctx
4829 );
4830 let (privkey_4, pubkey_4) = get_keys_from!(
4831 "0404040404040404040404040404040404040404040404040404040404040404",
4832 secp_ctx
4833 );
4834 let sig_1 =
4835 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4836 let sig_2 =
4837 get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
4838 let sig_3 =
4839 get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
4840 let sig_4 =
4841 get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
4842 let mut features = ChannelFeatures::empty();
4843 if unknown_features_bits {
4844 features = ChannelFeatures::from_le_bytes(vec![0xFF, 0xFF]);
4845 }
4846 let unsigned_channel_announcement = msgs::UnsignedChannelAnnouncement {
4847 features,
4848 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
4849 short_channel_id: 2316138423780173,
4850 node_id_1: NodeId::from_pubkey(&pubkey_1),
4851 node_id_2: NodeId::from_pubkey(&pubkey_2),
4852 bitcoin_key_1: NodeId::from_pubkey(&pubkey_3),
4853 bitcoin_key_2: NodeId::from_pubkey(&pubkey_4),
4854 excess_data: if excess_data {
4855 vec![10, 0, 0, 20, 0, 0, 30, 0, 0, 40]
4856 } else {
4857 Vec::new()
4858 },
4859 };
4860 let channel_announcement = msgs::ChannelAnnouncement {
4861 node_signature_1: sig_1,
4862 node_signature_2: sig_2,
4863 bitcoin_signature_1: sig_3,
4864 bitcoin_signature_2: sig_4,
4865 contents: unsigned_channel_announcement,
4866 };
4867 let encoded_value = channel_announcement.encode();
4868 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a1735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap();
4869 if unknown_features_bits {
4870 target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
4871 } else {
4872 target_value.append(&mut <Vec<u8>>::from_hex("0000").unwrap());
4873 }
4874 target_value.append(
4875 &mut <Vec<u8>>::from_hex(
4876 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
4877 )
4878 .unwrap(),
4879 );
4880 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b").unwrap());
4881 if excess_data {
4882 target_value.append(&mut <Vec<u8>>::from_hex("0a00001400001e000028").unwrap());
4883 }
4884 assert_eq!(encoded_value, target_value);
4885 }
4886
4887 #[test]
4888 fn encoding_channel_announcement() {
4889 do_encoding_channel_announcement(true, false);
4890 do_encoding_channel_announcement(false, true);
4891 do_encoding_channel_announcement(false, false);
4892 do_encoding_channel_announcement(true, true);
4893 }
4894
4895 fn do_encoding_node_announcement(
4896 unknown_features_bits: bool, ipv4: bool, ipv6: bool, onionv2: bool, onionv3: bool,
4897 hostname: bool, excess_address_data: bool, excess_data: bool,
4898 ) {
4899 let secp_ctx = Secp256k1::new();
4900 let (privkey_1, pubkey_1) = get_keys_from!(
4901 "0101010101010101010101010101010101010101010101010101010101010101",
4902 secp_ctx
4903 );
4904 let sig_1 =
4905 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
4906 let features = if unknown_features_bits {
4907 NodeFeatures::from_le_bytes(vec![0xFF, 0xFF])
4908 } else {
4909 NodeFeatures::from_le_bytes(vec![2 | 1 << 5])
4911 };
4912 let mut addresses = Vec::new();
4913 if ipv4 {
4914 addresses.push(SocketAddress::TcpIpV4 { addr: [255, 254, 253, 252], port: 9735 });
4915 }
4916 if ipv6 {
4917 addresses.push(SocketAddress::TcpIpV6 {
4918 addr: [
4919 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240,
4920 ],
4921 port: 9735,
4922 });
4923 }
4924 if onionv2 {
4925 addresses.push(msgs::SocketAddress::OnionV2([
4926 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7,
4927 ]));
4928 }
4929 if onionv3 {
4930 addresses.push(msgs::SocketAddress::OnionV3 {
4931 ed25519_pubkey: [
4932 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240,
4933 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224,
4934 ],
4935 checksum: 32,
4936 version: 16,
4937 port: 9735,
4938 });
4939 }
4940 if hostname {
4941 addresses.push(SocketAddress::Hostname {
4942 hostname: Hostname::try_from(String::from("host")).unwrap(),
4943 port: 9735,
4944 });
4945 }
4946 let mut addr_len = 0;
4947 for addr in &addresses {
4948 addr_len += addr.len() + 1;
4949 }
4950 let unsigned_node_announcement = msgs::UnsignedNodeAnnouncement {
4951 features,
4952 timestamp: 20190119,
4953 node_id: NodeId::from_pubkey(&pubkey_1),
4954 rgb: [32; 3],
4955 alias: NodeAlias([16; 32]),
4956 addresses,
4957 excess_address_data: if excess_address_data {
4958 vec![
4959 33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34,
4960 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84,
4961 174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42,
4962 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105,
4963 ]
4964 } else {
4965 Vec::new()
4966 },
4967 excess_data: if excess_data {
4968 vec![
4969 59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160,
4970 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8,
4971 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17,
4972 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253,
4973 ]
4974 } else {
4975 Vec::new()
4976 },
4977 };
4978 addr_len += unsigned_node_announcement.excess_address_data.len() as u16;
4979 let node_announcement =
4980 msgs::NodeAnnouncement { signature: sig_1, contents: unsigned_node_announcement };
4981 let encoded_value = node_announcement.encode();
4982 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
4983 if unknown_features_bits {
4984 target_value.append(&mut <Vec<u8>>::from_hex("0002ffff").unwrap());
4985 } else {
4986 target_value.append(&mut <Vec<u8>>::from_hex("000122").unwrap());
4987 }
4988 target_value.append(&mut <Vec<u8>>::from_hex("013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010").unwrap());
4989 target_value.append(&mut vec![(addr_len >> 8) as u8, addr_len as u8]);
4990 if ipv4 {
4991 target_value.append(&mut <Vec<u8>>::from_hex("01fffefdfc2607").unwrap());
4992 }
4993 if ipv6 {
4994 target_value.append(
4995 &mut <Vec<u8>>::from_hex("02fffefdfcfbfaf9f8f7f6f5f4f3f2f1f02607").unwrap(),
4996 );
4997 }
4998 if onionv2 {
4999 target_value.append(&mut <Vec<u8>>::from_hex("03fffefdfcfbfaf9f8f7f62607").unwrap());
5000 }
5001 if onionv3 {
5002 target_value.append(
5003 &mut <Vec<u8>>::from_hex(
5004 "04fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0efeeedecebeae9e8e7e6e5e4e3e2e1e00020102607",
5005 )
5006 .unwrap(),
5007 );
5008 }
5009 if hostname {
5010 target_value.append(&mut <Vec<u8>>::from_hex("0504686f73742607").unwrap());
5011 }
5012 if excess_address_data {
5013 target_value.append(&mut <Vec<u8>>::from_hex("216c280b5395a2546e7e4b2663e04f811622f15a4f92e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d269").unwrap());
5014 }
5015 if excess_data {
5016 target_value.append(&mut <Vec<u8>>::from_hex("3b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd").unwrap());
5017 }
5018 assert_eq!(encoded_value, target_value);
5019 }
5020
5021 #[test]
5022 fn encoding_node_announcement() {
5023 do_encoding_node_announcement(true, true, true, true, true, true, true, true);
5024 do_encoding_node_announcement(false, false, false, false, false, false, false, false);
5025 do_encoding_node_announcement(false, true, false, false, false, false, false, false);
5026 do_encoding_node_announcement(false, false, true, false, false, false, false, false);
5027 do_encoding_node_announcement(false, false, false, true, false, false, false, false);
5028 do_encoding_node_announcement(false, false, false, false, true, false, false, false);
5029 do_encoding_node_announcement(false, false, false, false, false, true, false, false);
5030 do_encoding_node_announcement(false, false, false, false, false, false, true, false);
5031 do_encoding_node_announcement(false, true, false, true, false, false, true, false);
5032 do_encoding_node_announcement(false, false, true, false, true, false, false, false);
5033 }
5034
5035 fn do_encoding_channel_update(direction: bool, disable: bool, excess_data: bool) {
5036 let secp_ctx = Secp256k1::new();
5037 let (privkey_1, _) = get_keys_from!(
5038 "0101010101010101010101010101010101010101010101010101010101010101",
5039 secp_ctx
5040 );
5041 let sig_1 =
5042 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5043 let unsigned_channel_update = msgs::UnsignedChannelUpdate {
5044 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
5045 short_channel_id: 2316138423780173,
5046 timestamp: 20190119,
5047 message_flags: 1, channel_flags: if direction { 1 } else { 0 } | if disable { 1 << 1 } else { 0 },
5049 cltv_expiry_delta: 144,
5050 htlc_minimum_msat: 1000000,
5051 htlc_maximum_msat: 131355275467161,
5052 fee_base_msat: 10000,
5053 fee_proportional_millionths: 20,
5054 excess_data: if excess_data { vec![0, 0, 0, 0, 59, 154, 202, 0] } else { Vec::new() },
5055 };
5056 let channel_update =
5057 msgs::ChannelUpdate { signature: sig_1, contents: unsigned_channel_update };
5058 let encoded_value = channel_update.encode();
5059 let mut target_value = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5060 target_value.append(
5061 &mut <Vec<u8>>::from_hex(
5062 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
5063 )
5064 .unwrap(),
5065 );
5066 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d013413a7").unwrap());
5067 target_value.append(&mut <Vec<u8>>::from_hex("01").unwrap());
5068 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
5069 if direction {
5070 let flag = target_value.last_mut().unwrap();
5071 *flag = 1;
5072 }
5073 if disable {
5074 let flag = target_value.last_mut().unwrap();
5075 *flag |= 1 << 1;
5076 }
5077 target_value
5078 .append(&mut <Vec<u8>>::from_hex("009000000000000f42400000271000000014").unwrap());
5079 target_value.append(&mut <Vec<u8>>::from_hex("0000777788889999").unwrap());
5080 if excess_data {
5081 target_value.append(&mut <Vec<u8>>::from_hex("000000003b9aca00").unwrap());
5082 }
5083 assert_eq!(encoded_value, target_value);
5084 }
5085
5086 #[test]
5087 fn encoding_channel_update() {
5088 do_encoding_channel_update(false, false, false);
5089 do_encoding_channel_update(false, false, true);
5090 do_encoding_channel_update(true, false, false);
5091 do_encoding_channel_update(true, false, true);
5092 do_encoding_channel_update(false, true, false);
5093 do_encoding_channel_update(false, true, true);
5094 do_encoding_channel_update(true, true, false);
5095 do_encoding_channel_update(true, true, true);
5096 }
5097
5098 fn do_encoding_open_channel(random_bit: bool, shutdown: bool, incl_chan_type: bool) {
5099 let secp_ctx = Secp256k1::new();
5100 let (_, pubkey_1) = get_keys_from!(
5101 "0101010101010101010101010101010101010101010101010101010101010101",
5102 secp_ctx
5103 );
5104 let (_, pubkey_2) = get_keys_from!(
5105 "0202020202020202020202020202020202020202020202020202020202020202",
5106 secp_ctx
5107 );
5108 let (_, pubkey_3) = get_keys_from!(
5109 "0303030303030303030303030303030303030303030303030303030303030303",
5110 secp_ctx
5111 );
5112 let (_, pubkey_4) = get_keys_from!(
5113 "0404040404040404040404040404040404040404040404040404040404040404",
5114 secp_ctx
5115 );
5116 let (_, pubkey_5) = get_keys_from!(
5117 "0505050505050505050505050505050505050505050505050505050505050505",
5118 secp_ctx
5119 );
5120 let (_, pubkey_6) = get_keys_from!(
5121 "0606060606060606060606060606060606060606060606060606060606060606",
5122 secp_ctx
5123 );
5124 let open_channel = msgs::OpenChannel {
5125 common_fields: CommonOpenChannelFields {
5126 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
5127 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5128 funding_satoshis: 1311768467284833366,
5129 dust_limit_satoshis: 3608586615801332854,
5130 max_htlc_value_in_flight_msat: 8517154655701053848,
5131 htlc_minimum_msat: 2316138423780173,
5132 commitment_feerate_sat_per_1000_weight: 821716,
5133 to_self_delay: 49340,
5134 max_accepted_htlcs: 49340,
5135 funding_pubkey: pubkey_1,
5136 revocation_basepoint: pubkey_2,
5137 payment_basepoint: pubkey_3,
5138 delayed_payment_basepoint: pubkey_4,
5139 htlc_basepoint: pubkey_5,
5140 first_per_commitment_point: pubkey_6,
5141 channel_flags: if random_bit { 1 << 5 } else { 0 },
5142 shutdown_scriptpubkey: if shutdown {
5143 Some(
5144 Address::p2pkh(
5145 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5146 Network::Testnet,
5147 )
5148 .script_pubkey(),
5149 )
5150 } else {
5151 None
5152 },
5153 channel_type: if incl_chan_type {
5154 Some(ChannelTypeFeatures::empty())
5155 } else {
5156 None
5157 },
5158 },
5159 push_msat: 2536655962884945560,
5160 channel_reserve_satoshis: 8665828695742877976,
5161 };
5162 let encoded_value = open_channel.encode();
5163 let mut target_value = Vec::new();
5164 target_value.append(
5165 &mut <Vec<u8>>::from_hex(
5166 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
5167 )
5168 .unwrap(),
5169 );
5170 target_value.append(&mut <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202021234567890123456233403289122369832144668701144767633030896203198784335490624111800083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap());
5171 if random_bit {
5172 target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
5173 } else {
5174 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
5175 }
5176 if shutdown {
5177 target_value.append(
5178 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5179 .unwrap(),
5180 );
5181 }
5182 if incl_chan_type {
5183 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
5184 }
5185 assert_eq!(encoded_value, target_value);
5186 }
5187
5188 #[test]
5189 fn encoding_open_channel() {
5190 do_encoding_open_channel(false, false, false);
5191 do_encoding_open_channel(false, false, true);
5192 do_encoding_open_channel(false, true, false);
5193 do_encoding_open_channel(false, true, true);
5194 do_encoding_open_channel(true, false, false);
5195 do_encoding_open_channel(true, false, true);
5196 do_encoding_open_channel(true, true, false);
5197 do_encoding_open_channel(true, true, true);
5198 }
5199
5200 fn do_encoding_open_channelv2(
5201 random_bit: bool, shutdown: bool, incl_chan_type: bool, require_confirmed_inputs: bool,
5202 disable_channel_reserve: bool,
5203 ) {
5204 let secp_ctx = Secp256k1::new();
5205 let (_, pubkey_1) = get_keys_from!(
5206 "0101010101010101010101010101010101010101010101010101010101010101",
5207 secp_ctx
5208 );
5209 let (_, pubkey_2) = get_keys_from!(
5210 "0202020202020202020202020202020202020202020202020202020202020202",
5211 secp_ctx
5212 );
5213 let (_, pubkey_3) = get_keys_from!(
5214 "0303030303030303030303030303030303030303030303030303030303030303",
5215 secp_ctx
5216 );
5217 let (_, pubkey_4) = get_keys_from!(
5218 "0404040404040404040404040404040404040404040404040404040404040404",
5219 secp_ctx
5220 );
5221 let (_, pubkey_5) = get_keys_from!(
5222 "0505050505050505050505050505050505050505050505050505050505050505",
5223 secp_ctx
5224 );
5225 let (_, pubkey_6) = get_keys_from!(
5226 "0606060606060606060606060606060606060606060606060606060606060606",
5227 secp_ctx
5228 );
5229 let (_, pubkey_7) = get_keys_from!(
5230 "0707070707070707070707070707070707070707070707070707070707070707",
5231 secp_ctx
5232 );
5233 let open_channelv2 = msgs::OpenChannelV2 {
5234 common_fields: CommonOpenChannelFields {
5235 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
5236 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5237 commitment_feerate_sat_per_1000_weight: 821716,
5238 funding_satoshis: 1311768467284833366,
5239 dust_limit_satoshis: 3608586615801332854,
5240 max_htlc_value_in_flight_msat: 8517154655701053848,
5241 htlc_minimum_msat: 2316138423780173,
5242 to_self_delay: 49340,
5243 max_accepted_htlcs: 49340,
5244 funding_pubkey: pubkey_1,
5245 revocation_basepoint: pubkey_2,
5246 payment_basepoint: pubkey_3,
5247 delayed_payment_basepoint: pubkey_4,
5248 htlc_basepoint: pubkey_5,
5249 first_per_commitment_point: pubkey_6,
5250 channel_flags: if random_bit { 1 << 5 } else { 0 },
5251 shutdown_scriptpubkey: if shutdown {
5252 Some(
5253 Address::p2pkh(
5254 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5255 Network::Testnet,
5256 )
5257 .script_pubkey(),
5258 )
5259 } else {
5260 None
5261 },
5262 channel_type: if incl_chan_type {
5263 Some(ChannelTypeFeatures::empty())
5264 } else {
5265 None
5266 },
5267 },
5268 funding_feerate_sat_per_1000_weight: 821716,
5269 locktime: 305419896,
5270 second_per_commitment_point: pubkey_7,
5271 require_confirmed_inputs: require_confirmed_inputs.then_some(()),
5272 disable_channel_reserve: disable_channel_reserve.then_some(()),
5273 };
5274 let encoded_value = open_channelv2.encode();
5275 let mut target_value = Vec::new();
5276 target_value.append(
5277 &mut <Vec<u8>>::from_hex(
5278 "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000",
5279 )
5280 .unwrap(),
5281 );
5282 target_value.append(
5283 &mut <Vec<u8>>::from_hex(
5284 "0202020202020202020202020202020202020202020202020202020202020202",
5285 )
5286 .unwrap(),
5287 );
5288 target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
5289 target_value.append(&mut <Vec<u8>>::from_hex("000c89d4").unwrap());
5290 target_value.append(&mut <Vec<u8>>::from_hex("1234567890123456").unwrap());
5291 target_value.append(&mut <Vec<u8>>::from_hex("3214466870114476").unwrap());
5292 target_value.append(&mut <Vec<u8>>::from_hex("7633030896203198").unwrap());
5293 target_value.append(&mut <Vec<u8>>::from_hex("00083a840000034d").unwrap());
5294 target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
5295 target_value.append(&mut <Vec<u8>>::from_hex("c0bc").unwrap());
5296 target_value.append(&mut <Vec<u8>>::from_hex("12345678").unwrap());
5297 target_value.append(
5298 &mut <Vec<u8>>::from_hex(
5299 "031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",
5300 )
5301 .unwrap(),
5302 );
5303 target_value.append(
5304 &mut <Vec<u8>>::from_hex(
5305 "024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",
5306 )
5307 .unwrap(),
5308 );
5309 target_value.append(
5310 &mut <Vec<u8>>::from_hex(
5311 "02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
5312 )
5313 .unwrap(),
5314 );
5315 target_value.append(
5316 &mut <Vec<u8>>::from_hex(
5317 "03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b",
5318 )
5319 .unwrap(),
5320 );
5321 target_value.append(
5322 &mut <Vec<u8>>::from_hex(
5323 "0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7",
5324 )
5325 .unwrap(),
5326 );
5327 target_value.append(
5328 &mut <Vec<u8>>::from_hex(
5329 "03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a",
5330 )
5331 .unwrap(),
5332 );
5333 target_value.append(
5334 &mut <Vec<u8>>::from_hex(
5335 "02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f",
5336 )
5337 .unwrap(),
5338 );
5339
5340 if random_bit {
5341 target_value.append(&mut <Vec<u8>>::from_hex("20").unwrap());
5342 } else {
5343 target_value.append(&mut <Vec<u8>>::from_hex("00").unwrap());
5344 }
5345 if shutdown {
5346 target_value.append(
5347 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5348 .unwrap(),
5349 );
5350 }
5351 if incl_chan_type {
5352 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
5353 }
5354 if require_confirmed_inputs {
5355 target_value.append(&mut <Vec<u8>>::from_hex("0200").unwrap());
5356 }
5357 if disable_channel_reserve {
5358 target_value.append(&mut <Vec<u8>>::from_hex("6700").unwrap());
5359 }
5360 assert_eq!(encoded_value, target_value);
5361 }
5362
5363 #[test]
5364 fn encoding_open_channelv2() {
5365 do_encoding_open_channelv2(false, false, false, false, false);
5366 do_encoding_open_channelv2(false, false, false, false, true);
5367 do_encoding_open_channelv2(false, false, false, true, false);
5368 do_encoding_open_channelv2(false, false, false, true, true);
5369 do_encoding_open_channelv2(false, false, true, false, false);
5370 do_encoding_open_channelv2(false, false, true, false, true);
5371 do_encoding_open_channelv2(false, false, true, true, false);
5372 do_encoding_open_channelv2(false, false, true, true, true);
5373 do_encoding_open_channelv2(false, true, false, false, false);
5374 do_encoding_open_channelv2(false, true, false, false, true);
5375 do_encoding_open_channelv2(false, true, false, true, false);
5376 do_encoding_open_channelv2(false, true, false, true, true);
5377 do_encoding_open_channelv2(false, true, true, false, false);
5378 do_encoding_open_channelv2(false, true, true, false, true);
5379 do_encoding_open_channelv2(false, true, true, true, false);
5380 do_encoding_open_channelv2(false, true, true, true, true);
5381 do_encoding_open_channelv2(true, false, false, false, false);
5382 do_encoding_open_channelv2(true, false, false, false, true);
5383 do_encoding_open_channelv2(true, false, false, true, false);
5384 do_encoding_open_channelv2(true, false, false, true, true);
5385 do_encoding_open_channelv2(true, false, true, false, false);
5386 do_encoding_open_channelv2(true, false, true, false, true);
5387 do_encoding_open_channelv2(true, false, true, true, false);
5388 do_encoding_open_channelv2(true, false, true, true, true);
5389 do_encoding_open_channelv2(true, true, false, false, false);
5390 do_encoding_open_channelv2(true, true, false, false, true);
5391 do_encoding_open_channelv2(true, true, false, true, false);
5392 do_encoding_open_channelv2(true, true, false, true, true);
5393 do_encoding_open_channelv2(true, true, true, false, false);
5394 do_encoding_open_channelv2(true, true, true, false, true);
5395 do_encoding_open_channelv2(true, true, true, true, false);
5396 do_encoding_open_channelv2(true, true, true, true, true);
5397 }
5398
5399 fn do_encoding_accept_channel(shutdown: bool) {
5400 let secp_ctx = Secp256k1::new();
5401 let (_, pubkey_1) = get_keys_from!(
5402 "0101010101010101010101010101010101010101010101010101010101010101",
5403 secp_ctx
5404 );
5405 let (_, pubkey_2) = get_keys_from!(
5406 "0202020202020202020202020202020202020202020202020202020202020202",
5407 secp_ctx
5408 );
5409 let (_, pubkey_3) = get_keys_from!(
5410 "0303030303030303030303030303030303030303030303030303030303030303",
5411 secp_ctx
5412 );
5413 let (_, pubkey_4) = get_keys_from!(
5414 "0404040404040404040404040404040404040404040404040404040404040404",
5415 secp_ctx
5416 );
5417 let (_, pubkey_5) = get_keys_from!(
5418 "0505050505050505050505050505050505050505050505050505050505050505",
5419 secp_ctx
5420 );
5421 let (_, pubkey_6) = get_keys_from!(
5422 "0606060606060606060606060606060606060606060606060606060606060606",
5423 secp_ctx
5424 );
5425 let accept_channel = msgs::AcceptChannel {
5426 common_fields: CommonAcceptChannelFields {
5427 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5428 dust_limit_satoshis: 1311768467284833366,
5429 max_htlc_value_in_flight_msat: 2536655962884945560,
5430 htlc_minimum_msat: 2316138423780173,
5431 minimum_depth: 821716,
5432 to_self_delay: 49340,
5433 max_accepted_htlcs: 49340,
5434 funding_pubkey: pubkey_1,
5435 revocation_basepoint: pubkey_2,
5436 payment_basepoint: pubkey_3,
5437 delayed_payment_basepoint: pubkey_4,
5438 htlc_basepoint: pubkey_5,
5439 first_per_commitment_point: pubkey_6,
5440 shutdown_scriptpubkey: if shutdown {
5441 Some(
5442 Address::p2pkh(
5443 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5444 Network::Testnet,
5445 )
5446 .script_pubkey(),
5447 )
5448 } else {
5449 None
5450 },
5451 channel_type: None,
5452 },
5453 channel_reserve_satoshis: 3608586615801332854,
5454 };
5455 let encoded_value = accept_channel.encode();
5456 let mut target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020212345678901234562334032891223698321446687011447600083a840000034d000c89d4c0bcc0bc031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d076602531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33703462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a").unwrap();
5457 if shutdown {
5458 target_value.append(
5459 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5460 .unwrap(),
5461 );
5462 }
5463 assert_eq!(encoded_value, target_value);
5464 }
5465
5466 #[test]
5467 fn encoding_accept_channel() {
5468 do_encoding_accept_channel(false);
5469 do_encoding_accept_channel(true);
5470 }
5471
5472 fn do_encoding_accept_channelv2(
5473 shutdown: bool, incl_chan_type: bool, require_confirmed_inputs: bool,
5474 disable_channel_reserve: bool,
5475 ) {
5476 let secp_ctx = Secp256k1::new();
5477 let (_, pubkey_1) = get_keys_from!(
5478 "0101010101010101010101010101010101010101010101010101010101010101",
5479 secp_ctx
5480 );
5481 let (_, pubkey_2) = get_keys_from!(
5482 "0202020202020202020202020202020202020202020202020202020202020202",
5483 secp_ctx
5484 );
5485 let (_, pubkey_3) = get_keys_from!(
5486 "0303030303030303030303030303030303030303030303030303030303030303",
5487 secp_ctx
5488 );
5489 let (_, pubkey_4) = get_keys_from!(
5490 "0404040404040404040404040404040404040404040404040404040404040404",
5491 secp_ctx
5492 );
5493 let (_, pubkey_5) = get_keys_from!(
5494 "0505050505050505050505050505050505050505050505050505050505050505",
5495 secp_ctx
5496 );
5497 let (_, pubkey_6) = get_keys_from!(
5498 "0606060606060606060606060606060606060606060606060606060606060606",
5499 secp_ctx
5500 );
5501 let (_, pubkey_7) = get_keys_from!(
5502 "0707070707070707070707070707070707070707070707070707070707070707",
5503 secp_ctx
5504 );
5505 let accept_channelv2 = msgs::AcceptChannelV2 {
5506 common_fields: CommonAcceptChannelFields {
5507 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5508 dust_limit_satoshis: 1311768467284833366,
5509 max_htlc_value_in_flight_msat: 2536655962884945560,
5510 htlc_minimum_msat: 2316138423780173,
5511 minimum_depth: 821716,
5512 to_self_delay: 49340,
5513 max_accepted_htlcs: 49340,
5514 funding_pubkey: pubkey_1,
5515 revocation_basepoint: pubkey_2,
5516 payment_basepoint: pubkey_3,
5517 delayed_payment_basepoint: pubkey_4,
5518 htlc_basepoint: pubkey_5,
5519 first_per_commitment_point: pubkey_6,
5520 shutdown_scriptpubkey: if shutdown {
5521 Some(
5522 Address::p2pkh(
5523 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
5524 Network::Testnet,
5525 )
5526 .script_pubkey(),
5527 )
5528 } else {
5529 None
5530 },
5531 channel_type: if incl_chan_type {
5532 Some(ChannelTypeFeatures::empty())
5533 } else {
5534 None
5535 },
5536 },
5537 funding_satoshis: 1311768467284833366,
5538 second_per_commitment_point: pubkey_7,
5539 require_confirmed_inputs: require_confirmed_inputs.then_some(()),
5540 disable_channel_reserve: disable_channel_reserve.then_some(()),
5541 };
5542 let encoded_value = accept_channelv2.encode();
5543 let mut target_value =
5544 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5545 .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(
5554 &mut <Vec<u8>>::from_hex(
5555 "031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",
5556 )
5557 .unwrap(),
5558 ); target_value.append(
5560 &mut <Vec<u8>>::from_hex(
5561 "024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",
5562 )
5563 .unwrap(),
5564 ); target_value.append(
5566 &mut <Vec<u8>>::from_hex(
5567 "02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
5568 )
5569 .unwrap(),
5570 ); target_value.append(
5572 &mut <Vec<u8>>::from_hex(
5573 "03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b",
5574 )
5575 .unwrap(),
5576 ); target_value.append(
5578 &mut <Vec<u8>>::from_hex(
5579 "0362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7",
5580 )
5581 .unwrap(),
5582 ); target_value.append(
5584 &mut <Vec<u8>>::from_hex(
5585 "03f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a",
5586 )
5587 .unwrap(),
5588 ); target_value.append(
5590 &mut <Vec<u8>>::from_hex(
5591 "02989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f",
5592 )
5593 .unwrap(),
5594 ); if shutdown {
5596 target_value.append(
5597 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
5598 .unwrap(),
5599 );
5600 }
5601 if incl_chan_type {
5602 target_value.append(&mut <Vec<u8>>::from_hex("0100").unwrap());
5603 }
5604 if require_confirmed_inputs {
5605 target_value.append(&mut <Vec<u8>>::from_hex("0200").unwrap());
5606 }
5607 if disable_channel_reserve {
5608 target_value.append(&mut <Vec<u8>>::from_hex("6700").unwrap());
5609 }
5610 assert_eq!(encoded_value, target_value);
5611 }
5612
5613 #[test]
5614 fn encoding_accept_channelv2() {
5615 do_encoding_accept_channelv2(false, false, false, false);
5616 do_encoding_accept_channelv2(false, false, false, true);
5617 do_encoding_accept_channelv2(false, false, true, false);
5618 do_encoding_accept_channelv2(false, false, true, true);
5619 do_encoding_accept_channelv2(false, true, false, false);
5620 do_encoding_accept_channelv2(false, true, false, true);
5621 do_encoding_accept_channelv2(false, true, true, false);
5622 do_encoding_accept_channelv2(false, true, true, true);
5623 do_encoding_accept_channelv2(true, false, false, false);
5624 do_encoding_accept_channelv2(true, false, false, true);
5625 do_encoding_accept_channelv2(true, false, true, false);
5626 do_encoding_accept_channelv2(true, false, true, true);
5627 do_encoding_accept_channelv2(true, true, false, false);
5628 do_encoding_accept_channelv2(true, true, false, true);
5629 do_encoding_accept_channelv2(true, true, true, false);
5630 do_encoding_accept_channelv2(true, true, true, true);
5631 }
5632
5633 #[test]
5634 fn encoding_funding_created() {
5635 let secp_ctx = Secp256k1::new();
5636 let (privkey_1, _) = get_keys_from!(
5637 "0101010101010101010101010101010101010101010101010101010101010101",
5638 secp_ctx
5639 );
5640 let sig_1 =
5641 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5642 let funding_created = msgs::FundingCreated {
5643 temporary_channel_id: ChannelId::from_bytes([2; 32]),
5644 funding_txid: Txid::from_str(
5645 "c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e",
5646 )
5647 .unwrap(),
5648 funding_output_index: 255,
5649 signature: sig_1,
5650 };
5651 let encoded_value = funding_created.encode();
5652 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c200ffd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5653 assert_eq!(encoded_value, target_value);
5654 }
5655
5656 #[test]
5657 fn encoding_funding_signed() {
5658 let secp_ctx = Secp256k1::new();
5659 let (privkey_1, _) = get_keys_from!(
5660 "0101010101010101010101010101010101010101010101010101010101010101",
5661 secp_ctx
5662 );
5663 let sig_1 =
5664 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5665 let funding_signed =
5666 msgs::FundingSigned { channel_id: ChannelId::from_bytes([2; 32]), signature: sig_1 };
5667 let encoded_value = funding_signed.encode();
5668 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
5669 assert_eq!(encoded_value, target_value);
5670 }
5671
5672 #[test]
5673 fn encoding_channel_ready() {
5674 let secp_ctx = Secp256k1::new();
5675 let (_, pubkey_1) = get_keys_from!(
5676 "0101010101010101010101010101010101010101010101010101010101010101",
5677 secp_ctx
5678 );
5679 let channel_ready = msgs::ChannelReady {
5680 channel_id: ChannelId::from_bytes([2; 32]),
5681 next_per_commitment_point: pubkey_1,
5682 short_channel_id_alias: None,
5683 };
5684 let encoded_value = channel_ready.encode();
5685 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
5686 assert_eq!(encoded_value, target_value);
5687 }
5688
5689 #[test]
5690 fn encoding_splice_init() {
5691 let secp_ctx = Secp256k1::new();
5692 let (_, pubkey_1) = get_keys_from!(
5693 "0101010101010101010101010101010101010101010101010101010101010101",
5694 secp_ctx
5695 );
5696 let splice_init = msgs::SpliceInit {
5697 channel_id: ChannelId::from_bytes([2; 32]),
5698 funding_contribution_satoshis: -123456,
5699 funding_feerate_per_kw: 2000,
5700 locktime: 0,
5701 funding_pubkey: pubkey_1,
5702 require_confirmed_inputs: Some(()),
5703 };
5704 let encoded_value = splice_init.encode();
5705 assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0000007d000000000031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
5706 }
5707
5708 #[test]
5709 fn encoding_stfu() {
5710 let stfu = msgs::Stfu { channel_id: ChannelId::from_bytes([2; 32]), initiator: true };
5711 let encoded_value = stfu.encode();
5712 assert_eq!(
5713 encoded_value.as_hex().to_string(),
5714 "020202020202020202020202020202020202020202020202020202020202020201"
5715 );
5716
5717 let stfu = msgs::Stfu { channel_id: ChannelId::from_bytes([3; 32]), initiator: false };
5718 let encoded_value = stfu.encode();
5719 assert_eq!(
5720 encoded_value.as_hex().to_string(),
5721 "030303030303030303030303030303030303030303030303030303030303030300"
5722 );
5723 }
5724
5725 #[test]
5726 fn encoding_splice_ack() {
5727 let secp_ctx = Secp256k1::new();
5728 let (_, pubkey_1) = get_keys_from!(
5729 "0101010101010101010101010101010101010101010101010101010101010101",
5730 secp_ctx
5731 );
5732 let splice_ack = msgs::SpliceAck {
5733 channel_id: ChannelId::from_bytes([2; 32]),
5734 funding_contribution_satoshis: -123456,
5735 funding_pubkey: pubkey_1,
5736 require_confirmed_inputs: Some(()),
5737 };
5738 let encoded_value = splice_ack.encode();
5739 assert_eq!(encoded_value.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020202fffffffffffe1dc0031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0200");
5740 }
5741
5742 #[test]
5743 fn encoding_splice_locked() {
5744 let splice_locked = msgs::SpliceLocked {
5745 channel_id: ChannelId::from_bytes([2; 32]),
5746 splice_txid: Txid::from_str(
5747 "c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e",
5748 )
5749 .unwrap(),
5750 };
5751 let encoded_value = splice_locked.encode();
5752 assert_eq!(encoded_value.as_hex().to_string(), "02020202020202020202020202020202020202020202020202020202020202026e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2");
5753 }
5754
5755 #[test]
5756 fn encoding_tx_add_input() {
5757 let tx_add_input = msgs::TxAddInput {
5758 channel_id: ChannelId::from_bytes([2; 32]),
5759 serial_id: 4886718345,
5760 prevtx: Some(Transaction {
5761 version: Version::TWO,
5762 lock_time: LockTime::ZERO,
5763 input: vec![TxIn {
5764 previous_output: OutPoint { txid: Txid::from_str("305bab643ee297b8b6b76b320792c8223d55082122cb606bf89382146ced9c77").unwrap(), index: 2 }.into_bitcoin_outpoint(),
5765 script_sig: ScriptBuf::new(),
5766 sequence: Sequence(0xfffffffd),
5767 witness: Witness::from_slice(&[
5768 <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
5769 <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
5770 }],
5771 output: vec![
5772 TxOut {
5773 value: Amount::from_sat(12704566),
5774 script_pubkey: Address::from_str("bc1qzlffunw52jav8vwdu5x3jfk6sr8u22rmq3xzw2").unwrap().assume_checked().script_pubkey(),
5775 },
5776 TxOut {
5777 value: Amount::from_sat(245148),
5778 script_pubkey: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z").unwrap().assume_checked().script_pubkey(),
5779 },
5780 ],
5781 }),
5782 prevtx_out: 305419896,
5783 sequence: 305419896,
5784 shared_input_txid: None,
5785 };
5786 let encoded_value = tx_add_input.encode();
5787 let target_value = "0202020202020202020202020202020202020202020202020202020202020202000000012345678900de02000000000101779ced6c148293f86b60cb222108553d22c89207326bb7b6b897e23e64ab5b300200000000fdffffff0236dbc1000000000016001417d29e4dd454bac3b1cde50d1926da80cfc5287b9cbd03000000000016001436ec78d514df462da95e6a00c24daa8915362d420247304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701210301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944000000001234567812345678";
5788 assert_eq!(encoded_value.as_hex().to_string(), target_value);
5789 }
5790
5791 #[test]
5792 fn encoding_tx_add_input_shared() {
5793 let tx_add_input = msgs::TxAddInput {
5794 channel_id: ChannelId::from_bytes([2; 32]),
5795 serial_id: 4886718345,
5796 prevtx: None,
5797 prevtx_out: 305419896,
5798 sequence: 305419896,
5799 shared_input_txid: Some(
5800 Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e")
5801 .unwrap(),
5802 ),
5803 };
5804 let encoded_value = tx_add_input.encode();
5805 let target_value = "020202020202020202020202020202020202020202020202020202020202020200000001234567890000123456781234567800206e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2";
5806 assert_eq!(encoded_value.as_hex().to_string(), target_value);
5807 }
5808
5809 #[test]
5810 fn encoding_tx_add_output() {
5811 let tx_add_output = msgs::TxAddOutput {
5812 channel_id: ChannelId::from_bytes([2; 32]),
5813 serial_id: 4886718345,
5814 sats: 4886718345,
5815 script: Address::from_str("bc1qxmk834g5marzm227dgqvynd23y2nvt2ztwcw2z")
5816 .unwrap()
5817 .assume_checked()
5818 .script_pubkey(),
5819 };
5820 let encoded_value = tx_add_output.encode();
5821 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000000012345678900000001234567890016001436ec78d514df462da95e6a00c24daa8915362d42").unwrap();
5822 assert_eq!(encoded_value, target_value);
5823 }
5824
5825 #[test]
5826 fn encoding_tx_remove_input() {
5827 let tx_remove_input = msgs::TxRemoveInput {
5828 channel_id: ChannelId::from_bytes([2; 32]),
5829 serial_id: 4886718345,
5830 };
5831 let encoded_value = tx_remove_input.encode();
5832 let target_value = <Vec<u8>>::from_hex(
5833 "02020202020202020202020202020202020202020202020202020202020202020000000123456789",
5834 )
5835 .unwrap();
5836 assert_eq!(encoded_value, target_value);
5837 }
5838
5839 #[test]
5840 fn encoding_tx_remove_output() {
5841 let tx_remove_output = msgs::TxRemoveOutput {
5842 channel_id: ChannelId::from_bytes([2; 32]),
5843 serial_id: 4886718345,
5844 };
5845 let encoded_value = tx_remove_output.encode();
5846 let target_value = <Vec<u8>>::from_hex(
5847 "02020202020202020202020202020202020202020202020202020202020202020000000123456789",
5848 )
5849 .unwrap();
5850 assert_eq!(encoded_value, target_value);
5851 }
5852
5853 #[test]
5854 fn encoding_tx_complete() {
5855 let tx_complete = msgs::TxComplete { channel_id: ChannelId::from_bytes([2; 32]) };
5856 let encoded_value = tx_complete.encode();
5857 let target_value =
5858 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5859 .unwrap();
5860 assert_eq!(encoded_value, target_value);
5861 }
5862
5863 #[test]
5864 fn encoding_tx_signatures() {
5865 let secp_ctx = Secp256k1::new();
5866 let (privkey_1, _) = get_keys_from!(
5867 "0101010101010101010101010101010101010101010101010101010101010101",
5868 secp_ctx
5869 );
5870 let sig_1 =
5871 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
5872
5873 let tx_signatures = msgs::TxSignatures {
5874 channel_id: ChannelId::from_bytes([2; 32]),
5875 tx_hash: Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap(),
5876 witnesses: vec![
5877 Witness::from_slice(&[
5878 <Vec<u8>>::from_hex("304402206af85b7dd67450ad12c979302fac49dfacbc6a8620f49c5da2b5721cf9565ca502207002b32fed9ce1bf095f57aeb10c36928ac60b12e723d97d2964a54640ceefa701").unwrap(),
5879 <Vec<u8>>::from_hex("0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944").unwrap()]),
5880 Witness::from_slice(&[
5881 <Vec<u8>>::from_hex("3045022100ee00dbf4a862463e837d7c08509de814d620e4d9830fa84818713e0fa358f145022021c3c7060c4d53fe84fd165d60208451108a778c13b92ca4c6bad439236126cc01").unwrap(),
5882 <Vec<u8>>::from_hex("028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5").unwrap()]),
5883 ],
5884 shared_input_signature: Some(sig_1),
5885 };
5886 let encoded_value = tx_signatures.encode();
5887 let mut target_value =
5888 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5889 .unwrap(); target_value.append(
5891 &mut <Vec<u8>>::from_hex(
5892 "6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2",
5893 )
5894 .unwrap(),
5895 ); 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());
5903 target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); target_value.append(
5905 &mut <Vec<u8>>::from_hex(
5906 "0301ab7dc16488303549bfcdd80f6ae5ee4c20bf97ab5410bbd6b1bfa85dcd6944",
5907 )
5908 .unwrap(),
5909 );
5910 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());
5915 target_value.append(&mut <Vec<u8>>::from_hex("21").unwrap()); target_value.append(
5917 &mut <Vec<u8>>::from_hex(
5918 "028fbbf0b16f5ba5bcb5dd37cd4047ce6f726a21c06682f9ec2f52b057de1dbdb5",
5919 )
5920 .unwrap(),
5921 );
5922 target_value.append(&mut <Vec<u8>>::from_hex("0040").unwrap()); target_value.append(&mut <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap());
5924 assert_eq!(encoded_value, target_value);
5925 }
5926
5927 fn do_encoding_tx_init_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
5928 let tx_init_rbf = msgs::TxInitRbf {
5929 channel_id: ChannelId::from_bytes([2; 32]),
5930 locktime: 305419896,
5931 feerate_sat_per_1000_weight: 20190119,
5932 funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target {
5933 Some(value)
5934 } else {
5935 None
5936 },
5937 };
5938 let encoded_value = tx_init_rbf.encode();
5939 let mut target_value =
5940 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5941 .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 {
5945 target_value.push(0x00); target_value.push(target.len() as u8 / 2); target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); }
5949 assert_eq!(encoded_value, target_value);
5950 }
5951
5952 #[test]
5953 fn encoding_tx_init_rbf() {
5954 do_encoding_tx_init_rbf(Some((1311768467284833366, "1234567890123456")));
5955 do_encoding_tx_init_rbf(Some((13117684672, "000000030DDFFBC0")));
5956 do_encoding_tx_init_rbf(None);
5957 }
5958
5959 fn do_encoding_tx_ack_rbf(funding_value_with_hex_target: Option<(i64, &str)>) {
5960 let tx_ack_rbf = msgs::TxAckRbf {
5961 channel_id: ChannelId::from_bytes([2; 32]),
5962 funding_output_contribution: if let Some((value, _)) = funding_value_with_hex_target {
5963 Some(value)
5964 } else {
5965 None
5966 },
5967 };
5968 let encoded_value = tx_ack_rbf.encode();
5969 let mut target_value =
5970 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
5971 .unwrap();
5972 if let Some((_, target)) = funding_value_with_hex_target {
5973 target_value.push(0x00); target_value.push(target.len() as u8 / 2); target_value.append(&mut <Vec<u8>>::from_hex(target).unwrap()); }
5977 assert_eq!(encoded_value, target_value);
5978 }
5979
5980 #[test]
5981 fn encoding_tx_ack_rbf() {
5982 do_encoding_tx_ack_rbf(Some((1311768467284833366, "1234567890123456")));
5983 do_encoding_tx_ack_rbf(Some((13117684672, "000000030DDFFBC0")));
5984 do_encoding_tx_ack_rbf(None);
5985 }
5986
5987 #[test]
5988 fn encoding_tx_abort() {
5989 let tx_abort = msgs::TxAbort {
5990 channel_id: ChannelId::from_bytes([2; 32]),
5991 data: <Vec<u8>>::from_hex("54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap(),
5992 };
5993 let encoded_value = tx_abort.encode();
5994 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202002C54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F672E").unwrap();
5995 assert_eq!(encoded_value, target_value);
5996 }
5997
5998 fn do_encoding_shutdown(script_type: u8) {
5999 let secp_ctx = Secp256k1::new();
6000 let (_, pubkey_1) = get_keys_from!(
6001 "0101010101010101010101010101010101010101010101010101010101010101",
6002 secp_ctx
6003 );
6004 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
6005 let shutdown = msgs::Shutdown {
6006 channel_id: ChannelId::from_bytes([2; 32]),
6007 scriptpubkey: if script_type == 1 {
6008 Address::p2pkh(
6009 &::bitcoin::PublicKey { compressed: true, inner: pubkey_1 },
6010 Network::Testnet,
6011 )
6012 .script_pubkey()
6013 } else if script_type == 2 {
6014 Address::p2sh(&script, Network::Testnet).unwrap().script_pubkey()
6015 } else if script_type == 3 {
6016 Address::p2wpkh(&::bitcoin::CompressedPublicKey(pubkey_1), Network::Testnet)
6017 .script_pubkey()
6018 } else {
6019 Address::p2wsh(&script, Network::Testnet).script_pubkey()
6020 },
6021 };
6022 let encoded_value = shutdown.encode();
6023 let mut target_value =
6024 <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202")
6025 .unwrap();
6026 if script_type == 1 {
6027 target_value.append(
6028 &mut <Vec<u8>>::from_hex("001976a91479b000887626b294a914501a4cd226b58b23598388ac")
6029 .unwrap(),
6030 );
6031 } else if script_type == 2 {
6032 target_value.append(
6033 &mut <Vec<u8>>::from_hex("0017a914da1745e9b549bd0bfa1a569971c77eba30cd5a4b87")
6034 .unwrap(),
6035 );
6036 } else if script_type == 3 {
6037 target_value.append(
6038 &mut <Vec<u8>>::from_hex("0016001479b000887626b294a914501a4cd226b58b235983")
6039 .unwrap(),
6040 );
6041 } else if script_type == 4 {
6042 target_value.append(
6043 &mut <Vec<u8>>::from_hex(
6044 "002200204ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260",
6045 )
6046 .unwrap(),
6047 );
6048 }
6049 assert_eq!(encoded_value, target_value);
6050 }
6051
6052 #[test]
6053 fn encoding_shutdown() {
6054 do_encoding_shutdown(1);
6055 do_encoding_shutdown(2);
6056 do_encoding_shutdown(3);
6057 do_encoding_shutdown(4);
6058 }
6059
6060 #[test]
6061 fn encoding_closing_signed() {
6062 let secp_ctx = Secp256k1::new();
6063 let (privkey_1, _) = get_keys_from!(
6064 "0101010101010101010101010101010101010101010101010101010101010101",
6065 secp_ctx
6066 );
6067 let sig_1 =
6068 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
6069 let closing_signed = msgs::ClosingSigned {
6070 channel_id: ChannelId::from_bytes([2; 32]),
6071 fee_satoshis: 2316138423780173,
6072 signature: sig_1,
6073 fee_range: None,
6074 };
6075 let encoded_value = closing_signed.encode();
6076 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a").unwrap();
6077 assert_eq!(encoded_value, target_value);
6078 assert_eq!(
6079 msgs::ClosingSigned::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(),
6080 closing_signed
6081 );
6082
6083 let closing_signed_with_range = msgs::ClosingSigned {
6084 channel_id: ChannelId::from_bytes([2; 32]),
6085 fee_satoshis: 2316138423780173,
6086 signature: sig_1,
6087 fee_range: Some(msgs::ClosingSignedFeeRange {
6088 min_fee_satoshis: 0xdeadbeef,
6089 max_fee_satoshis: 0x1badcafe01234567,
6090 }),
6091 };
6092 let encoded_value_with_range = closing_signed_with_range.encode();
6093 let target_value_with_range = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034dd977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a011000000000deadbeef1badcafe01234567").unwrap();
6094 assert_eq!(encoded_value_with_range, target_value_with_range);
6095 assert_eq!(
6096 msgs::ClosingSigned::read_from_fixed_length_buffer(&mut &target_value_with_range[..])
6097 .unwrap(),
6098 closing_signed_with_range
6099 );
6100 }
6101
6102 #[test]
6103 fn encoding_update_add_htlc() {
6104 let secp_ctx = Secp256k1::new();
6105 let (_, pubkey_1) = get_keys_from!(
6106 "0101010101010101010101010101010101010101010101010101010101010101",
6107 secp_ctx
6108 );
6109 let onion_routing_packet = msgs::OnionPacket {
6110 version: 255,
6111 public_key: Ok(pubkey_1),
6112 hop_data: [1; 20 * 65],
6113 hmac: [2; 32],
6114 };
6115 let update_add_htlc = msgs::UpdateAddHTLC {
6116 channel_id: ChannelId::from_bytes([2; 32]),
6117 htlc_id: 2316138423780173,
6118 amount_msat: 3608586615801332854,
6119 payment_hash: PaymentHash([1; 32]),
6120 cltv_expiry: 821716,
6121 onion_routing_packet,
6122 skimmed_fee_msat: None,
6123 blinding_point: None,
6124 hold_htlc: None,
6125 accountable: None,
6126 };
6127 let encoded_value = update_add_htlc.encode();
6128 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d32144668701144760101010101010101010101010101010101010101010101010101010101010101000c89d4ff031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap();
6129 assert_eq!(encoded_value, target_value);
6130 }
6131
6132 #[test]
6133 fn encoding_update_fulfill_htlc() {
6134 let update_fulfill_htlc = msgs::UpdateFulfillHTLC {
6135 channel_id: ChannelId::from_bytes([2; 32]),
6136 htlc_id: 2316138423780173,
6137 payment_preimage: PaymentPreimage([1; 32]),
6138 attribution_data: None,
6139 };
6140 let encoded_value = update_fulfill_htlc.encode();
6141 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0101010101010101010101010101010101010101010101010101010101010101").unwrap();
6142 assert_eq!(encoded_value, target_value);
6143 }
6144
6145 #[test]
6146 fn encoding_update_fail_htlc() {
6147 let update_fail_htlc = msgs::UpdateFailHTLC {
6148 channel_id: ChannelId::from_bytes([2; 32]),
6149 htlc_id: 2316138423780173,
6150 reason: [1; 32].to_vec(),
6151 attribution_data: Some(AttributionData::new()),
6152 };
6153 let encoded_value = update_fail_htlc.encode();
6154 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d0020010101010101010101010101010101010101010101010101010101010101010101fd03980000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6155 assert_eq!(encoded_value, target_value);
6156 }
6157
6158 #[test]
6159 fn encoding_update_fail_malformed_htlc() {
6160 let update_fail_malformed_htlc = msgs::UpdateFailMalformedHTLC {
6161 channel_id: ChannelId::from_bytes([2; 32]),
6162 htlc_id: 2316138423780173,
6163 sha256_of_onion: [1; 32],
6164 failure_code: 255,
6165 };
6166 let encoded_value = update_fail_malformed_htlc.encode();
6167 let target_value = <Vec<u8>>::from_hex("020202020202020202020202020202020202020202020202020202020202020200083a840000034d010101010101010101010101010101010101010101010101010101010101010100ff").unwrap();
6168 assert_eq!(encoded_value, target_value);
6169 }
6170
6171 fn do_encoding_commitment_signed(htlcs: bool) {
6172 let secp_ctx = Secp256k1::new();
6173 let (privkey_1, _) = get_keys_from!(
6174 "0101010101010101010101010101010101010101010101010101010101010101",
6175 secp_ctx
6176 );
6177 let (privkey_2, _) = get_keys_from!(
6178 "0202020202020202020202020202020202020202020202020202020202020202",
6179 secp_ctx
6180 );
6181 let (privkey_3, _) = get_keys_from!(
6182 "0303030303030303030303030303030303030303030303030303030303030303",
6183 secp_ctx
6184 );
6185 let (privkey_4, _) = get_keys_from!(
6186 "0404040404040404040404040404040404040404040404040404040404040404",
6187 secp_ctx
6188 );
6189 let sig_1 =
6190 get_sig_on!(privkey_1, secp_ctx, String::from("01010101010101010101010101010101"));
6191 let sig_2 =
6192 get_sig_on!(privkey_2, secp_ctx, String::from("01010101010101010101010101010101"));
6193 let sig_3 =
6194 get_sig_on!(privkey_3, secp_ctx, String::from("01010101010101010101010101010101"));
6195 let sig_4 =
6196 get_sig_on!(privkey_4, secp_ctx, String::from("01010101010101010101010101010101"));
6197 let commitment_signed = msgs::CommitmentSigned {
6198 channel_id: ChannelId::from_bytes([2; 32]),
6199 signature: sig_1,
6200 htlc_signatures: if htlcs { vec![sig_2, sig_3, sig_4] } else { Vec::new() },
6201 funding_txid: Some(
6202 Txid::from_str("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e")
6203 .unwrap(),
6204 ),
6205 };
6206 let encoded_value = commitment_signed.encode();
6207 let mut target_value = "0202020202020202020202020202020202020202020202020202020202020202d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a".to_string();
6208 if htlcs {
6209 target_value += "00031735b6a427e80d5fe7cd90a2f4ee08dc9c27cda7c35a4172e5d85b12c49d4232537e98f9b1f3c5e6989a8b9644e90e8918127680dbd0d4043510840fc0f1e11a216c280b5395a2546e7e4b2663e04f811622f15a4f91e83aa2e92ba2a573c139142c54ae63072a1ec1ee7dc0c04bde5c847806172aa05c92c22ae8e308d1d2692b12cc195ce0a2d1bda6a88befa19fa07f51caa75ce83837f28965600b8aacab0855ffb0e741ec5f7c41421e9829a9d48611c8c831f71be5ea73e66594977ffd";
6210 } else {
6211 target_value += "0000";
6212 }
6213 target_value += "01"; target_value += "20"; target_value += "6e96fe9f8b0ddcd729ba03cfafa5a27b050b39d354dd980814268dfa9a44d4c2"; assert_eq!(encoded_value.as_hex().to_string(), target_value);
6217 }
6218
6219 #[test]
6220 fn encoding_commitment_signed() {
6221 do_encoding_commitment_signed(true);
6222 do_encoding_commitment_signed(false);
6223 }
6224
6225 #[test]
6226 fn encoding_revoke_and_ack() {
6227 let secp_ctx = Secp256k1::new();
6228 let (_, pubkey_1) = get_keys_from!(
6229 "0101010101010101010101010101010101010101010101010101010101010101",
6230 secp_ctx
6231 );
6232 let raa = msgs::RevokeAndACK {
6233 channel_id: ChannelId::from_bytes([2; 32]),
6234 per_commitment_secret: [
6235 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,
6236 1, 1, 1, 1,
6237 ],
6238 next_per_commitment_point: pubkey_1,
6239 release_htlc_message_paths: Vec::new(),
6240 };
6241 let encoded_value = raa.encode();
6242 let target_value = <Vec<u8>>::from_hex("02020202020202020202020202020202020202020202020202020202020202020101010101010101010101010101010101010101010101010101010101010101031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f").unwrap();
6243 assert_eq!(encoded_value, target_value);
6244 }
6245
6246 #[test]
6247 fn encoding_update_fee() {
6248 let update_fee = msgs::UpdateFee {
6249 channel_id: ChannelId::from_bytes([2; 32]),
6250 feerate_per_kw: 20190119,
6251 };
6252 let encoded_value = update_fee.encode();
6253 let target_value = <Vec<u8>>::from_hex(
6254 "0202020202020202020202020202020202020202020202020202020202020202013413a7",
6255 )
6256 .unwrap();
6257 assert_eq!(encoded_value, target_value);
6258 }
6259
6260 #[test]
6261 fn encoding_init() {
6262 let mainnet_hash = ChainHash::using_genesis_block(Network::Bitcoin);
6263 assert_eq!(msgs::Init {
6264 features: InitFeatures::from_le_bytes(vec![0xFF, 0xFF, 0xFF]),
6265 networks: Some(vec![mainnet_hash]),
6266 remote_network_address: None,
6267 }.encode(), <Vec<u8>>::from_hex("00023fff0003ffffff01206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000").unwrap());
6268 assert_eq!(
6269 msgs::Init {
6270 features: InitFeatures::from_le_bytes(vec![0xFF]),
6271 networks: None,
6272 remote_network_address: None,
6273 }
6274 .encode(),
6275 <Vec<u8>>::from_hex("0001ff0001ff").unwrap()
6276 );
6277 assert_eq!(
6278 msgs::Init {
6279 features: InitFeatures::from_le_bytes(vec![]),
6280 networks: Some(vec![mainnet_hash]),
6281 remote_network_address: None,
6282 }
6283 .encode(),
6284 <Vec<u8>>::from_hex(
6285 "0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000"
6286 )
6287 .unwrap()
6288 );
6289 assert_eq!(msgs::Init {
6290 features: InitFeatures::from_le_bytes(vec![]),
6291 networks: Some(vec![ChainHash::from(&[1; 32]), ChainHash::from(&[2; 32])]),
6292 remote_network_address: None,
6293 }.encode(), <Vec<u8>>::from_hex("00000000014001010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202").unwrap());
6294 let init_msg = msgs::Init {
6295 features: InitFeatures::from_le_bytes(vec![]),
6296 networks: Some(vec![mainnet_hash]),
6297 remote_network_address: Some(SocketAddress::TcpIpV4 {
6298 addr: [127, 0, 0, 1],
6299 port: 1000,
6300 }),
6301 };
6302 let encoded_value = init_msg.encode();
6303 let target_value = <Vec<u8>>::from_hex("0000000001206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d61900000000000307017f00000103e8").unwrap();
6304 assert_eq!(encoded_value, target_value);
6305 assert_eq!(
6306 msgs::Init::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap(),
6307 init_msg
6308 );
6309 }
6310
6311 #[test]
6312 fn encoding_error() {
6313 let error = msgs::ErrorMessage {
6314 channel_id: ChannelId::from_bytes([2; 32]),
6315 data: String::from("rust-lightning"),
6316 };
6317 let encoded_value = error.encode();
6318 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
6319 assert_eq!(encoded_value, target_value);
6320 }
6321
6322 #[test]
6323 fn encoding_warning() {
6324 let error = msgs::WarningMessage {
6325 channel_id: ChannelId::from_bytes([2; 32]),
6326 data: String::from("rust-lightning"),
6327 };
6328 let encoded_value = error.encode();
6329 let target_value = <Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202000e727573742d6c696768746e696e67").unwrap();
6330 assert_eq!(encoded_value, target_value);
6331 }
6332
6333 #[test]
6334 fn encoding_ping() {
6335 let ping = msgs::Ping { ponglen: 64, byteslen: 64 };
6336 let encoded_value = ping.encode();
6337 let target_value = <Vec<u8>>::from_hex("0040004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6338 assert_eq!(encoded_value, target_value);
6339 }
6340
6341 #[test]
6342 fn encoding_peer_storage() {
6343 let peer_storage =
6344 msgs::PeerStorage { data: <Vec<u8>>::from_hex("01020304050607080910").unwrap() };
6345 let encoded_value = peer_storage.encode();
6346 let target_value = <Vec<u8>>::from_hex("000a01020304050607080910").unwrap();
6347 assert_eq!(encoded_value, target_value);
6348 }
6349
6350 #[test]
6351 fn encoding_peer_storage_retrieval() {
6352 let peer_storage_retrieval = msgs::PeerStorageRetrieval {
6353 data: <Vec<u8>>::from_hex("01020304050607080910").unwrap(),
6354 };
6355 let encoded_value = peer_storage_retrieval.encode();
6356 let target_value = <Vec<u8>>::from_hex("000a01020304050607080910").unwrap();
6357 assert_eq!(encoded_value, target_value);
6358 }
6359
6360 #[test]
6361 fn encoding_pong() {
6362 let pong = msgs::Pong { byteslen: 64 };
6363 let encoded_value = pong.encode();
6364 let target_value = <Vec<u8>>::from_hex("004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
6365 assert_eq!(encoded_value, target_value);
6366 }
6367
6368 #[test]
6369 fn encoding_nonfinal_onion_hop_data() {
6370 let outbound_msg = msgs::OutboundOnionPayload::Forward {
6371 short_channel_id: 0xdeadbeef1bad1dea,
6372 amt_to_forward: 0x0badf00d01020304,
6373 outgoing_cltv_value: 0xffffffff,
6374 };
6375 let encoded_value = outbound_msg.encode();
6376 let target_value =
6377 <Vec<u8>>::from_hex("1a02080badf00d010203040404ffffffff0608deadbeef1bad1dea").unwrap();
6378 assert_eq!(encoded_value, target_value);
6379
6380 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6381 let inbound_msg =
6382 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6383 if let msgs::InboundOnionPayload::Forward(InboundOnionForwardPayload {
6384 short_channel_id,
6385 amt_to_forward,
6386 outgoing_cltv_value,
6387 }) = inbound_msg
6388 {
6389 assert_eq!(short_channel_id, 0xdeadbeef1bad1dea);
6390 assert_eq!(amt_to_forward, 0x0badf00d01020304);
6391 assert_eq!(outgoing_cltv_value, 0xffffffff);
6392 } else {
6393 panic!();
6394 }
6395 }
6396
6397 #[test]
6398 fn encoding_final_onion_hop_data() {
6399 let outbound_msg = msgs::OutboundOnionPayload::Receive {
6400 payment_data: None,
6401 payment_metadata: None,
6402 keysend_preimage: None,
6403 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6404 cltv_expiry_height: 0xffffffff,
6405 custom_tlvs: &vec![],
6406 };
6407 let encoded_value = outbound_msg.encode();
6408 let target_value = <Vec<u8>>::from_hex("1002080badf00d010203040404ffffffff").unwrap();
6409 assert_eq!(encoded_value, target_value);
6410
6411 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6412 let inbound_msg =
6413 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6414 if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6415 payment_data: None,
6416 sender_intended_htlc_amt_msat,
6417 cltv_expiry_height,
6418 ..
6419 }) = inbound_msg
6420 {
6421 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6422 assert_eq!(cltv_expiry_height, 0xffffffff);
6423 } else {
6424 panic!();
6425 }
6426 }
6427
6428 #[test]
6429 fn encoding_final_onion_hop_data_with_secret() {
6430 let expected_payment_secret = PaymentSecret([0x42u8; 32]);
6431 let outbound_msg = msgs::OutboundOnionPayload::Receive {
6432 payment_data: Some(FinalOnionHopData {
6433 payment_secret: expected_payment_secret,
6434 total_msat: 0x1badca1f,
6435 }),
6436 payment_metadata: None,
6437 keysend_preimage: None,
6438 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6439 cltv_expiry_height: 0xffffffff,
6440 custom_tlvs: &vec![],
6441 };
6442 let encoded_value = outbound_msg.encode();
6443 let target_value = <Vec<u8>>::from_hex("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
6444 assert_eq!(encoded_value, target_value);
6445
6446 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6447 let inbound_msg =
6448 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6449 if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6450 payment_data: Some(FinalOnionHopData { payment_secret, total_msat: 0x1badca1f }),
6451 sender_intended_htlc_amt_msat,
6452 cltv_expiry_height,
6453 payment_metadata: None,
6454 keysend_preimage: None,
6455 custom_tlvs,
6456 }) = inbound_msg
6457 {
6458 assert_eq!(payment_secret, expected_payment_secret);
6459 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6460 assert_eq!(cltv_expiry_height, 0xffffffff);
6461 assert_eq!(custom_tlvs, vec![]);
6462 } else {
6463 panic!();
6464 }
6465 }
6466
6467 #[test]
6468 fn encoding_final_onion_hop_data_with_bad_custom_tlvs() {
6469 let bad_type_range_tlvs = vec![((1 << 16) - 4, vec![42]), ((1 << 16) - 2, vec![42; 32])];
6472 let mut msg = msgs::OutboundOnionPayload::Receive {
6473 payment_data: None,
6474 payment_metadata: None,
6475 keysend_preimage: None,
6476 custom_tlvs: &bad_type_range_tlvs,
6477 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6478 cltv_expiry_height: 0xffffffff,
6479 };
6480 let encoded_value = msg.encode();
6481 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6482 assert!(msgs::InboundOnionPayload::read(
6483 &mut Cursor::new(&encoded_value[..]),
6484 (None, &node_signer)
6485 )
6486 .is_err());
6487 let good_type_range_tlvs = vec![((1 << 16) - 3, vec![42]), ((1 << 16) - 1, vec![42; 32])];
6488 if let msgs::OutboundOnionPayload::Receive { ref mut custom_tlvs, .. } = msg {
6489 *custom_tlvs = &good_type_range_tlvs;
6490 }
6491 let encoded_value = msg.encode();
6492 let inbound_msg =
6493 ReadableArgs::read(&mut Cursor::new(&encoded_value[..]), (None, &node_signer)).unwrap();
6494 match inbound_msg {
6495 msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6496 custom_tlvs, ..
6497 }) => assert!(custom_tlvs.is_empty()),
6498 _ => panic!(),
6499 }
6500 }
6501
6502 #[test]
6503 fn encoding_final_onion_hop_data_with_custom_tlvs() {
6504 let expected_custom_tlvs =
6505 vec![(5482373483, vec![0x12, 0x34]), (5482373487, vec![0x42u8; 8])];
6506 let msg = msgs::OutboundOnionPayload::Receive {
6507 payment_data: None,
6508 payment_metadata: None,
6509 keysend_preimage: None,
6510 custom_tlvs: &expected_custom_tlvs,
6511 sender_intended_htlc_amt_msat: 0x0badf00d01020304,
6512 cltv_expiry_height: 0xffffffff,
6513 };
6514 let encoded_value = msg.encode();
6515 let target_value = <Vec<u8>>::from_hex("2e02080badf00d010203040404ffffffffff0000000146c6616b021234ff0000000146c6616f084242424242424242").unwrap();
6516 assert_eq!(encoded_value, target_value);
6517 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6518 let inbound_msg: msgs::InboundOnionPayload =
6519 ReadableArgs::read(&mut Cursor::new(&target_value[..]), (None, &node_signer)).unwrap();
6520 if let msgs::InboundOnionPayload::Receive(InboundOnionReceivePayload {
6521 payment_data: None,
6522 payment_metadata: None,
6523 keysend_preimage: None,
6524 custom_tlvs,
6525 sender_intended_htlc_amt_msat,
6526 cltv_expiry_height: outgoing_cltv_value,
6527 ..
6528 }) = inbound_msg
6529 {
6530 assert_eq!(custom_tlvs, expected_custom_tlvs);
6531 assert_eq!(sender_intended_htlc_amt_msat, 0x0badf00d01020304);
6532 assert_eq!(outgoing_cltv_value, 0xffffffff);
6533 } else {
6534 panic!();
6535 }
6536 }
6537
6538 #[test]
6539 fn encoding_final_onion_hop_data_with_trampoline_packet() {
6540 let secp_ctx = Secp256k1::new();
6541 let (_private_key, public_key) = get_keys_from!(
6542 "0101010101010101010101010101010101010101010101010101010101010101",
6543 secp_ctx
6544 );
6545
6546 let compressed_public_key = public_key.serialize();
6547 assert_eq!(compressed_public_key.len(), 33);
6548
6549 let trampoline_packet = TrampolineOnionPacket {
6550 version: 0,
6551 public_key,
6552 hop_data: vec![1; 650], hmac: [2; 32],
6554 };
6555 let encoded_trampoline_packet = trampoline_packet.encode();
6556 assert_eq!(encoded_trampoline_packet.len(), 716);
6557
6558 {
6559 let decoded_trampoline_packet: TrampolineOnionPacket =
6561 <TrampolineOnionPacket as LengthReadable>::read_from_fixed_length_buffer(
6562 &mut &encoded_trampoline_packet[..],
6563 )
6564 .unwrap();
6565 assert_eq!(decoded_trampoline_packet.encode(), encoded_trampoline_packet);
6566 }
6567
6568 let msg = msgs::OutboundOnionPayload::TrampolineEntrypoint {
6569 multipath_trampoline_data: None,
6570 amt_to_forward: 0x0badf00d01020304,
6571 outgoing_cltv_value: 0xffffffff,
6572 trampoline_packet,
6573 };
6574 let encoded_payload = msg.encode();
6575
6576 let trampoline_type_bytes = &encoded_payload[19..=19];
6577 let mut trampoline_type_cursor = Cursor::new(trampoline_type_bytes);
6578 let trampoline_type_big_size: BigSize =
6579 Readable::read(&mut trampoline_type_cursor).unwrap();
6580 assert_eq!(trampoline_type_big_size.0, 20);
6581
6582 let trampoline_length_bytes = &encoded_payload[20..=22];
6583 let mut trampoline_length_cursor = Cursor::new(trampoline_length_bytes);
6584 let trampoline_length_big_size: BigSize =
6585 Readable::read(&mut trampoline_length_cursor).unwrap();
6586 assert_eq!(trampoline_length_big_size.0, encoded_trampoline_packet.len() as u64);
6587 }
6588
6589 #[test]
6590 fn encoding_final_onion_hop_data_with_eclair_trampoline_packet() {
6591 let public_key = PublicKey::from_slice(
6592 &<Vec<u8>>::from_hex(
6593 "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
6594 )
6595 .unwrap(),
6596 )
6597 .unwrap();
6598 let hop_data = <Vec<u8>>::from_hex("cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4c").unwrap();
6599 let hmac_vector =
6600 <Vec<u8>>::from_hex("bb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c")
6601 .unwrap();
6602 let mut hmac = [0; 32];
6603 hmac.copy_from_slice(&hmac_vector);
6604
6605 let compressed_public_key = public_key.serialize();
6606 assert_eq!(compressed_public_key.len(), 33);
6607
6608 let trampoline_packet = TrampolineOnionPacket { version: 0, public_key, hop_data, hmac };
6609 let encoded_trampoline_packet = trampoline_packet.encode();
6610 let expected_eclair_trampoline_packet = <Vec<u8>>::from_hex("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619cff34152f3a36e52ca94e74927203a560392b9cc7ce3c45809c6be52166c24a595716880f95f178bf5b30ca63141f74db6e92795c6130877cfdac3d4bd3087ee73c65d627ddd709112a848cc99e303f3706509aa43ba7c8a88cba175fccf9a8f5016ef06d3b935dbb15196d7ce16dc1a7157845566901d7b2197e52cab4ce487014b14816e5805f9fcacb4f8f88b8ff176f1b94f6ce6b00bc43221130c17d20ef629db7c5f7eafaa166578c720619561dd14b3277db557ec7dcdb793771aef0f2f667cfdbeae3ac8d331c5994779dffb31e5fc0dbdedc0c592ca6d21c18e47fe3528d6975c19517d7e2ea8c5391cf17d0fe30c80913ed887234ccb48808f7ef9425bcd815c3b586210979e3bb286ef2851bf9ce04e28c40a203df98fd648d2f1936fd2f1def0e77eecb277229b4b682322371c0a1dbfcd723a991993df8cc1f2696b84b055b40a1792a29f710295a18fbd351b0f3ff34cd13941131b8278ba79303c89117120eea691738a9954908195143b039dbeed98f26a92585f3d15cf742c953799d3272e0545e9b744be9d3b4cbb079bfc4b35190eee9f59a1d7b41ba2f773179f322dafb4b1af900c289ebd6c").unwrap();
6611 assert_eq!(encoded_trampoline_packet, expected_eclair_trampoline_packet);
6612 }
6613
6614 #[test]
6615 fn encoding_outbound_trampoline_payload() {
6616 let mut trampoline_features = Bolt12InvoiceFeatures::empty();
6617 trampoline_features.set_basic_mpp_optional();
6618 let introduction_node = PublicKey::from_slice(
6619 &<Vec<u8>>::from_hex(
6620 "032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",
6621 )
6622 .unwrap(),
6623 )
6624 .unwrap();
6625 let blinding_point = PublicKey::from_slice(
6626 &<Vec<u8>>::from_hex(
6627 "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619",
6628 )
6629 .unwrap(),
6630 )
6631 .unwrap();
6632 let trampoline_payload = OutboundTrampolinePayload::LegacyBlindedPathEntry {
6633 amt_to_forward: 150_000_000,
6634 outgoing_cltv_value: 800_000,
6635 payment_paths: vec![BlindedPaymentPath::from_blinded_path_and_payinfo(
6636 introduction_node,
6637 blinding_point,
6638 vec![],
6639 BlindedPayInfo {
6640 fee_base_msat: 500,
6641 fee_proportional_millionths: 1_000,
6642 cltv_expiry_delta: 36,
6643 htlc_minimum_msat: 1,
6644 htlc_maximum_msat: 500_000_000,
6645 features: BlindedHopFeatures::empty(),
6646 },
6647 )],
6648 invoice_features: Some(trampoline_features),
6649 };
6650 let serialized_payload = trampoline_payload.encode().to_lower_hex_string();
6651 assert_eq!(serialized_payload, "71020408f0d18004030c35001503020000165f032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e66868099102eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661900000001f4000003e800240000000000000001000000001dcd65000000");
6652 }
6653
6654 #[test]
6655 fn encode_trampoline_blinded_path_payload() {
6656 let trampoline_payload_eve = OutboundTrampolinePayload::BlindedReceive {
6657 sender_intended_htlc_amt_msat: 150_000_000,
6658 total_msat: 150_000_000,
6659 cltv_expiry_height: 800_000,
6660 encrypted_tlvs: &<Vec<u8>>::from_hex("bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c").unwrap(),
6661 intro_node_blinding_point: None,
6662 keysend_preimage: None,
6663 custom_tlvs: &vec![],
6664 };
6665 let eve_payload = trampoline_payload_eve.encode().to_lower_hex_string();
6666 assert_eq!(eve_payload, "e4020408f0d18004030c35000ad1bcd747394fbd4d99588da075a623316e15a576df5bc785cccc7cd6ec7b398acce6faf520175f9ec920f2ef261cdb83dc28cc3a0eeb970107b3306489bf771ef5b1213bca811d345285405861d08a655b6c237fa247a8b4491beee20c878a60e9816492026d8feb9dafa84585b253978db6a0aa2945df5ef445c61e801fb82f43d5f00716baf9fc9b3de50bc22950a36bda8fc27bfb1242e5860c7e687438d4133e058770361a19b6c271a2a07788d34dccc27e39b9829b061a4d960eac4a2c2b0f4de506c24f9af3868c0aff6dda27281c120408f0d180");
6667
6668 let trampoline_payload_dave = OutboundTrampolinePayload::BlindedForward {
6669 encrypted_tlvs: &<Vec<u8>>::from_hex("0ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a").unwrap(),
6670 intro_node_blinding_point: Some(PublicKey::from_slice(&<Vec<u8>>::from_hex("02988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e").unwrap()).unwrap()),
6671 };
6672 let dave_payload = trampoline_payload_dave.encode().to_lower_hex_string();
6673 assert_eq!(dave_payload, "690a440ccf3c8a58deaa603f657ee2a5ed9d604eb5c8ca1e5f801989afa8f3ea6d789bbdde2c7e7a1ef9ca8c38d2c54760febad8446d3f273ddb537569ef56613846ccd3aba78a0c2102988face71e92c345a068f740191fd8e53be14f0bb957ef730d3c5f76087b960e")
6674 }
6675
6676 #[test]
6677 fn query_channel_range_end_blocknum() {
6678 let tests: Vec<(u32, u32, u32)> =
6679 vec![(10000, 1500, 11500), (0, 0xffffffff, 0xffffffff), (1, 0xffffffff, 0xffffffff)];
6680
6681 for (first_blocknum, number_of_blocks, expected) in tests.into_iter() {
6682 let sut = msgs::QueryChannelRange {
6683 chain_hash: ChainHash::using_genesis_block(Network::Regtest),
6684 first_blocknum,
6685 number_of_blocks,
6686 };
6687 assert_eq!(sut.end_blocknum(), expected);
6688 }
6689 }
6690
6691 #[test]
6692 fn encoding_query_channel_range() {
6693 let mut query_channel_range = msgs::QueryChannelRange {
6694 chain_hash: ChainHash::using_genesis_block(Network::Regtest),
6695 first_blocknum: 100000,
6696 number_of_blocks: 1500,
6697 };
6698 let encoded_value = query_channel_range.encode();
6699 let target_value = <Vec<u8>>::from_hex(
6700 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000186a0000005dc",
6701 )
6702 .unwrap();
6703 assert_eq!(encoded_value, target_value);
6704
6705 query_channel_range =
6706 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6707 assert_eq!(query_channel_range.first_blocknum, 100000);
6708 assert_eq!(query_channel_range.number_of_blocks, 1500);
6709 }
6710
6711 #[test]
6712 fn encoding_reply_channel_range() {
6713 do_encoding_reply_channel_range(0);
6714 do_encoding_reply_channel_range(1);
6715 }
6716
6717 fn do_encoding_reply_channel_range(encoding_type: u8) {
6718 let mut target_value = <Vec<u8>>::from_hex(
6719 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f000b8a06000005dc01",
6720 )
6721 .unwrap();
6722 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6723 let mut reply_channel_range = msgs::ReplyChannelRange {
6724 chain_hash: expected_chain_hash,
6725 first_blocknum: 756230,
6726 number_of_blocks: 1500,
6727 sync_complete: true,
6728 short_channel_ids: vec![0x000000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
6729 };
6730
6731 if encoding_type == 0 {
6732 target_value.append(
6733 &mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4")
6734 .unwrap(),
6735 );
6736 let encoded_value = reply_channel_range.encode();
6737 assert_eq!(encoded_value, target_value);
6738
6739 reply_channel_range =
6740 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6741 assert_eq!(reply_channel_range.chain_hash, expected_chain_hash);
6742 assert_eq!(reply_channel_range.first_blocknum, 756230);
6743 assert_eq!(reply_channel_range.number_of_blocks, 1500);
6744 assert_eq!(reply_channel_range.sync_complete, true);
6745 assert_eq!(reply_channel_range.short_channel_ids[0], 0x000000000000008e);
6746 assert_eq!(reply_channel_range.short_channel_ids[1], 0x0000000000003c69);
6747 assert_eq!(reply_channel_range.short_channel_ids[2], 0x000000000045a6c4);
6748 } else {
6749 target_value.append(
6750 &mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a")
6751 .unwrap(),
6752 );
6753 let result: Result<msgs::ReplyChannelRange, msgs::DecodeError> =
6754 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]);
6755 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
6756 }
6757 }
6758
6759 #[test]
6760 fn encoding_query_short_channel_ids() {
6761 do_encoding_query_short_channel_ids(0);
6762 do_encoding_query_short_channel_ids(1);
6763 }
6764
6765 fn do_encoding_query_short_channel_ids(encoding_type: u8) {
6766 let mut target_value =
6767 <Vec<u8>>::from_hex("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f")
6768 .unwrap();
6769 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6770 let mut query_short_channel_ids = msgs::QueryShortChannelIds {
6771 chain_hash: expected_chain_hash,
6772 short_channel_ids: vec![0x0000000000008e, 0x0000000000003c69, 0x000000000045a6c4],
6773 };
6774
6775 if encoding_type == 0 {
6776 target_value.append(
6777 &mut <Vec<u8>>::from_hex("001900000000000000008e0000000000003c69000000000045a6c4")
6778 .unwrap(),
6779 );
6780 let encoded_value = query_short_channel_ids.encode();
6781 assert_eq!(encoded_value, target_value);
6782
6783 query_short_channel_ids =
6784 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6785 assert_eq!(query_short_channel_ids.chain_hash, expected_chain_hash);
6786 assert_eq!(query_short_channel_ids.short_channel_ids[0], 0x000000000000008e);
6787 assert_eq!(query_short_channel_ids.short_channel_ids[1], 0x0000000000003c69);
6788 assert_eq!(query_short_channel_ids.short_channel_ids[2], 0x000000000045a6c4);
6789 } else {
6790 target_value.append(
6791 &mut <Vec<u8>>::from_hex("001601789c636000833e08659309a65878be010010a9023a")
6792 .unwrap(),
6793 );
6794 let result: Result<msgs::QueryShortChannelIds, msgs::DecodeError> =
6795 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]);
6796 assert!(result.is_err(), "Expected decode failure with unsupported zlib encoding");
6797 }
6798 }
6799
6800 #[test]
6801 fn encoding_reply_short_channel_ids_end() {
6802 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6803 let mut reply_short_channel_ids_end = msgs::ReplyShortChannelIdsEnd {
6804 chain_hash: expected_chain_hash,
6805 full_information: true,
6806 };
6807 let encoded_value = reply_short_channel_ids_end.encode();
6808 let target_value = <Vec<u8>>::from_hex(
6809 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f01",
6810 )
6811 .unwrap();
6812 assert_eq!(encoded_value, target_value);
6813
6814 reply_short_channel_ids_end =
6815 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6816 assert_eq!(reply_short_channel_ids_end.chain_hash, expected_chain_hash);
6817 assert_eq!(reply_short_channel_ids_end.full_information, true);
6818 }
6819
6820 #[test]
6821 fn encoding_gossip_timestamp_filter() {
6822 let expected_chain_hash = ChainHash::using_genesis_block(Network::Regtest);
6823 let mut gossip_timestamp_filter = msgs::GossipTimestampFilter {
6824 chain_hash: expected_chain_hash,
6825 first_timestamp: 1590000000,
6826 timestamp_range: 0xffff_ffff,
6827 };
6828 let encoded_value = gossip_timestamp_filter.encode();
6829 let target_value = <Vec<u8>>::from_hex(
6830 "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f5ec57980ffffffff",
6831 )
6832 .unwrap();
6833 assert_eq!(encoded_value, target_value);
6834
6835 gossip_timestamp_filter =
6836 LengthReadable::read_from_fixed_length_buffer(&mut &target_value[..]).unwrap();
6837 assert_eq!(gossip_timestamp_filter.chain_hash, expected_chain_hash);
6838 assert_eq!(gossip_timestamp_filter.first_timestamp, 1590000000);
6839 assert_eq!(gossip_timestamp_filter.timestamp_range, 0xffff_ffff);
6840 }
6841
6842 #[test]
6843 fn decode_onion_hop_data_len_as_bigsize() {
6844 let big_payload = encode_big_payload().unwrap();
6852 let mut rd = Cursor::new(&big_payload[..]);
6853
6854 let node_signer = test_utils::TestKeysInterface::new(&[42; 32], Network::Testnet);
6855 <msgs::InboundOnionPayload as ReadableArgs<(
6856 Option<PublicKey>,
6857 &test_utils::TestKeysInterface,
6858 )>>::read(&mut rd, (None, &&node_signer))
6859 .unwrap();
6860 }
6861 fn encode_big_payload() -> Result<Vec<u8>, io::Error> {
6863 use crate::util::ser::HighZeroBytesDroppedBigSize;
6864 let payload = msgs::OutboundOnionPayload::Forward {
6865 short_channel_id: 0xdeadbeef1bad1dea,
6866 amt_to_forward: 1000,
6867 outgoing_cltv_value: 0xffffffff,
6868 };
6869 let mut encoded_payload = Vec::new();
6870 let test_bytes = vec![42u8; 1000];
6871 if let msgs::OutboundOnionPayload::Forward {
6872 short_channel_id,
6873 amt_to_forward,
6874 outgoing_cltv_value,
6875 } = payload
6876 {
6877 _encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
6878 (1, &test_bytes, required_vec),
6879 (2, HighZeroBytesDroppedBigSize(amt_to_forward), required),
6880 (4, HighZeroBytesDroppedBigSize(outgoing_cltv_value), required),
6881 (6, short_channel_id, required)
6882 });
6883 }
6884 Ok(encoded_payload)
6885 }
6886
6887 #[test]
6888 #[cfg(feature = "std")]
6889 fn test_socket_address_from_str() {
6890 let tcpip_v4 =
6891 SocketAddress::TcpIpV4 { addr: Ipv4Addr::new(127, 0, 0, 1).octets(), port: 1234 };
6892 assert_eq!(tcpip_v4, SocketAddress::from_str("127.0.0.1:1234").unwrap());
6893 assert_eq!(tcpip_v4, SocketAddress::from_str(&tcpip_v4.to_string()).unwrap());
6894
6895 let tcpip_v6 = SocketAddress::TcpIpV6 {
6896 addr: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).octets(),
6897 port: 1234,
6898 };
6899 assert_eq!(tcpip_v6, SocketAddress::from_str("[0:0:0:0:0:0:0:1]:1234").unwrap());
6900 assert_eq!(tcpip_v6, SocketAddress::from_str(&tcpip_v6.to_string()).unwrap());
6901
6902 let hostname = SocketAddress::Hostname {
6903 hostname: Hostname::try_from("lightning-node.mydomain.com".to_string()).unwrap(),
6904 port: 1234,
6905 };
6906 assert_eq!(hostname, SocketAddress::from_str("lightning-node.mydomain.com:1234").unwrap());
6907 assert_eq!(hostname, SocketAddress::from_str(&hostname.to_string()).unwrap());
6908
6909 let onion_v2 = SocketAddress::OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7]);
6910 assert_eq!(
6911 "OnionV2([40, 4, 64, 185, 202, 19, 162, 75, 90, 200, 38, 7])",
6912 &onion_v2.to_string()
6913 );
6914 assert_eq!(
6915 Err(SocketAddressParseError::InvalidOnionV3),
6916 SocketAddress::from_str("FACEBOOKCOREWWWI.onion:9735")
6917 );
6918
6919 let onion_v3 = SocketAddress::OnionV3 {
6920 ed25519_pubkey: [
6921 121, 188, 198, 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247,
6922 246, 85, 111, 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31,
6923 ],
6924 checksum: 8519,
6925 version: 3,
6926 port: 1234,
6927 };
6928 let onion_v3_str = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:1234";
6929 let parsed = SocketAddress::from_str(onion_v3_str).unwrap();
6930 assert_eq!(onion_v3, parsed);
6931 assert_eq!(onion_v3_str, parsed.to_string());
6932 match parsed {
6933 SocketAddress::OnionV3 { version, .. } => assert_eq!(version, 3),
6934 _ => panic!("expected OnionV3"),
6935 }
6936
6937 assert_eq!(
6938 Err(SocketAddressParseError::InvalidOnionV3),
6939 SocketAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6.onion:1234")
6940 );
6941 assert_eq!(
6942 Err(SocketAddressParseError::InvalidInput),
6943 SocketAddress::from_str("127.0.0.1@1234")
6944 );
6945 assert_eq!(Err(SocketAddressParseError::InvalidInput), "".parse::<SocketAddress>());
6946 assert!(SocketAddress::from_str(
6947 "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:9735:94"
6948 )
6949 .is_err());
6950 assert!(SocketAddress::from_str("wrong$%#.com:1234").is_err());
6951 assert_eq!(
6952 Err(SocketAddressParseError::InvalidPort),
6953 SocketAddress::from_str("example.com:wrong")
6954 );
6955 assert!("localhost".parse::<SocketAddress>().is_err());
6956 assert!("localhost:invalid-port".parse::<SocketAddress>().is_err());
6957 assert!("invalid-onion-v3-hostname.onion:8080".parse::<SocketAddress>().is_err());
6958 assert!("b32.example.onion:invalid-port".parse::<SocketAddress>().is_err());
6959 assert!("invalid-address".parse::<SocketAddress>().is_err());
6960 assert!(SocketAddress::from_str(
6961 "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion.onion:1234"
6962 )
6963 .is_err());
6964 }
6965
6966 #[test]
6967 #[cfg(feature = "std")]
6968 fn test_socket_address_to_socket_addrs() {
6969 assert_eq!(
6970 SocketAddress::TcpIpV4 { addr: [0u8; 4], port: 1337 }
6971 .to_socket_addrs()
6972 .unwrap()
6973 .next()
6974 .unwrap(),
6975 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 1337))
6976 );
6977 assert_eq!(
6978 SocketAddress::TcpIpV6 { addr: [0u8; 16], port: 1337 }
6979 .to_socket_addrs()
6980 .unwrap()
6981 .next()
6982 .unwrap(),
6983 SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from([0u8; 16]), 1337, 0, 0))
6984 );
6985 assert_eq!(
6986 SocketAddress::Hostname {
6987 hostname: Hostname::try_from("0.0.0.0".to_string()).unwrap(),
6988 port: 0,
6989 }
6990 .to_socket_addrs()
6991 .unwrap()
6992 .next()
6993 .unwrap(),
6994 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from([0u8; 4]), 0))
6995 );
6996 assert!(SocketAddress::OnionV2([0u8; 12]).to_socket_addrs().is_err());
6997 assert!(SocketAddress::OnionV3 {
6998 ed25519_pubkey: [
6999 37, 24, 75, 5, 25, 73, 117, 194, 139, 102, 182, 107, 4, 105, 247, 246, 85, 111,
7000 177, 172, 49, 137, 167, 155, 64, 221, 163, 47, 31, 33, 71, 3
7001 ],
7002 checksum: 48326,
7003 version: 121,
7004 port: 1234
7005 }
7006 .to_socket_addrs()
7007 .is_err());
7008 }
7009
7010 fn test_update_add_htlc() -> msgs::UpdateAddHTLC {
7011 msgs::UpdateAddHTLC {
7012 channel_id: ChannelId::from_bytes([2; 32]),
7013 htlc_id: 42,
7014 amount_msat: 1000,
7015 payment_hash: PaymentHash([1; 32]),
7016 cltv_expiry: 500000,
7017 skimmed_fee_msat: None,
7018 onion_routing_packet: msgs::OnionPacket {
7019 version: 0,
7020 public_key: Ok(pubkey(42)),
7021 hop_data: [1; 20 * 65],
7022 hmac: [2; 32],
7023 },
7024 blinding_point: None,
7025 hold_htlc: None,
7026 accountable: None,
7027 }
7028 }
7029
7030 #[test]
7031 fn test_update_add_htlc_accountable_encoding() {
7032 for (bool_signal, wire_value) in [(Some(false), 0u8), (Some(true), 7u8)] {
7034 let mut base_msg = test_update_add_htlc();
7035 base_msg.accountable = bool_signal;
7036 let encoded = base_msg.encode();
7037 assert_eq!(
7038 *encoded.last().unwrap(),
7039 wire_value,
7040 "wrong wire value for accountable={:?}",
7041 bool_signal
7042 );
7043 }
7044 }
7045
7046 fn do_test_htlc_accountable_from_u8(accountable_override: Option<u8>, expected: Option<bool>) {
7047 let base_msg = test_update_add_htlc();
7050 let mut encoded = base_msg.encode();
7051 if let Some(value) = accountable_override {
7052 encoded.extend_from_slice(&[0xfe, 0x00, 0x01, 0xa1, 0x47]);
7053 encoded.push(1);
7054 encoded.push(value);
7055 }
7056
7057 let decoded: msgs::UpdateAddHTLC =
7058 LengthReadable::read_from_fixed_length_buffer(&mut &encoded[..]).unwrap();
7059
7060 assert_eq!(
7061 decoded.accountable, expected,
7062 "accountable={:?} with override={:?} not eq to expected={:?}",
7063 decoded.accountable, accountable_override, expected
7064 );
7065 }
7066
7067 #[test]
7068 fn update_add_htlc_accountable_from_u8() {
7069 do_test_htlc_accountable_from_u8(None, None);
7071 do_test_htlc_accountable_from_u8(Some(8), Some(false)); do_test_htlc_accountable_from_u8(Some(7), Some(true));
7073 do_test_htlc_accountable_from_u8(Some(3), Some(false));
7074 do_test_htlc_accountable_from_u8(Some(0), Some(false));
7075 }
7076}