Skip to content

Commit

Permalink
Move ChannelId to its own module
Browse files Browse the repository at this point in the history
  • Loading branch information
optout21 committed Aug 24, 2023
2 parents 7ec2b2e + 3c96ee3 commit 5a68b9a
Show file tree
Hide file tree
Showing 16 changed files with 168 additions and 101 deletions.
3 changes: 1 addition & 2 deletions fuzz/src/full_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ use lightning::chain::chainmonitor;
use lightning::chain::transaction::OutPoint;
use lightning::sign::{InMemorySigner, Recipient, KeyMaterial, EntropySource, NodeSigner, SignerProvider};
use lightning::events::Event;
use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::ln::channel::ChannelId;
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::ln::channelmanager::{ChainParameters, ChannelDetails, ChannelManager, PaymentId, RecipientOnionFields, Retry};
use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor,IgnoringMessageHandler};
use lightning::ln::msgs::{self, DecodeError};
Expand Down
2 changes: 1 addition & 1 deletion fuzz/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use bitcoin::hash_types::BlockHash;

use lightning::blinded_path::{BlindedHop, BlindedPath};
use lightning::chain::transaction::OutPoint;
use lightning::ln::channel::ChannelId;
use lightning::ln::ChannelId;
use lightning::ln::channelmanager::{self, ChannelDetails, ChannelCounterparty};
use lightning::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
use lightning::ln::msgs;
Expand Down
2 changes: 1 addition & 1 deletion lightning/src/chain/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

//! Types describing on-chain transactions.

use crate::ln::channel::ChannelId;
use crate::ln::ChannelId;
use bitcoin::hash_types::Txid;
use bitcoin::hashes::Hash;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ pub use bump_transaction::BumpTransactionEvent;

use crate::sign::SpendableOutputDescriptor;
use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
use crate::ln::channel::{ChannelId, FUNDING_CONF_DEADLINE_BLOCKS};
use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
use crate::ln::features::ChannelTypeFeatures;
use crate::ln::msgs;
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::routing::gossip::NetworkUpdate;
use crate::util::errors::APIError;
use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
Expand Down
74 changes: 1 addition & 73 deletions lightning/src/ln/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use bitcoin::secp256k1::{PublicKey,SecretKey};
use bitcoin::secp256k1::{Secp256k1,ecdsa::Signature};
use bitcoin::secp256k1;

use crate::ln::{PaymentPreimage, PaymentHash};
use crate::ln::{ChannelId, PaymentPreimage, PaymentHash};
use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
use crate::ln::msgs;
use crate::ln::msgs::DecodeError;
Expand Down Expand Up @@ -602,78 +602,6 @@ impl_writeable_tlv_based!(PendingChannelMonitorUpdate, {
(0, update, required),
});

/// 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: generated based on funding tx outpoint (txid&index)
/// - temporary: generated randomly
/// (later planned v2: based on revocation point)
/// 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 {
// The 32-byte data of the ID
data: [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::from_bytes(res)
}

/// 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::from_bytes(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.
/// This constructor is useful for tests, and internally, e.g. when the channel ID is being deserialized.
pub fn from_bytes(data: [u8; 32]) -> Self {
Self{data}
}

/// Create a channel ID consisting of all-zeros data (placeholder).
pub fn new_zero() -> Self {
Self::from_bytes([0; 32])
}

/// Accessor for the channel ID data
pub fn bytes(&self) -> &[u8; 32] {
&self.data
}
}

impl Writeable for ChannelId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.data.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::from_bytes(buf))
}
}

impl ToHex for ChannelId {
fn to_hex(&self) -> String {
self.data.to_hex()
}
}

impl fmt::Display for ChannelId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
crate::util::logger::DebugBytes(&self.data).fmt(f)
}
}

/// Contains all state common to unfunded inbound/outbound channels.
pub(super) struct UnfundedChannelContext {
/// A counter tracking how many ticks have elapsed since this unfunded channel was
Expand Down
143 changes: 143 additions & 0 deletions lightning/src/ln/channel_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// 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.

use crate::ln::msgs::DecodeError;
use crate::sign::EntropySource;
use crate::util::ser::{Readable, Writeable, Writer};

use bitcoin::hashes::hex::ToHex;

use crate::io;
use crate::prelude::*;
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: generated based on funding tx outpoint (txid&index)
/// - temporary: generated randomly
/// (later planned v2: based on revocation point)
/// 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 {
// The 32-byte data of the ID
data: [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::from_bytes(res)
}

/// 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::from_bytes(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.
/// This constructor is useful for tests, and internally, e.g. when the channel ID is being deserialized.
pub fn from_bytes(data: [u8; 32]) -> Self {
Self{data}
}

/// Create a channel ID consisting of all-zeros data (placeholder).
pub fn new_zero() -> Self {
Self::from_bytes([0; 32])
}

/// Accessor for the channel ID data
pub fn bytes(&self) -> &[u8; 32] {
&self.data
}
}

impl Writeable for ChannelId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.data.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::from_bytes(buf))
}
}

impl ToHex for ChannelId {
fn to_hex(&self) -> String {
self.data.to_hex()
}
}

impl fmt::Display for ChannelId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
crate::util::logger::DebugBytes(&self.data).fmt(f)
}
}

#[cfg(test)]
mod tests {
use crate::ln::ChannelId;
use crate::util::ser::{Readable, Writeable};
use crate::util::test_utils;
use bitcoin::hashes::hex::ToHex;
use crate::prelude::*;
use crate::io;

#[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.bytes(), data);
}

#[test]
fn test_channel_id_v1_from_funding_txid() {
let channel_id = ChannelId::v1_from_funding_txid(&[2; 32], 1);
assert_eq!(channel_id.to_hex(), "0202020202020202020202020202020202020202020202020202020202020203");
}

#[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.bytes(), &data);
}

#[test]
fn test_channel_id_display() {
let channel_id = ChannelId::from_bytes([42; 32]);
assert_eq!(format!("{}", &channel_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
}
}
6 changes: 3 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ use crate::events;
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, PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channel::{Channel, ChannelContext, ChannelError, ChannelId, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channel::{Channel, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
#[cfg(any(feature = "_test_utils", test))]
use crate::ln::features::Bolt11InvoiceFeatures;
Expand Down Expand Up @@ -9408,7 +9408,7 @@ mod tests {
use core::sync::atomic::Ordering;
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channel::ChannelId;
use crate::ln::ChannelId;
use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
use crate::ln::functional_test_utils::*;
use crate::ln::msgs::{self, ErrorAction};
Expand Down
3 changes: 1 addition & 2 deletions lightning/src/ln/functional_test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ use crate::chain::channelmonitor::ChannelMonitor;
use crate::chain::transaction::OutPoint;
use crate::events::{ClaimedHTLC, ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, PaymentFailureReason};
use crate::events::bump_transaction::{BumpTransactionEventHandler, Wallet, WalletSource};
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channel::ChannelId;
use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channelmanager::{self, AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, PaymentId, MIN_CLTV_EXPIRY_DELTA};
use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
use crate::routing::router::{self, PaymentParameters, Route};
Expand Down
3 changes: 1 addition & 2 deletions lightning/src/ln/functional_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCK
use crate::chain::transaction::OutPoint;
use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource, SignerProvider};
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
use crate::ln::channel::ChannelId;
use crate::ln::{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};
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};
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#[macro_use]
pub mod functional_test_utils;

pub mod channel_id;
pub mod channelmanager;
pub mod inbound_payment;
pub mod msgs;
Expand All @@ -31,6 +32,9 @@ pub mod channel;
#[cfg(not(fuzzing))]
pub(crate) mod channel;

// Re-export ChannelId
pub use self::channel_id::ChannelId;

pub(crate) mod onion_utils;
mod outbound_payment;
pub mod wire;
Expand Down Expand Up @@ -67,9 +71,6 @@ mod monitor_tests;
#[allow(unused_mut)]
mod shutdown_tests;

// Re-export ChannelId
pub use self::channel::ChannelId;

pub use self::peer_channel_encryptor::LN_MAX_MSG_LEN;

/// payment_hash type, use to cross-lock hop
Expand Down
6 changes: 2 additions & 4 deletions lightning/src/ln/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use bitcoin::{secp256k1, Witness};
use bitcoin::blockdata::script::Script;
use bitcoin::hash_types::{Txid, BlockHash};

use crate::ln::channel::ChannelId;
use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
use crate::ln::onion_utils;
use crate::onion_message;
Expand All @@ -46,8 +46,6 @@ use crate::events::{MessageSendEventsProvider, OnionMessageProvider};
use crate::util::logger;
use crate::util::ser::{LengthReadable, Readable, ReadableArgs, Writeable, Writer, WithoutLength, FixedLengthReader, HighZeroBytesDroppedBigSize, Hostname, TransactionU16LenLimited, BigSize};

use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::routing::gossip::{NodeAlias, NodeId};

/// 21 million * 10^8 * 1000
Expand Down Expand Up @@ -2477,7 +2475,7 @@ mod tests {
use bitcoin::{Transaction, PackedLockTime, TxIn, Script, Sequence, Witness, TxOut};
use hex;
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
use crate::ln::channel::ChannelId;
use crate::ln::ChannelId;
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
use crate::ln::msgs::{self, FinalOnionHopData, OnionErrorPacket};
use crate::routing::gossip::{NodeAlias, NodeId};
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/ln/payment_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATE
use crate::sign::EntropySource;
use crate::chain::transaction::OutPoint;
use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason, PaymentPurpose};
use crate::ln::channel::{ChannelId, EXPIRE_PREV_CONFIG_TICKS};
use crate::ln::channel::{EXPIRE_PREV_CONFIG_TICKS};
use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
use crate::ln::features::Bolt11InvoiceFeatures;
use crate::ln::{msgs, PaymentSecret, PaymentPreimage};
use crate::ln::{msgs, ChannelId, PaymentSecret, PaymentPreimage};
use crate::ln::msgs::ChannelMessageHandler;
use crate::ln::outbound_payment::Retry;
use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/ln/peer_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};

use crate::sign::{KeysManager, NodeSigner, Recipient};
use crate::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
use crate::ln::channel::ChannelId;
use crate::ln::ChannelId;
use crate::ln::features::{InitFeatures, NodeFeatures};
use crate::ln::msgs;
use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
Expand Down Expand Up @@ -2483,7 +2483,7 @@ mod tests {
use crate::sign::{NodeSigner, Recipient};
use crate::events;
use crate::io;
use crate::ln::channel::ChannelId;
use crate::ln::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};
Expand Down
Loading

0 comments on commit 5a68b9a

Please sign in to comment.