Skip to content

Commit

Permalink
openchannel w/custom fees + refuse_high_fees test
Browse files Browse the repository at this point in the history
  • Loading branch information
zoedberg committed Feb 20, 2024
1 parent 5f3a292 commit 4645169
Show file tree
Hide file tree
Showing 8 changed files with 153 additions and 12 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,12 @@ components:
with_anchors:
type: boolean
example: true
fee_base_msat:
type: integer
example: 1000
fee_proportional_millionths:
type: integer
example: 0
OpenChannelResponse:
type: object
properties:
Expand Down
4 changes: 3 additions & 1 deletion src/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use crate::error::APIError;
use crate::ldk::{InboundPaymentInfoStorage, NetworkGraph, OutboundPaymentInfoStorage};
use crate::utils::{parse_peer_info, LOGS_DIR};

pub(crate) const LDK_LOGS_FILE: &str = "logs.txt";

pub(crate) const INBOUND_PAYMENTS_FNAME: &str = "inbound_payments";
pub(crate) const OUTBOUND_PAYMENTS_FNAME: &str = "outbound_payments";

Expand Down Expand Up @@ -47,7 +49,7 @@ impl Logger for FilesystemLogger {
record.line,
raw_log
);
let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
let logs_file_path = format!("{}/{LDK_LOGS_FILE}", self.data_dir.clone());
fs::OpenOptions::new()
.create(true)
.append(true)
Expand Down
13 changes: 12 additions & 1 deletion src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use lightning::ln::ChannelId;
use lightning::onion_message::{Destination, OnionMessagePath};
use lightning::rgb_utils::{get_rgb_payment_info_path, parse_rgb_payment_info};
use lightning::sign::EntropySource;
use lightning::util::config::ChannelConfig;
use lightning::{
ln::{
channelmanager::{PaymentId, RecipientOnionFields, Retry},
Expand Down Expand Up @@ -244,7 +245,7 @@ pub(crate) struct DisconnectPeerRequest {
#[derive(Deserialize, Serialize)]
pub(crate) struct EmptyResponse {}

#[derive(Clone, Copy, Deserialize, Serialize)]
#[derive(Clone, Copy, PartialEq, Deserialize, Serialize)]
pub(crate) enum HTLCStatus {
Pending,
Succeeded,
Expand Down Expand Up @@ -390,6 +391,8 @@ pub(crate) struct OpenChannelRequest {
pub(crate) asset_id: String,
pub(crate) public: bool,
pub(crate) with_anchors: bool,
pub(crate) fee_base_msat: Option<u32>,
pub(crate) fee_proportional_millionths: Option<u32>,
}

#[derive(Deserialize, Serialize)]
Expand Down Expand Up @@ -1515,6 +1518,13 @@ pub(crate) async fn open_channel(
return Err(APIError::InsufficientAssets(spendable_rgb_amount));
}

let mut channel_config = ChannelConfig::default();
if let Some(fee_base_msat) = payload.fee_base_msat {
channel_config.forwarding_fee_base_msat = fee_base_msat;
}
if let Some(fee_proportional_millionths) = payload.fee_proportional_millionths {
channel_config.forwarding_fee_proportional_millionths = fee_proportional_millionths;
}
let config = UserConfig {
channel_handshake_limits: ChannelHandshakeLimits {
// lnd's max to_self_delay is 2016, so we want to be compatible.
Expand All @@ -1528,6 +1538,7 @@ pub(crate) async fn open_channel(
negotiate_anchors_zero_fee_htlc_tx: payload.with_anchors,
..Default::default()
},
channel_config,
..Default::default()
};

Expand Down
2 changes: 1 addition & 1 deletion src/test/close_coop_standard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn close_coop_standard() {
fund_and_create_utxos(node3_addr).await;

let unspents = list_unspents(node1_addr).await;
assert_eq!(unspents.len(), 5);
assert_eq!(unspents.len(), 11);

let assets = list_assets(node1_addr).await;
assert_eq!(assets.len(), 0);
Expand Down
44 changes: 38 additions & 6 deletions src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ async fn fund_and_create_utxos(node_address: SocketAddr) {

let payload = CreateUtxosRequest {
up_to: false,
num: None,
num: Some(10),
};
let res = reqwest::Client::new()
.post(format!("http://{}/createutxos", node_address))
Expand Down Expand Up @@ -485,22 +485,26 @@ async fn node_info(node_address: SocketAddr) -> NodeInfoResponse {
.unwrap()
}

async fn open_channel(
async fn open_channel_with_custom_fees(
node_address: SocketAddr,
dest_peer_pubkey: &str,
dest_peer_port: u16,
asset_amount: u64,
asset_id: &str,
fee_base_msat: Option<u32>,
fee_proportional_millionths: Option<u32>,
) -> Channel {
stop_mining();
let payload = OpenChannelRequest {
peer_pubkey_and_addr: format!("{}@127.0.0.1:{}", dest_peer_pubkey, dest_peer_port),
capacity_sat: 30010,
push_msat: 2130000,
capacity_sat: 100_000,
push_msat: 3_500_000,
asset_amount,
asset_id: asset_id.to_string(),
public: true,
with_anchors: true,
fee_base_msat,
fee_proportional_millionths,
};
let res = reqwest::Client::new()
.post(format!("http://{}/openchannel", node_address))
Expand Down Expand Up @@ -554,6 +558,25 @@ async fn open_channel(
}
}

async fn open_channel(
node_address: SocketAddr,
dest_peer_pubkey: &str,
dest_peer_port: u16,
asset_amount: u64,
asset_id: &str,
) -> Channel {
open_channel_with_custom_fees(
node_address,
dest_peer_pubkey,
dest_peer_port,
asset_amount,
asset_id,
None,
None,
)
.await
}

async fn list_assets(node_address: SocketAddr) -> Vec<Asset> {
let res = reqwest::Client::new()
.get(format!("http://{}/listassets", node_address))
Expand Down Expand Up @@ -695,6 +718,14 @@ async fn send_asset(node_address: SocketAddr, asset_id: &str, amount: u64, blind
}

async fn send_payment(node_address: SocketAddr, invoice: String) -> Payment {
send_payment_with_status(node_address, invoice, HTLCStatus::Succeeded).await
}

async fn send_payment_with_status(
node_address: SocketAddr,
invoice: String,
expected_status: HTLCStatus,
) -> Payment {
let payload = SendPaymentRequest { invoice };
let res = reqwest::Client::new()
.post(format!("http://{}/sendpayment", node_address))
Expand All @@ -716,12 +747,12 @@ async fn send_payment(node_address: SocketAddr, invoice: String) -> Payment {
.iter()
.find(|p| p.payment_hash == send_payment.payment_hash)
{
if matches!(payment.status, HTLCStatus::Succeeded) {
if payment.status == expected_status {
return payment.clone();
}
}
if (OffsetDateTime::now_utc() - t_0).as_seconds_f32() > 10.0 {
panic!("cannot find successful payment")
panic!("cannot find payment in expected status")
}
}
}
Expand Down Expand Up @@ -946,5 +977,6 @@ mod multi_hop;
mod multi_open_close;
mod open_after_double_send;
mod payment;
mod refuse_high_fees;
mod restart;
mod send_receive;
89 changes: 89 additions & 0 deletions src/test/refuse_high_fees.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use crate::disk::LDK_LOGS_FILE;
use crate::utils::LDK_DIR;
use std::{
fs::File,
io::{BufRead, BufReader},
path::PathBuf,
};

use super::*;

const TEST_DIR_BASE: &str = "tmp/refuse_high_fees/";
const NODE1_PEER_PORT: u16 = 9931;
const NODE2_PEER_PORT: u16 = 9932;
const NODE3_PEER_PORT: u16 = 9933;

#[serial_test::serial]
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[traced_test]
async fn refuse_high_fees() {
initialize();

let test_dir_node1 = format!("{TEST_DIR_BASE}node1");
let test_dir_node2 = format!("{TEST_DIR_BASE}node2");
let test_dir_node3 = format!("{TEST_DIR_BASE}node3");
let (node1_addr, _) = start_node(test_dir_node1.clone(), NODE1_PEER_PORT, false).await;
let (node2_addr, _) = start_node(test_dir_node2, NODE2_PEER_PORT, false).await;
let (node3_addr, _) = start_node(test_dir_node3, NODE3_PEER_PORT, false).await;

fund_and_create_utxos(node1_addr).await;
fund_and_create_utxos(node2_addr).await;

let asset_id = issue_asset(node1_addr).await;

let node2_info = node_info(node2_addr).await;
let node2_pubkey = node2_info.pubkey;
let node3_info = node_info(node3_addr).await;
let node3_pubkey = node3_info.pubkey;

let recipient_id = rgb_invoice(node2_addr, None).await.recipient_id;
send_asset(node1_addr, &asset_id, 400, recipient_id).await;
mine(false);
refresh_transfers(node2_addr).await;
refresh_transfers(node2_addr).await;
refresh_transfers(node1_addr).await;
assert_eq!(asset_balance(node1_addr, &asset_id).await, 600);

let _channel_12 =
open_channel(node1_addr, &node2_pubkey, NODE2_PEER_PORT, 500, &asset_id).await;
assert_eq!(asset_balance(node1_addr, &asset_id).await, 100);
assert_eq!(asset_balance(node2_addr, &asset_id).await, 400);

let _channel_23 = open_channel_with_custom_fees(
node2_addr,
&node3_pubkey,
NODE3_PEER_PORT,
300,
&asset_id,
Some(2_000_000),
None,
)
.await;
assert_eq!(asset_balance(node1_addr, &asset_id).await, 100);

let LNInvoiceResponse { invoice } = ln_invoice(node3_addr, &asset_id, 50, 900).await;
let _ = send_payment_with_status(node1_addr, invoice, HTLCStatus::Failed).await;

let file = File::open(
PathBuf::from(test_dir_node1)
.join(LDK_DIR)
.join(LOGS_DIR)
.join(LDK_LOGS_FILE),
)
.unwrap();
let reader = BufReader::new(file);

let mut found_log = false;
for line in reader.lines() {
if line
.unwrap()
.contains("due to exceeding max total routing fee limit")
{
found_log = true;
break;
}
}
if !found_log {
panic!("expected log line not found")
}
}
3 changes: 2 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use crate::{
rgb::get_bitcoin_network,
};

pub(crate) const LDK_DIR: &str = ".ldk";
pub(crate) const LOGS_DIR: &str = "logs";
const ELECTRUM_URL_REGTEST: &str = "127.0.0.1:50001";
const ELECTRUM_URL_TESTNET: &str = "ssl://electrum.iriswallet.com:50013";
Expand Down Expand Up @@ -317,7 +318,7 @@ pub(crate) fn parse_peer_info(

pub(crate) async fn start_daemon(args: LdkUserInfo) -> Result<Arc<AppState>, AppError> {
// Initialize the Logger (creates ldk_data_dir and its logs directory)
let ldk_data_dir = format!("{}/.ldk", args.storage_dir_path);
let ldk_data_dir = format!("{}/{LDK_DIR}", args.storage_dir_path);
let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));

// Initialize our bitcoind client.
Expand Down

0 comments on commit 4645169

Please sign in to comment.