use lightning::chain::transaction::OutPoint;
use lightning::events::{Event, PathFailure, MessageSendEventsProvider, MessageSendEvent};
use lightning::{get_event_msg, get_event};
- use lightning::ln::{PaymentHash, ChannelId};
+ use lightning::ln::types::{PaymentHash, ChannelId};
use lightning::ln::channelmanager;
use lightning::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChainParameters, MIN_CLTV_EXPIRY_DELTA, PaymentId};
use lightning::ln::features::{ChannelFeatures, NodeFeatures};
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256;
use crate::prelude::*;
-use lightning::ln::PaymentSecret;
+use lightning::ln::types::PaymentSecret;
use lightning::routing::gossip::RoutingFees;
use lightning::routing::router::{RouteHint, RouteHintHop};
use serde::{Deserialize, Deserializer,Serialize, Serializer, de::Error};
#[doc(no_inline)]
-pub use lightning::ln::PaymentSecret;
+pub use lightning::ln::types::PaymentSecret;
#[doc(no_inline)]
pub use lightning::routing::router::{RouteHint, RouteHintHop};
#[doc(no_inline)]
/// use secp256k1::Secp256k1;
/// use secp256k1::SecretKey;
///
-/// use lightning::ln::PaymentSecret;
+/// use lightning::ln::types::PaymentSecret;
///
/// use lightning_invoice::{Currency, InvoiceBuilder};
///
Bolt11SemanticError};
let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
- let payment_secret = lightning::ln::PaymentSecret([21; 32]);
+ let payment_secret = lightning::ln::types::PaymentSecret([21; 32]);
let invoice_template = RawBolt11Invoice {
hrp: RawHrp {
currency: Currency::Bitcoin,
use crate::Bolt11Invoice;
use bitcoin::hashes::Hash;
-use lightning::ln::PaymentHash;
+use lightning::ln::types::PaymentHash;
use lightning::ln::channelmanager::RecipientOnionFields;
use lightning::routing::router::{PaymentParameters, RouteParameters};
use super::*;
use crate::{InvoiceBuilder, Currency};
use bitcoin::hashes::sha256::Hash as Sha256;
- use lightning::ln::PaymentSecret;
+ use lightning::ln::types::PaymentSecret;
use lightning::routing::router::Payee;
use secp256k1::{SecretKey, PublicKey, Secp256k1};
use core::time::Duration;
use lightning::chain;
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use lightning::sign::{Recipient, NodeSigner, SignerProvider, EntropySource};
-use lightning::ln::{PaymentHash, PaymentSecret};
+use lightning::ln::types::{PaymentHash, PaymentSecret};
use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, MIN_FINAL_CLTV_EXPIRY_DELTA};
use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA};
use lightning::ln::inbound_payment::{create, create_from_hash, ExpandedKey};
use bitcoin::hashes::sha256::Hash as Sha256;
use lightning::sign::PhantomKeysManager;
use lightning::events::{MessageSendEvent, MessageSendEventsProvider};
- use lightning::ln::PaymentHash;
+ use lightning::ln::types::PaymentHash;
#[cfg(feature = "std")]
- use lightning::ln::PaymentPreimage;
+ use lightning::ln::types::PaymentPreimage;
use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId, RecipientOnionFields, Retry};
use lightning::ln::functional_test_utils::*;
use lightning::ln::msgs::ChannelMessageHandler;
use crate::blinded_path::BlindedHop;
use crate::blinded_path::utils;
use crate::io;
-use crate::ln::PaymentSecret;
+use crate::ln::types::PaymentSecret;
use crate::ln::channelmanager::CounterpartyForwardingInfo;
use crate::ln::features::BlindedHopFeatures;
use crate::ln::msgs::DecodeError;
mod tests {
use bitcoin::secp256k1::PublicKey;
use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentContext, PaymentRelay};
- use crate::ln::PaymentSecret;
+ use crate::ln::types::PaymentSecret;
use crate::ln::features::BlindedHopFeatures;
use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, WithChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
use crate::chain::transaction::{OutPoint, TransactionData};
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
use crate::events;
use crate::events::{Event, EventHandler};
use bitcoin::sighash::EcdsaSighashType;
use crate::ln::channel::INITIAL_COMMITMENT_NUMBER;
-use crate::ln::{PaymentHash, PaymentPreimage, ChannelId};
+use crate::ln::types::{PaymentHash, PaymentPreimage, ChannelId};
use crate::ln::msgs::DecodeError;
use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint};
use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys};
use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
use crate::chain::transaction::OutPoint;
use crate::sign::InMemorySigner;
- use crate::ln::{PaymentPreimage, PaymentHash, ChannelId};
+ use crate::ln::types::{PaymentPreimage, PaymentHash, ChannelId};
use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
use bitcoin::secp256k1::PublicKey;
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
use crate::chain::transaction::{OutPoint, TransactionData};
use crate::impl_writeable_tlv_based;
use crate::chain::chaininterface::compute_feerate_sat_per_1000_weight;
use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, ChannelSigner, EntropySource, SignerProvider, ecdsa::WriteableEcdsaChannelSigner};
use crate::ln::msgs::DecodeError;
-use crate::ln::PaymentPreimage;
+use crate::ln::types::PaymentPreimage;
use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction};
use crate::chain::ClaimId;
use crate::chain::chaininterface::{ConfirmationTarget, FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
use bitcoin::secp256k1::{SecretKey,PublicKey};
use bitcoin::sighash::EcdsaSighashType;
-use crate::ln::PaymentPreimage;
+use crate::ln::types::PaymentPreimage;
use crate::ln::chan_utils::{self, TxCreationKeys, HTLCOutputInCommitment};
use crate::ln::features::ChannelTypeFeatures;
use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint};
use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedOutput, WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc};
use crate::chain::Txid;
use crate::ln::chan_utils::HTLCOutputInCommitment;
- use crate::ln::{PaymentPreimage, PaymentHash};
+ use crate::ln::types::{PaymentPreimage, PaymentHash};
use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint};
use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
#[cfg(test)]
mod tests {
use crate::chain::transaction::OutPoint;
- use crate::ln::ChannelId;
+ use crate::ln::types::ChannelId;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::consensus::encode;
use crate::chain::ClaimId;
use crate::io_extras::sink;
use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::ln::chan_utils;
use crate::ln::chan_utils::{
ANCHOR_INPUT_WITNESS_WEIGHT, HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT,
use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
use crate::ln::features::ChannelTypeFeatures;
use crate::ln::msgs;
-use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::chain::transaction;
use crate::routing::gossip::NetworkUpdate;
use crate::util::errors::APIError;
use crate::blinded_path::BlindedPath;
use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentContext, PaymentRelay, ReceiveTlvs};
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PaymentFailureReason};
-use crate::ln::PaymentSecret;
+use crate::ln::types::PaymentSecret;
use crate::ln::channelmanager;
use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
use crate::ln::features::BlindedHopFeatures;
use crate::chain::chaininterface::fee_for_weight;
use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
use crate::sign::EntropySource;
-use crate::ln::{PaymentHash, PaymentPreimage};
+use crate::ln::types::{PaymentHash, PaymentPreimage};
use crate::ln::msgs::DecodeError;
use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
use crate::util::transaction_utils;
use bitcoin::{Network, Txid, ScriptBuf};
use bitcoin::hashes::Hash;
use bitcoin::hashes::hex::FromHex;
- use crate::ln::PaymentHash;
+ use crate::ln::types::PaymentHash;
use bitcoin::address::Payload;
use bitcoin::PublicKey as BitcoinPublicKey;
use crate::ln::features::ChannelTypeFeatures;
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
use crate::ln::channelmanager::{RAACommitmentOrder, PaymentSendFailure, PaymentId, RecipientOnionFields};
use crate::ln::channel::{AnnouncementSigsState, ChannelPhase};
-use crate::ln::{msgs, ChannelId};
+use crate::ln::msgs;
+use crate::ln::types::ChannelId;
use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use crate::util::test_channel_signer::TestChannelSigner;
use crate::util::errors::APIError;
use bitcoin::secp256k1::{Secp256k1,ecdsa::Signature};
use bitcoin::secp256k1;
-use crate::ln::{ChannelId, PaymentPreimage, PaymentHash};
+use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash};
use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
use crate::ln::msgs;
use crate::ln::msgs::DecodeError;
use bitcoin::blockdata::opcodes;
use bitcoin::network::constants::Network;
use crate::ln::onion_utils::INVALID_ONION_BLINDING;
- use crate::ln::{PaymentHash, PaymentPreimage};
+ use crate::ln::types::{PaymentHash, PaymentPreimage};
use crate::ln::channel_keys::{RevocationKey, RevocationBasepoint};
use crate::ln::channelmanager::{self, HTLCSource, PaymentId};
use crate::ln::channel::InitFeatures;
+++ /dev/null
-// This file is Copyright its original authors, visible in version control
-// history.
-//
-// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
-// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
-// You may not use this file except in accordance with one or both of these
-// licenses.
-
-//! ChannelId definition.
-
-use crate::chain::transaction::OutPoint;
-use crate::io;
-use crate::ln::msgs::DecodeError;
-use crate::sign::EntropySource;
-use crate::util::ser::{Readable, Writeable, Writer};
-use super::channel_keys::RevocationBasepoint;
-
-use bitcoin::hashes::{
- Hash as _,
- HashEngine as _,
- sha256::Hash as Sha256,
-};
-use core::fmt;
-use core::ops::Deref;
-
-/// A unique 32-byte identifier for a channel.
-/// Depending on how the ID is generated, several varieties are distinguished
-/// (but all are stored as 32 bytes):
-/// _v1_ and _temporary_.
-/// A _v1_ channel ID is generated based on funding tx outpoint (txid & index).
-/// A _temporary_ ID is generated randomly.
-/// (Later revocation-point-based _v2_ is a possibility.)
-/// The variety (context) is not stored, it is relevant only at creation.
-///
-/// This is not exported to bindings users as we just use [u8; 32] directly.
-#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
-pub struct ChannelId(pub [u8; 32]);
-
-impl ChannelId {
- /// Create _v1_ channel ID based on a funding TX ID and output index
- pub fn v1_from_funding_txid(txid: &[u8; 32], output_index: u16) -> Self {
- let mut res = [0; 32];
- res[..].copy_from_slice(&txid[..]);
- res[30] ^= ((output_index >> 8) & 0xff) as u8;
- res[31] ^= ((output_index >> 0) & 0xff) as u8;
- Self(res)
- }
-
- /// Create _v1_ channel ID from a funding tx outpoint
- pub fn v1_from_funding_outpoint(outpoint: OutPoint) -> Self {
- Self::v1_from_funding_txid(outpoint.txid.as_byte_array(), outpoint.index)
- }
-
- /// Create a _temporary_ channel ID randomly, based on an entropy source.
- pub fn temporary_from_entropy_source<ES: Deref>(entropy_source: &ES) -> Self
- where ES::Target: EntropySource {
- Self(entropy_source.get_secure_random_bytes())
- }
-
- /// Generic constructor; create a new channel ID from the provided data.
- /// Use a more specific `*_from_*` constructor when possible.
- pub fn from_bytes(data: [u8; 32]) -> Self {
- Self(data)
- }
-
- /// Create a channel ID consisting of all-zeros data (e.g. when uninitialized or a placeholder).
- pub fn new_zero() -> Self {
- Self([0; 32])
- }
-
- /// Check whether ID is consisting of all zeros (uninitialized)
- pub fn is_zero(&self) -> bool {
- self.0[..] == [0; 32]
- }
-
- /// Create _v2_ channel ID by concatenating the holder revocation basepoint with the counterparty
- /// revocation basepoint and hashing the result. The basepoints will be concatenated in increasing
- /// sorted order.
- pub fn v2_from_revocation_basepoints(
- ours: &RevocationBasepoint,
- theirs: &RevocationBasepoint,
- ) -> Self {
- let ours = ours.0.serialize();
- let theirs = theirs.0.serialize();
- let (lesser, greater) = if ours < theirs {
- (ours, theirs)
- } else {
- (theirs, ours)
- };
- let mut engine = Sha256::engine();
- engine.input(&lesser[..]);
- engine.input(&greater[..]);
- Self(Sha256::from_engine(engine).to_byte_array())
- }
-
- /// Create temporary _v2_ channel ID by concatenating a zeroed out basepoint with the holder
- /// revocation basepoint and hashing the result.
- pub fn temporary_v2_from_revocation_basepoint(our_revocation_basepoint: &RevocationBasepoint) -> Self {
- Self(Sha256::hash(&[[0u8; 33], our_revocation_basepoint.0.serialize()].concat()).to_byte_array())
- }
-}
-
-impl Writeable for ChannelId {
- fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
- self.0.write(w)
- }
-}
-
-impl Readable for ChannelId {
- fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
- let buf: [u8; 32] = Readable::read(r)?;
- Ok(ChannelId(buf))
- }
-}
-
-impl fmt::Display for ChannelId {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- crate::util::logger::DebugBytes(&self.0).fmt(f)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use bitcoin::hashes::{
- Hash as _,
- HashEngine as _,
- hex::FromHex as _,
- sha256::Hash as Sha256,
- };
- use bitcoin::secp256k1::PublicKey;
- use hex::DisplayHex;
-
- use crate::ln::ChannelId;
- use crate::ln::channel_keys::RevocationBasepoint;
- use crate::util::ser::{Readable, Writeable};
- use crate::util::test_utils;
- use crate::prelude::*;
- use crate::io;
-
- #[test]
- fn test_channel_id_v1_from_funding_txid() {
- let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
- assert_eq!(channel_id.0.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020203");
- }
-
- #[test]
- fn test_channel_id_new_from_data() {
- let data: [u8; 32] = [2; 32];
- let channel_id = ChannelId::from_bytes(data.clone());
- assert_eq!(channel_id.0, data);
- }
-
- #[test]
- fn test_channel_id_equals() {
- let channel_id11 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
- let channel_id12 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
- let channel_id21 = ChannelId::v1_from_funding_txid(&[2; 32], 42);
- assert_eq!(channel_id11, channel_id12);
- assert_ne!(channel_id11, channel_id21);
- }
-
- #[test]
- fn test_channel_id_write_read() {
- let data: [u8; 32] = [2; 32];
- let channel_id = ChannelId::from_bytes(data.clone());
-
- let mut w = test_utils::TestVecWriter(Vec::new());
- channel_id.write(&mut w).unwrap();
-
- let channel_id_2 = ChannelId::read(&mut io::Cursor::new(&w.0)).unwrap();
- assert_eq!(channel_id_2, channel_id);
- assert_eq!(channel_id_2.0, data);
- }
-
- #[test]
- fn test_channel_id_display() {
- let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
- assert_eq!(format!("{}", &channel_id), "0202020202020202020202020202020202020202020202020202020202020203");
- }
-
- #[test]
- fn test_channel_id_v2_from_basepoints() {
- // Ours greater than theirs
- let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap());
- let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
-
- let mut engine = Sha256::engine();
- engine.input(&theirs.0.serialize());
- engine.input(&ours.0.serialize());
- let expected_id = ChannelId(Sha256::from_engine(engine).to_byte_array());
-
- assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
-
- // Theirs greater than ours
- let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap());
- let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
-
- let mut engine = Sha256::engine();
- engine.input(&ours.0.serialize());
- engine.input(&theirs.0.serialize());
- let expected_id = ChannelId(Sha256::from_engine(engine).to_byte_array());
-
- assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
- }
-}
use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
// Since this struct is returned in `list_channels` methods, expose it here in case users want to
// construct one themselves.
-use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
+use crate::ln::inbound_payment;
+use crate::ln::types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channel::{self, Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext};
pub use crate::ln::channel::{InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails};
use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
///
/// ```
/// # use bitcoin::secp256k1::PublicKey;
-/// # use lightning::ln::ChannelId;
+/// # use lightning::ln::types::ChannelId;
/// # use lightning::ln::channelmanager::AChannelManager;
/// # use lightning::events::{Event, EventsProvider};
/// #
///
/// ```
/// # use lightning::events::{Event, EventsProvider};
-/// # use lightning::ln::PaymentHash;
+/// # use lightning::ln::types::PaymentHash;
/// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry};
/// # use lightning::routing::router::RouteParameters;
/// #
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use core::sync::atomic::Ordering;
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
- use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
- use crate::ln::ChannelId;
+ use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
use crate::ln::functional_test_utils::*;
use crate::ln::msgs::{self, ErrorAction};
use crate::chain::transaction::OutPoint;
use crate::events::{ClaimedHTLC, ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, PaymentFailureReason};
use crate::events::bump_transaction::{BumpTransactionEvent, BumpTransactionEventHandler, Wallet, WalletSource};
-use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channelmanager::{AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, PaymentId, MIN_CLTV_EXPIRY_DELTA};
use crate::ln::features::InitFeatures;
use crate::ln::msgs;
use crate::chain::transaction::OutPoint;
use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, OutputSpender, SignerProvider};
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
-use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
+use crate::ln::types::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
use bitcoin::hashes::hmac::{Hmac, HmacEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use crate::sign::{KeyMaterial, EntropySource};
-use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
+use crate::ln::types::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::crypto::chacha20::ChaCha20;
use crate::chain::chaininterface::fee_for_weight;
use crate::events::bump_transaction::{BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT};
use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
+use crate::ln::msgs;
use crate::ln::msgs::SerialId;
-use crate::ln::{msgs, ChannelId};
+use crate::ln::types::ChannelId;
use crate::sign::{EntropySource, P2TR_KEY_PATH_WITNESS_WEIGHT, P2WPKH_WITNESS_WEIGHT};
use crate::util::ser::TransactionU16LenLimited;
InteractiveTxMessageSend, MAX_INPUTS_OUTPUTS_COUNT, MAX_RECEIVED_TX_ADD_INPUT_COUNT,
MAX_RECEIVED_TX_ADD_OUTPUT_COUNT,
};
- use crate::ln::ChannelId;
+ use crate::ln::types::ChannelId;
use crate::sign::EntropySource;
use crate::util::atomic_counter::AtomicCounter;
use crate::util::ser::TransactionU16LenLimited;
pub mod chan_utils;
pub mod features;
pub mod script;
-mod channel_id;
+pub mod types;
+
+pub use types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
#[cfg(fuzzing)]
pub mod peer_channel_encryptor;
#[cfg(not(fuzzing))]
pub(crate) mod channel;
-// Re-export ChannelId
-pub use channel_id::ChannelId;
-
pub(crate) mod onion_utils;
mod outbound_payment;
pub mod wire;
pub(crate) mod interactivetxs;
pub use self::peer_channel_encryptor::LN_MAX_MSG_LEN;
-
-use bitcoin::hashes::{sha256::Hash as Sha256, Hash};
-
-/// payment_hash type, use to cross-lock hop
-///
-/// This is not exported to bindings users as we just use [u8; 32] directly
-#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
-pub struct PaymentHash(pub [u8; 32]);
-
-impl core::fmt::Display for PaymentHash {
- fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
- crate::util::logger::DebugBytes(&self.0).fmt(f)
- }
-}
-
-/// payment_preimage type, use to route payment between hop
-///
-/// This is not exported to bindings users as we just use [u8; 32] directly
-#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
-pub struct PaymentPreimage(pub [u8; 32]);
-
-impl core::fmt::Display for PaymentPreimage {
- fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
- crate::util::logger::DebugBytes(&self.0).fmt(f)
- }
-}
-
-/// Converts a `PaymentPreimage` into a `PaymentHash` by hashing the preimage with SHA256.
-impl From<PaymentPreimage> for PaymentHash {
- fn from(value: PaymentPreimage) -> Self {
- PaymentHash(Sha256::hash(&value.0).to_byte_array())
- }
-}
-
-/// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
-///
-/// This is not exported to bindings users as we just use [u8; 32] directly
-#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
-pub struct PaymentSecret(pub [u8; 32]);
-
-#[allow(unused_imports)]
-use crate::prelude::*;
-
-use bitcoin::bech32;
-use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, WriteBase32, u5};
-
-impl FromBase32 for PaymentSecret {
- type Err = bech32::Error;
-
- fn from_base32(field_data: &[u5]) -> Result<PaymentSecret, bech32::Error> {
- if field_data.len() != 52 {
- return Err(bech32::Error::InvalidLength)
- } else {
- let data_bytes = Vec::<u8>::from_base32(field_data)?;
- let mut payment_secret = [0; 32];
- payment_secret.copy_from_slice(&data_bytes);
- Ok(PaymentSecret(payment_secret))
- }
- }
-}
-
-impl ToBase32 for PaymentSecret {
- fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
- (&self.0[..]).write_base32(writer)
- }
-}
-
-impl Base32Len for PaymentSecret {
- fn base32_len(&self) -> usize {
- 52
- }
-}
use crate::chain::chaininterface::{LowerBoundedFeeEstimator, compute_feerate_sat_per_1000_weight};
use crate::events::bump_transaction::{BumpTransactionEvent, WalletSource};
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
-use crate::ln::{channel, ChannelId};
+use crate::ln::channel;
+use crate::ln::types::ChannelId;
use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, PaymentId, RecipientOnionFields};
use crate::ln::msgs::ChannelMessageHandler;
use crate::util::config::UserConfig;
use bitcoin::hash_types::Txid;
use crate::blinded_path::payment::{BlindedPaymentTlvs, ForwardTlvs, ReceiveTlvs};
-use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
use crate::ln::onion_utils;
use crate::onion_message;
mod fuzzy_internal_msgs {
use bitcoin::secp256k1::PublicKey;
use crate::blinded_path::payment::{PaymentConstraints, PaymentContext, PaymentRelay};
- use crate::ln::{PaymentPreimage, PaymentSecret};
+ use crate::ln::types::{PaymentPreimage, PaymentSecret};
use crate::ln::features::BlindedHopFeatures;
use super::{FinalOnionHopData, TrampolineOnionPacket};
mod tests {
use bitcoin::{Transaction, TxIn, ScriptBuf, Sequence, Witness, TxOut};
use hex::DisplayHex;
- use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
- use crate::ln::ChannelId;
+ use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
use crate::ln::msgs::{self, FinalOnionHopData, OnionErrorPacket, CommonOpenChannelFields, CommonAcceptChannelFields, TrampolineOnionPacket};
use crate::ln::msgs::SocketAddress;
use crate::blinded_path;
use crate::blinded_path::payment::{PaymentConstraints, PaymentRelay};
use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
-use crate::ln::PaymentHash;
+use crate::ln::types::PaymentHash;
use crate::ln::channelmanager::{BlindedFailure, BlindedForward, CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
use crate::ln::features::BlindedHopFeatures;
use crate::ln::msgs;
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
- use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
- use crate::ln::ChannelId;
+ use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channelmanager::RecipientOnionFields;
use crate::ln::features::{ChannelFeatures, NodeFeatures};
use crate::ln::msgs;
use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
use crate::sign::{EntropySource, NodeSigner, Recipient};
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
-use crate::ln::{PaymentHash, PaymentSecret};
+use crate::ln::types::{PaymentHash, PaymentSecret};
use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
use crate::ln::channelmanager::{HTLCForwardInfo, FailureCode, CLTV_FAR_FAR_AWAY, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA, PendingAddHTLCInfo, PendingHTLCInfo, PendingHTLCRouting, PaymentId, RecipientOnionFields};
use crate::ln::onion_utils;
use crate::crypto::streams::ChaChaReader;
use crate::ln::channelmanager::{HTLCSource, RecipientOnionFields};
use crate::ln::msgs;
+use crate::ln::types::{PaymentHash, PaymentPreimage};
use crate::ln::wire::Encode;
-use crate::ln::{PaymentHash, PaymentPreimage};
use crate::routing::gossip::NetworkUpdate;
use crate::routing::router::{BlindedTail, Path, RouteHop};
use crate::sign::NodeSigner;
use crate::io;
use crate::ln::features::{ChannelFeatures, NodeFeatures};
use crate::ln::msgs;
- use crate::ln::PaymentHash;
+ use crate::ln::types::PaymentHash;
use crate::routing::router::{Path, Route, RouteHop};
use crate::util::ser::{VecWriter, Writeable, Writer};
use crate::sign::{EntropySource, NodeSigner, Recipient};
use crate::events::{self, PaymentFailureReason};
-use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
+use crate::ln::types::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channelmanager::{ChannelDetails, EventCompletionAction, HTLCSource, PaymentId};
use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
use crate::offers::invoice::Bolt12Invoice;
use core::time::Duration;
use crate::events::{Event, PathFailure, PaymentFailureReason};
- use crate::ln::PaymentHash;
+ use crate::ln::types::PaymentHash;
use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
use crate::ln::features::{ChannelFeatures, NodeFeatures};
use crate::ln::msgs::{ErrorAction, LightningError};
use crate::ln::channel::{EXPIRE_PREV_CONFIG_TICKS, commit_tx_fee_msat, get_holder_selected_channel_reserve_satoshis, ANCHOR_OUTPUT_VALUE_SATOSHI};
use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
use crate::ln::features::{Bolt11InvoiceFeatures, ChannelTypeFeatures};
-use crate::ln::{msgs, ChannelId, PaymentHash, PaymentSecret, PaymentPreimage};
+use crate::ln::msgs;
+use crate::ln::types::{ChannelId, PaymentHash, PaymentSecret, PaymentPreimage};
use crate::ln::msgs::ChannelMessageHandler;
use crate::ln::onion_utils;
use crate::ln::outbound_payment::{IDEMPOTENCY_TIMEOUT_TICKS, Retry};
use crate::sign::{NodeSigner, Recipient};
use crate::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::ln::features::{InitFeatures, NodeFeatures};
use crate::ln::msgs;
use crate::ln::msgs::{ChannelMessageHandler, LightningError, SocketAddress, OnionMessageHandler, RoutingMessageHandler};
use crate::sign::{NodeSigner, Recipient};
use crate::events;
use crate::io;
- use crate::ln::ChannelId;
+ use crate::ln::types::ChannelId;
use crate::ln::features::{InitFeatures, NodeFeatures};
use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses, ErroringMessageHandler, MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER};
use crate::routing::gossip::RoutingFees;
use crate::routing::router::{PaymentParameters, RouteHint, RouteHintHop};
use crate::ln::features::ChannelTypeFeatures;
-use crate::ln::{msgs, ChannelId};
+use crate::ln::msgs;
+use crate::ln::types::ChannelId;
use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ChannelUpdate, ErrorAction};
use crate::ln::wire::Encode;
use crate::util::config::{UserConfig, MaxDustHTLCExposure};
use crate::chain::transaction::OutPoint;
use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
use crate::ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RecipientOnionFields};
-use crate::ln::{msgs, ChannelId};
+use crate::ln::msgs;
+use crate::ln::types::ChannelId;
use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
use crate::util::test_channel_signer::TestChannelSigner;
use crate::util::test_utils;
use crate::chain::Confirm;
use crate::events::{Event, MessageSendEventsProvider, ClosureReason, HTLCDestination, MessageSendEvent};
use crate::ln::msgs::{ChannelMessageHandler, Init};
+use crate::ln::types::ChannelId;
use crate::sign::OutputSpender;
use crate::util::test_utils;
use crate::util::ser::Writeable;
use crate::prelude::*;
-use crate::ln::{functional_test_utils::*, ChannelId};
+use crate::ln::functional_test_utils::*;
fn do_test_onchain_htlc_reorg(local_commitment: bool, claim: bool) {
// Our on-chain HTLC-claim learning has a few properties worth testing:
use crate::events::{Event, MessageSendEvent, HTLCDestination, MessageSendEventsProvider, ClosureReason};
use crate::ln::channelmanager::{self, PaymentSendFailure, PaymentId, RecipientOnionFields, Retry, ChannelShutdownState, ChannelDetails};
use crate::routing::router::{PaymentParameters, get_route, RouteParameters};
-use crate::ln::{ChannelId, msgs};
+use crate::ln::msgs;
+use crate::ln::types::ChannelId;
use crate::ln::msgs::{ChannelMessageHandler, ErrorAction};
use crate::ln::onion_utils::INVALID_ONION_BLINDING;
use crate::ln::script::ShutdownScript;
--- /dev/null
+// This file is Copyright its original authors, visible in version control
+// history.
+//
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
+// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
+// You may not use this file except in accordance with one or both of these
+// licenses.
+
+//! Various wrapper types (most around 32-byte arrays) for use in lightning.
+
+use crate::chain::transaction::OutPoint;
+use crate::io;
+use crate::ln::msgs::DecodeError;
+use crate::sign::EntropySource;
+use crate::util::ser::{Readable, Writeable, Writer};
+use super::channel_keys::RevocationBasepoint;
+
+#[allow(unused_imports)]
+use crate::prelude::*;
+
+use bitcoin::hashes::{
+ Hash as _,
+ HashEngine as _,
+ sha256::Hash as Sha256,
+};
+use core::fmt;
+use core::ops::Deref;
+
+/// A unique 32-byte identifier for a channel.
+/// Depending on how the ID is generated, several varieties are distinguished
+/// (but all are stored as 32 bytes):
+/// _v1_ and _temporary_.
+/// A _v1_ channel ID is generated based on funding tx outpoint (txid & index).
+/// A _temporary_ ID is generated randomly.
+/// (Later revocation-point-based _v2_ is a possibility.)
+/// The variety (context) is not stored, it is relevant only at creation.
+///
+/// This is not exported to bindings users as we just use [u8; 32] directly.
+#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
+pub struct ChannelId(pub [u8; 32]);
+
+impl ChannelId {
+ /// Create _v1_ channel ID based on a funding TX ID and output index
+ pub fn v1_from_funding_txid(txid: &[u8; 32], output_index: u16) -> Self {
+ let mut res = [0; 32];
+ res[..].copy_from_slice(&txid[..]);
+ res[30] ^= ((output_index >> 8) & 0xff) as u8;
+ res[31] ^= ((output_index >> 0) & 0xff) as u8;
+ Self(res)
+ }
+
+ /// Create _v1_ channel ID from a funding tx outpoint
+ pub fn v1_from_funding_outpoint(outpoint: OutPoint) -> Self {
+ Self::v1_from_funding_txid(outpoint.txid.as_byte_array(), outpoint.index)
+ }
+
+ /// Create a _temporary_ channel ID randomly, based on an entropy source.
+ pub fn temporary_from_entropy_source<ES: Deref>(entropy_source: &ES) -> Self
+ where ES::Target: EntropySource {
+ Self(entropy_source.get_secure_random_bytes())
+ }
+
+ /// Generic constructor; create a new channel ID from the provided data.
+ /// Use a more specific `*_from_*` constructor when possible.
+ pub fn from_bytes(data: [u8; 32]) -> Self {
+ Self(data)
+ }
+
+ /// Create a channel ID consisting of all-zeros data (e.g. when uninitialized or a placeholder).
+ pub fn new_zero() -> Self {
+ Self([0; 32])
+ }
+
+ /// Check whether ID is consisting of all zeros (uninitialized)
+ pub fn is_zero(&self) -> bool {
+ self.0[..] == [0; 32]
+ }
+
+ /// Create _v2_ channel ID by concatenating the holder revocation basepoint with the counterparty
+ /// revocation basepoint and hashing the result. The basepoints will be concatenated in increasing
+ /// sorted order.
+ pub fn v2_from_revocation_basepoints(
+ ours: &RevocationBasepoint,
+ theirs: &RevocationBasepoint,
+ ) -> Self {
+ let ours = ours.0.serialize();
+ let theirs = theirs.0.serialize();
+ let (lesser, greater) = if ours < theirs {
+ (ours, theirs)
+ } else {
+ (theirs, ours)
+ };
+ let mut engine = Sha256::engine();
+ engine.input(&lesser[..]);
+ engine.input(&greater[..]);
+ Self(Sha256::from_engine(engine).to_byte_array())
+ }
+
+ /// Create temporary _v2_ channel ID by concatenating a zeroed out basepoint with the holder
+ /// revocation basepoint and hashing the result.
+ pub fn temporary_v2_from_revocation_basepoint(our_revocation_basepoint: &RevocationBasepoint) -> Self {
+ Self(Sha256::hash(&[[0u8; 33], our_revocation_basepoint.0.serialize()].concat()).to_byte_array())
+ }
+}
+
+impl Writeable for ChannelId {
+ fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+ self.0.write(w)
+ }
+}
+
+impl Readable for ChannelId {
+ fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
+ let buf: [u8; 32] = Readable::read(r)?;
+ Ok(ChannelId(buf))
+ }
+}
+
+impl fmt::Display for ChannelId {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ crate::util::logger::DebugBytes(&self.0).fmt(f)
+ }
+}
+
+
+/// payment_hash type, use to cross-lock hop
+///
+/// This is not exported to bindings users as we just use [u8; 32] directly
+#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
+pub struct PaymentHash(pub [u8; 32]);
+
+impl core::fmt::Display for PaymentHash {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ crate::util::logger::DebugBytes(&self.0).fmt(f)
+ }
+}
+
+/// payment_preimage type, use to route payment between hop
+///
+/// This is not exported to bindings users as we just use [u8; 32] directly
+#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
+pub struct PaymentPreimage(pub [u8; 32]);
+
+impl core::fmt::Display for PaymentPreimage {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ crate::util::logger::DebugBytes(&self.0).fmt(f)
+ }
+}
+
+/// Converts a `PaymentPreimage` into a `PaymentHash` by hashing the preimage with SHA256.
+impl From<PaymentPreimage> for PaymentHash {
+ fn from(value: PaymentPreimage) -> Self {
+ PaymentHash(Sha256::hash(&value.0).to_byte_array())
+ }
+}
+
+/// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
+///
+/// This is not exported to bindings users as we just use [u8; 32] directly
+#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug, Ord, PartialOrd)]
+pub struct PaymentSecret(pub [u8; 32]);
+
+use bitcoin::bech32;
+use bitcoin::bech32::{Base32Len, FromBase32, ToBase32, WriteBase32, u5};
+
+impl FromBase32 for PaymentSecret {
+ type Err = bech32::Error;
+
+ fn from_base32(field_data: &[u5]) -> Result<PaymentSecret, bech32::Error> {
+ if field_data.len() != 52 {
+ return Err(bech32::Error::InvalidLength)
+ } else {
+ let data_bytes = Vec::<u8>::from_base32(field_data)?;
+ let mut payment_secret = [0; 32];
+ payment_secret.copy_from_slice(&data_bytes);
+ Ok(PaymentSecret(payment_secret))
+ }
+ }
+}
+
+impl ToBase32 for PaymentSecret {
+ fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
+ (&self.0[..]).write_base32(writer)
+ }
+}
+
+impl Base32Len for PaymentSecret {
+ fn base32_len(&self) -> usize {
+ 52
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use bitcoin::hashes::{
+ Hash as _,
+ HashEngine as _,
+ hex::FromHex as _,
+ sha256::Hash as Sha256,
+ };
+ use bitcoin::secp256k1::PublicKey;
+ use hex::DisplayHex;
+
+ use super::ChannelId;
+ use crate::ln::channel_keys::RevocationBasepoint;
+ use crate::util::ser::{Readable, Writeable};
+ use crate::util::test_utils;
+ use crate::prelude::*;
+ use crate::io;
+
+ #[test]
+ fn test_channel_id_v1_from_funding_txid() {
+ let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
+ assert_eq!(channel_id.0.as_hex().to_string(), "0202020202020202020202020202020202020202020202020202020202020203");
+ }
+
+ #[test]
+ fn test_channel_id_new_from_data() {
+ let data: [u8; 32] = [2; 32];
+ let channel_id = ChannelId::from_bytes(data.clone());
+ assert_eq!(channel_id.0, data);
+ }
+
+ #[test]
+ fn test_channel_id_equals() {
+ let channel_id11 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
+ let channel_id12 = ChannelId::v1_from_funding_txid(&[2; 32], 2);
+ let channel_id21 = ChannelId::v1_from_funding_txid(&[2; 32], 42);
+ assert_eq!(channel_id11, channel_id12);
+ assert_ne!(channel_id11, channel_id21);
+ }
+
+ #[test]
+ fn test_channel_id_write_read() {
+ let data: [u8; 32] = [2; 32];
+ let channel_id = ChannelId::from_bytes(data.clone());
+
+ let mut w = test_utils::TestVecWriter(Vec::new());
+ channel_id.write(&mut w).unwrap();
+
+ let channel_id_2 = ChannelId::read(&mut io::Cursor::new(&w.0)).unwrap();
+ assert_eq!(channel_id_2, channel_id);
+ assert_eq!(channel_id_2.0, data);
+ }
+
+ #[test]
+ fn test_channel_id_display() {
+ let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
+ assert_eq!(format!("{}", &channel_id), "0202020202020202020202020202020202020202020202020202020202020203");
+ }
+
+ #[test]
+ fn test_channel_id_v2_from_basepoints() {
+ // Ours greater than theirs
+ let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap());
+ let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
+
+ let mut engine = Sha256::engine();
+ engine.input(&theirs.0.serialize());
+ engine.input(&ours.0.serialize());
+ let expected_id = ChannelId(Sha256::from_engine(engine).to_byte_array());
+
+ assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
+
+ // Theirs greater than ours
+ let ours = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap());
+ let theirs = RevocationBasepoint(PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap());
+
+ let mut engine = Sha256::engine();
+ engine.input(&ours.0.serialize());
+ engine.input(&theirs.0.serialize());
+ let expected_id = ChannelId(Sha256::from_engine(engine).to_byte_array());
+
+ assert_eq!(ChannelId::v2_from_revocation_basepoints(&ours, &theirs), expected_id);
+ }
+}
//! use lightning::offers::refund::Refund;
//! use lightning::util::ser::Writeable;
//!
-//! # use lightning::ln::PaymentHash;
+//! # use lightning::ln::types::PaymentHash;
//! # use lightning::offers::invoice::{BlindedPayInfo, ExplicitSigningPubkey, InvoiceBuilder};
//! # use lightning::blinded_path::BlindedPath;
//! #
use core::hash::{Hash, Hasher};
use crate::io;
use crate::blinded_path::BlindedPath;
-use crate::ln::PaymentHash;
+use crate::ln::types::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::sign::EntropySource;
use crate::io;
use crate::blinded_path::BlindedPath;
-use crate::ln::PaymentHash;
+use crate::ln::types::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::InvoiceRequestFeatures;
use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
use crate::sign::EntropySource;
use crate::io;
use crate::blinded_path::BlindedPath;
-use crate::ln::PaymentHash;
+use crate::ln::types::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::InvoiceRequestFeatures;
use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
use core::time::Duration;
use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
use crate::sign::EntropySource;
-use crate::ln::PaymentHash;
+use crate::ln::types::PaymentHash;
use crate::ln::features::BlindedHopFeatures;
use crate::offers::invoice::BlindedPayInfo;
use crate::offers::merkle::TaggedHash;
use bitcoin::network::constants::Network;
use crate::events::{MessageSendEvent, MessageSendEventsProvider};
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
use crate::ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, SocketAddress, MAX_VALUE_MSAT};
use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode};
use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
-use crate::ln::PaymentHash;
+use crate::ln::types::PaymentHash;
use crate::ln::channelmanager::{ChannelDetails, PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA};
use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
use crate::chain::transaction::OutPoint;
use crate::sign::EntropySource;
- use crate::ln::ChannelId;
+ use crate::ln::types::ChannelId;
use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
use crate::ln::channelmanager;
use crate::chain::transaction::OutPoint;
use crate::routing::scoring::ScoreUpdate;
use crate::sign::KeysManager;
- use crate::ln::ChannelId;
+ use crate::ln::types::ChannelId;
use crate::ln::channelmanager::{self, ChannelCounterparty};
use crate::util::config::UserConfig;
use crate::util::test_utils::TestLogger;
ClosingTransaction, CommitmentTransaction, HTLCOutputInCommitment, HolderCommitmentTransaction,
};
use crate::ln::msgs::UnsignedChannelAnnouncement;
-use crate::ln::PaymentPreimage;
+use crate::ln::types::PaymentPreimage;
use crate::util::ser::Writeable;
#[allow(unused_imports)]
use crate::chain::transaction::OutPoint;
use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
+use crate::ln::chan_utils;
use crate::ln::chan_utils::{
get_revokeable_redeemscript, make_funding_redeemscript, ChannelPublicKeys,
ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
use crate::ln::msgs::PartialSignatureWithNonce;
use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
use crate::ln::script::ShutdownScript;
-use crate::ln::{chan_utils, PaymentPreimage};
+use crate::ln::types::PaymentPreimage;
use crate::offers::invoice::UnsignedBolt12Invoice;
use crate::offers::invoice_request::UnsignedInvoiceRequest;
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use core::fmt;
use core::ops::Deref;
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
#[cfg(c_bindings)]
use crate::prelude::*; // Needed for String
#[cfg(test)]
mod tests {
use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
- use crate::ln::ChannelId;
+ use crate::ln::types::ChannelId;
use crate::util::logger::{Logger, Level, WithContext};
use crate::util::test_utils::TestLogger;
use crate::sync::Arc;
// You may not use this file except in accordance with one or both of these
// licenses.
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::sign::SpendableOutputDescriptor;
use bitcoin::blockdata::transaction::Transaction;
use crate::ln::msgs::DecodeError;
#[cfg(taproot)]
use crate::ln::msgs::PartialSignatureWithNonce;
-use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
+use crate::ln::types::{PaymentPreimage, PaymentHash, PaymentSecret};
use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::chain::{self, BestBlock, Confirm, Filter, Listen, WatchedOutput};
use crate::io;
use crate::ln::msgs::DecodeError;
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::prelude::Vec;
use crate::sign::{ChangeDestinationSource, OutputSpender, SpendableOutputDescriptor};
use crate::sync::Mutex;
use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, MIN_CHAN_DUST_LIMIT_SATOSHIS};
use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction, ClosingTransaction};
use crate::ln::channel_keys::{HtlcKey};
-use crate::ln::{msgs, PaymentPreimage};
+use crate::ln::msgs;
+use crate::ln::types::PaymentPreimage;
use crate::sign::{InMemorySigner, ChannelSigner};
use crate::sign::ecdsa::{EcdsaChannelSigner, WriteableEcdsaChannelSigner};
use crate::sign;
use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
-use crate::ln::ChannelId;
+use crate::ln::types::ChannelId;
use crate::ln::channelmanager::{ChannelDetails, self};
#[cfg(test)]
use crate::ln::chan_utils::CommitmentTransaction;
./lightning/src/ln/reorg_tests.rs
./lightning/src/ln/script.rs
./lightning/src/ln/shutdown_tests.rs
+./lightning/src/ln/types.rs
./lightning/src/ln/wire.rs
./lightning/src/offers/invoice.rs
./lightning/src/offers/invoice_error.rs