Skip to content

Commit

Permalink
chore: rename const
Browse files Browse the repository at this point in the history
  • Loading branch information
quake committed Nov 24, 2024
1 parent b616006 commit afe2219
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 52 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
tests/nodes/.ports
/coverage-report
/*.info
.vscode
25 changes: 11 additions & 14 deletions src/fiber/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1669,7 +1669,7 @@ where
commitment_fee_rate.unwrap_or(DEFAULT_COMMITMENT_FEE_RATE);
let funding_fee_rate = funding_fee_rate.unwrap_or(DEFAULT_FEE_RATE);

let (funding_amount, reserved_ckb_amount) = get_funding_and_reserved_amount(
let (to_local_amount, reserved_ckb_amount) = get_funding_and_reserved_amount(
funding_amount,
&shutdown_script,
&funding_udt_type_script,
Expand All @@ -1680,7 +1680,7 @@ where
&seed,
self.get_local_pubkey(),
self.get_remote_pubkey(),
funding_amount,
to_local_amount,
reserved_ckb_amount,
commitment_fee_rate,
commitment_delay_epoch
Expand Down Expand Up @@ -2337,31 +2337,28 @@ pub fn get_commitment_point(commitment_seed: &[u8; 32], commitment_number: u64)
}

pub(crate) fn get_funding_and_reserved_amount(
funding_amount: u128,
total_amount: u128,
shutdown_script: &Script,
udt_type_script: &Option<Script>,
) -> Result<(u128, u64), ProcessingChannelError> {
let reserved_capacity = reserved_capacity(shutdown_script, udt_type_script)?.as_u64();
if udt_type_script.is_none() {
if funding_amount < reserved_capacity as u128 {
if total_amount < reserved_capacity as u128 {
return Err(ProcessingChannelError::InvalidParameter(format!(
"The funding amount ({}) should be greater than or equal to {}",
funding_amount, reserved_capacity
total_amount, reserved_capacity
)));
}
if funding_amount >= u64::MAX as u128 {
if total_amount >= u64::MAX as u128 {
return Err(ProcessingChannelError::InvalidParameter(format!(
"The funding amount ({}) should be less than {}",
funding_amount,
total_amount,
u64::MAX
)));
}
Ok((
funding_amount - reserved_capacity as u128,
reserved_capacity,
))
Ok((total_amount - reserved_capacity as u128, reserved_capacity))
} else {
Ok((funding_amount, reserved_capacity))
Ok((total_amount, reserved_capacity))
}
}

Expand Down Expand Up @@ -2799,7 +2796,7 @@ impl ChannelActorState {
seed: &[u8],
local_pubkey: Pubkey,
remote_pubkey: Pubkey,
value: u128,
to_local_amount: u128,
local_reserved_ckb_amount: u64,
commitment_fee_rate: u64,
commitment_delay_epoch: u64,
Expand All @@ -2821,7 +2818,7 @@ impl ChannelActorState {
funding_tx_confirmed_at: None,
funding_udt_type_script,
is_acceptor: false,
to_local_amount: value,
to_local_amount,
to_remote_amount: 0,
commitment_fee_rate,
commitment_delay_epoch,
Expand Down
25 changes: 10 additions & 15 deletions src/fiber/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,19 @@ use std::{fs, path::PathBuf, str::FromStr};
use tentacle::secio::{PublicKey, SecioKeyPair};

pub const CKB_SHANNONS: u64 = 100_000_000; // 1 CKB = 10 ^ 8 shannons
pub const DEFAULT_MIN_INBOUND_LIQUIDITY: u64 = 100 * CKB_SHANNONS; // 100 CKB for minimal inbound liquidity
pub const DEFAULT_MIN_SHUTDOWN_FEE: u64 = 1 * CKB_SHANNONS; // 1 CKB prepared for shutdown transaction fee
pub const MIN_OCCUPIED_CAPACITY: u64 = 61 * CKB_SHANNONS; // 61 CKB for occupied capacity

/// By default, listen to any tcp port allocated by the kernel.
pub const DEFAULT_LISTENING_ADDR: &str = "/ip4/0.0.0.0/tcp/0";

/// 62 CKB minimal channel amount, at any time a partner should keep at least
/// `DEFAULT_CHANNEL_MINIMAL_CKB_AMOUNT` CKB in the channel,
/// to make sure he can build a valid shutdown transaction and pay proper fee.
pub const DEFAULT_CHANNEL_MINIMAL_CKB_AMOUNT: u64 =
const MIN_OCCUPIED_CAPACITY: u64 = 61 * CKB_SHANNONS; // 61 CKB for occupied capacity

/// Default ckb funding amount when auto accepting an open channel request.
pub const DEFAULT_AUTO_ACCEPT_CHANNEL_CKB_FUNDING_AMOUNT: u64 =
MIN_OCCUPIED_CAPACITY + DEFAULT_MIN_SHUTDOWN_FEE;

/// 162 CKB to open a channel which maybe automatically acceptted.
/// 100 CKB for minimal inbound liquidity, 61 CKB for occupied capacity, 1 CKB for shutdown fee
/// The other party may auto accept the channel if the amount is greater than this.
pub const DEFAULT_CHANNEL_MIN_AUTO_CKB_AMOUNT: u64 =
DEFAULT_MIN_INBOUND_LIQUIDITY + MIN_OCCUPIED_CAPACITY + DEFAULT_MIN_SHUTDOWN_FEE;
/// Default minimum ckb funding amount for auto accepting an open channel request.
pub const DEFAULT_OPEN_CHANNEL_AUTO_ACCEPT_MIN_CKB_FUNDING_AMOUNT: u64 = 100 * CKB_SHANNONS;

/// The expiry delta to forward a tlc, in milliseconds, default to 1 day.
pub const DEFAULT_TLC_EXPIRY_DELTA: u64 = 24 * 60 * 60 * 1000;
Expand Down Expand Up @@ -108,12 +103,12 @@ pub struct FiberConfig {
#[arg(name = "FIBER_SCRIPTS", long = "fiber-scripts", env, value_parser, num_args = 0.., value_delimiter = ',')]
pub scripts: Vec<FiberScript>,

/// minimum ckb funding amount for auto accepting an open channel requests, aunit: shannons [default: 16200000000 shannons]
/// minimum ckb funding amount for auto accepting an open channel requests, aunit: shannons [default: 10000000000 shannons]
#[arg(
name = "FIBER_OPEN_CHANNEL_AUTO_ACCEPT_MIN_CKB_FUNDING_AMOUNT",
long = "fiber-open-channel-auto-accept-min-ckb-funding-amount",
env,
help = "minimum ckb funding amount for auto accepting an open channel requests, unit: shannons [default: 16200000000 shannons]"
help = "minimum ckb funding amount for auto accepting an open channel requests, unit: shannons [default: 10000000000 shannons]"
)]
pub open_channel_auto_accept_min_ckb_funding_amount: Option<u64>,
/// whether to accept open channel requests with ckb funding amount automatically, unit: shannons [default: 6200000000 shannons], if this is set to zero, it means to disable auto accept
Expand Down Expand Up @@ -313,12 +308,12 @@ impl FiberConfig {

pub fn open_channel_auto_accept_min_ckb_funding_amount(&self) -> u64 {
self.open_channel_auto_accept_min_ckb_funding_amount
.unwrap_or(DEFAULT_CHANNEL_MIN_AUTO_CKB_AMOUNT)
.unwrap_or(DEFAULT_OPEN_CHANNEL_AUTO_ACCEPT_MIN_CKB_FUNDING_AMOUNT)
}

pub fn auto_accept_channel_ckb_funding_amount(&self) -> u64 {
self.auto_accept_channel_ckb_funding_amount
.unwrap_or(DEFAULT_CHANNEL_MINIMAL_CKB_AMOUNT)
.unwrap_or(DEFAULT_AUTO_ACCEPT_CHANNEL_CKB_FUNDING_AMOUNT)
}

pub fn tlc_expiry_delta(&self) -> u64 {
Expand Down
10 changes: 2 additions & 8 deletions src/fiber/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -665,8 +665,8 @@ where
is_udt_type_auto_accept(udt_type_script, open_channel.funding_amount)
} else {
state.auto_accept_channel_ckb_funding_amount > 0
&& open_channel.all_ckb_amount()
>= state.open_channel_auto_accept_min_ckb_funding_amount
&& open_channel.funding_amount
>= state.open_channel_auto_accept_min_ckb_funding_amount as u128
};
if auto_accept {
let accept_channel = AcceptChannelCommand {
Expand Down Expand Up @@ -3000,12 +3000,6 @@ where
}
let shutdown_script =
shutdown_script.unwrap_or_else(|| self.default_shutdown_script.clone());
// NOTE: here we only check the amount is valid, we will also check more in the `pre_start` from channel creation
let (_funding_amount, _reserved_ckb_amount) = get_funding_and_reserved_amount(
funding_amount,
&shutdown_script,
&funding_udt_type_script,
)?;

let seed = self.generate_channel_seed();
let (tx, rx) = oneshot::channel::<Hash256>();
Expand Down
83 changes: 76 additions & 7 deletions src/fiber/tests/channel.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::fiber::graph::PaymentSessionStatus;
use crate::fiber::network::SendPaymentCommand;
use crate::fiber::tests::test_utils::gen_rand_public_key;
use crate::fiber::tests::test_utils::gen_sha256_hash;

use crate::fiber::tests::test_utils::{
gen_rand_public_key, gen_sha256_hash, NetworkNodeConfigBuilder,
};
use crate::{
ckb::contracts::{get_cell_deps, Contract},
fiber::{
Expand All @@ -11,7 +11,7 @@ use crate::{
ChannelCommand, ChannelCommandWithId, InMemorySigner, RemoveTlcCommand,
ShutdownCommand, DEFAULT_COMMITMENT_FEE_RATE,
},
config::DEFAULT_CHANNEL_MINIMAL_CKB_AMOUNT,
config::DEFAULT_AUTO_ACCEPT_CHANNEL_CKB_FUNDING_AMOUNT,
graph::NetworkGraphStateStore,
hash_algorithm::HashAlgorithm,
network::{AcceptChannelCommand, OpenChannelCommand},
Expand Down Expand Up @@ -138,7 +138,7 @@ async fn test_open_and_accept_channel() {
NetworkActorMessage::Command(NetworkActorCommand::AcceptChannel(
AcceptChannelCommand {
temp_channel_id: open_channel_result.channel_id,
funding_amount: DEFAULT_CHANNEL_MINIMAL_CKB_AMOUNT as u128,
funding_amount: DEFAULT_AUTO_ACCEPT_CHANNEL_CKB_FUNDING_AMOUNT as u128,
shutdown_script: None,
},
rpc_reply,
Expand Down Expand Up @@ -1670,10 +1670,25 @@ async fn test_connect_to_peers_with_mutual_channel_on_restart_version_2() {
}

#[tokio::test]
#[should_panic(expected = "Waiting for event timeout")]
async fn test_open_channel_with_large_size_shutdown_script() {
init_tracing();
let [node_a, mut node_b] = NetworkNode::new_n_interconnected_nodes().await;
let mut nodes = NetworkNode::new_n_interconnected_nodes_with_config(2, |i| {
NetworkNodeConfigBuilder::new()
.node_name(Some(format!("node-{}", i)))
.base_dir_prefix(&format!("fnn-test-node-{}-", i))
.fiber_config_updater(|config| {
// enable auto accept channel with default value
config.auto_accept_channel_ckb_funding_amount = Some(6200000000);
config.open_channel_auto_accept_min_ckb_funding_amount = Some(16200000000);
})
.build()
})
.await;

let mut node_a = nodes.pop().unwrap();
let mut node_b = nodes.pop().unwrap();

// test open channel with large size shutdown script
let message = |rpc_reply| {
NetworkActorMessage::Command(NetworkActorCommand::OpenChannel(
OpenChannelCommand {
Expand Down Expand Up @@ -1702,4 +1717,58 @@ async fn test_open_channel_with_large_size_shutdown_script() {
.err()
.unwrap()
.contains("The funding amount (8199999999) should be greater than or equal to 8200000000"));

// test auto accept channel with large size shutdown script
let message = |rpc_reply| {
NetworkActorMessage::Command(NetworkActorCommand::OpenChannel(
OpenChannelCommand {
peer_id: node_b.peer_id.clone(),
public: false,
shutdown_script: Some(Script::new_builder().args(vec![0u8; 40].pack()).build()),
funding_amount: (81 + 1 + 90) * 100000000,
funding_udt_type_script: None,
commitment_fee_rate: None,
commitment_delay_epoch: None,
funding_fee_rate: None,
tlc_expiry_delta: None,
tlc_min_value: None,
tlc_max_value: None,
tlc_fee_proportional_millionths: None,
max_tlc_number_in_flight: None,
max_tlc_value_in_flight: None,
},
rpc_reply,
))
};

let open_channel_result = call!(node_a.network_actor, message)
.expect("node_a alive")
.expect("open channel success");

node_b
.expect_event(|event| match event {
NetworkServiceEvent::ChannelPendingToBeAccepted(peer_id, channel_id) => {
println!("A channel ({:?}) to {:?} create", channel_id, peer_id);
assert_eq!(channel_id, &open_channel_result.channel_id);
assert_eq!(peer_id, &node_a.peer_id);
true
}
_ => false,
})
.await;

// should panic
node_a
.expect_event(|event| match event {
NetworkServiceEvent::ChannelReady(peer_id, channel_id, _funding_tx_hash) => {
println!(
"A channel ({:?}) to {:?} is now ready",
&channel_id, &peer_id
);
assert_eq!(peer_id, &node_b.peer_id);
true
}
_ => false,
})
.await;
}
8 changes: 0 additions & 8 deletions src/fiber/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,14 +566,6 @@ pub struct OpenChannel {
}

impl OpenChannel {
pub fn all_ckb_amount(&self) -> u64 {
if self.funding_udt_type_script.is_none() {
self.funding_amount as u64 + self.reserved_ckb_amount
} else {
self.reserved_ckb_amount
}
}

pub fn is_public(&self) -> bool {
self.channel_flags.contains(ChannelFlags::PUBLIC)
}
Expand Down

0 comments on commit afe2219

Please sign in to comment.