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