Skip to content

Commit

Permalink
WIP on Transfers
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Nov 6, 2020
1 parent 5ba1842 commit e9b30a4
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 24 deletions.
15 changes: 15 additions & 0 deletions contrib/demo.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

./target/debug/lnp-cli -d /tmp listen

./target/debug/lnp-cli connect 0275a326e4416600cea2601696e4ae03b239e717e87a290a00dbc1ba4f6df28290@127.0.0.1

./target/debug/lnp-cli propose 0275a326e4416600cea2601696e4ae03b239e717e87a290a00dbc1ba4f6df28290@127.0.0.1 1000

./target/debug/lnp-cli info

echo -n "Temp. channel id: "
read tchid

./target/debug/lnp-cli fund "$tchid" 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b:0

4 changes: 3 additions & 1 deletion shell/_lnp-cli
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ _arguments "${_arguments_options[@]}" \
;;
(transfer)
_arguments "${_arguments_options[@]}" \
'-a+[Asset ticker in which the invoice should be issued]' \
'--asset=[Asset ticker in which the invoice should be issued]' \
'-d+[Data directory path]: :_files -/' \
'--data-dir=[Data directory path]: :_files -/' \
'-c+[Path to the configuration file]: :_files' \
Expand All @@ -277,8 +279,8 @@ _arguments "${_arguments_options[@]}" \
'--help[Prints help information]' \
'-V[Prints version information]' \
'--version[Prints version information]' \
':channel -- Channel to which the funding must be added:' \
':amount -- Asset amount to invoice, in atomic unit (satoshis or smallest asset unit type):' \
'::asset -- Asset ticker in which the invoice should be issued:' \
&& ret=0
;;
(invoice)
Expand Down
2 changes: 2 additions & 0 deletions shell/_lnp-cli.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,8 @@ Register-ArgumentCompleter -Native -CommandName 'lnp-cli' -ScriptBlock {
break
}
'lnp-cli;transfer' {
[CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'Asset ticker in which the invoice should be issued')
[CompletionResult]::new('--asset', 'asset', [CompletionResultType]::ParameterName, 'Asset ticker in which the invoice should be issued')
[CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'Data directory path')
[CompletionResult]::new('--data-dir', 'data-dir', [CompletionResultType]::ParameterName, 'Data directory path')
[CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'Path to the configuration file')
Expand Down
10 changes: 9 additions & 1 deletion shell/lnp-cli.bash
Original file line number Diff line number Diff line change
Expand Up @@ -855,13 +855,21 @@ _lnp-cli() {
return 0
;;
lnp__cli__transfer)
opts=" -d -c -v -T -m -x -n -h -V --data-dir --config --verbose --tor-proxy --msg-socket --ctl-socket --chain --help --version <amount> <asset> "
opts=" -a -d -c -v -T -m -x -n -h -V --asset --data-dir --config --verbose --tor-proxy --msg-socket --ctl-socket --chain --help --version <channel> <amount> "
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
fi
case "${prev}" in

--asset)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-a)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--data-dir)
COMPREPLY=($(compgen -f "${cur}"))
return 0
Expand Down
93 changes: 75 additions & 18 deletions src/channeld/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ pub fn run(
remote_keys: dumb!(),
offered_htlc: empty!(),
received_htlc: empty!(),
resolved_htlc: empty!(),
is_originator: false,
obscuring_factor: 0,
enquirer: None,
Expand Down Expand Up @@ -119,7 +118,6 @@ pub struct Runtime {

offered_htlc: Vec<HtlcKnown>,
received_htlc: Vec<HtlcSecret>,
resolved_htlc: Vec<HtlcKnown>,

is_originator: bool,
obscuring_factor: u64,
Expand Down Expand Up @@ -284,7 +282,7 @@ impl Runtime {
let _ = self.report_progress_to(senders, &enquirer, msg);
}

Request::PeerMessage(Messages::FundingSigned(funding_signed)) => {
Request::PeerMessage(Messages::FundingSigned(_funding_signed)) => {
// TODO:
// 1. Get commitment tx
// 2. Verify signature
Expand Down Expand Up @@ -314,9 +312,10 @@ impl Runtime {
self.send_peer(
senders,
Messages::FundingLocked(funding_locked),
);
)?;

self.state = Lifecycle::Active;
self.local_capacity = self.params.funding_satoshis;

// Ignoring possible error here: do not want to
// halt the channel just because the client disconnected
Expand Down Expand Up @@ -350,18 +349,19 @@ impl Runtime {
}

Request::PeerMessage(Messages::UpdateAddHtlc(update_add_htlc)) => {
let commitment_signed =
let _commitment_signed =
self.htlc_receive(senders, update_add_htlc)?;
}

Request::PeerMessage(Messages::CommitmentSigned(
commitment_signed,
_commitment_signed,
)) => {}

Request::PeerMessage(Messages::RevokeAndAck(revoke_ack)) => {}
Request::PeerMessage(Messages::RevokeAndAck(_revoke_ack)) => {}

Request::PeerMessage(Messages::AssignFunds(assign_req)) => {
self.refill(
senders,
assign_req.consignment,
assign_req.outpoint,
assign_req.blinding,
Expand Down Expand Up @@ -458,6 +458,7 @@ impl Runtime {
self.enquirer = source.into();

self.refill(
senders,
refill_req.consignment.clone(),
refill_req.outpoint,
refill_req.blinding,
Expand Down Expand Up @@ -808,8 +809,6 @@ impl Runtime {
&mut self,
senders: &mut Senders,
) -> Result<(), Error> {
let enquirer = self.enquirer.clone();

let mut engine = sha256::Hash::engine();
if self.is_originator {
engine.input(&self.local_keys.payment_basepoint.serialize());
Expand Down Expand Up @@ -877,6 +876,18 @@ impl Runtime {
) -> Result<message::UpdateAddHtlc, Error> {
let enquirer = self.enquirer.clone();

let available = if let Some(asset_id) = transfer_req.asset {
self.local_balances.get(&asset_id).copied().unwrap_or(0)
} else {
self.local_capacity
};

if available < transfer_req.amount {
Err(Error::Other(s!(
"You do not have required amount of the asset"
)))?
}

info!(
"{} {} {} to the remote peer",
"Transferring".promo(),
Expand Down Expand Up @@ -909,11 +920,22 @@ impl Runtime {
asset_id: transfer_req.asset,
};
self.total_payments += 1;
match transfer_req.asset {
Some(asset_id) => {
self.local_balances.get_mut(&asset_id).map(|balance| {
*balance -= transfer_req.amount;
});

let entry = self.remote_balances.entry(asset_id).or_insert(0);
*entry += transfer_req.amount;
}
None => {
self.local_capacity -= transfer_req.amount;
self.remote_capacity += transfer_req.amount;
}
}

let msg = format!(
"{}, awaiting for peer signature",
"Funding transferred".ended()
);
let msg = format!("{}", "Funding transferred".ended());
info!("{}", msg);
let _ = self.report_progress_to(senders, &enquirer, msg);

Expand All @@ -922,10 +944,13 @@ impl Runtime {

pub fn refill(
&mut self,
senders: &mut Senders,
consignment: Consignment,
outpoint: OutPoint,
blinding: u64,
) -> Result<(), Error> {
let enquirer = self.enquirer.clone();

debug!("Validating consignment with RGB Node ...");
self.request_rbg20(rgb_node::api::fungible::Request::Validate(
consignment.clone(),
Expand All @@ -951,21 +976,38 @@ impl Runtime {
for (id, balances) in balances {
let asset_id = AssetId::from(id);
let balance: u64 = balances.into_iter().sum();
debug!("Adding {} of {} to balance", balance, asset_id);
info!(
"{} {} of {} to balance",
"Adding".promo(),
balance.promoter(),
asset_id.promoter()
);
let msg = format!(
"adding {} of {} to balance",
balance.ender(),
asset_id.ender()
);
let _ = self.report_progress_to(senders, &enquirer, msg);

self.local_balances.insert(asset_id, balance);
}
}
_ => Err(Error::Other(s!("Unrecognized RGB Node response")))?,
}

let _ = self.report_success_to(
senders,
&enquirer,
Some("transfer completed"),
);
Ok(())
}

pub fn htlc_receive(
&mut self,
senders: &mut Senders,
_senders: &mut Senders,
update_add_htlc: message::UpdateAddHtlc,
) -> Result<message::CommitmentSigned, Error> {
) -> Result</* message::CommitmentSigned */ (), Error> {
trace!("Updating HTLCs with {:?}", update_add_htlc);
// TODO: Use From/To for message <-> Htlc conversion in LNP/BP
// Core lib
Expand All @@ -977,13 +1019,28 @@ impl Runtime {
};
self.received_htlc.push(htlc);

match update_add_htlc.asset_id {
Some(asset_id) => {
self.remote_balances.get_mut(&asset_id).map(|balance| {
*balance -= update_add_htlc.amount_msat;
});

let entry = self.local_balances.entry(asset_id).or_insert(0);
*entry += update_add_htlc.amount_msat;
}
None => {
self.remote_capacity -= update_add_htlc.amount_msat;
self.local_capacity += update_add_htlc.amount_msat;
}
}

Ok(())

// TODO:
// 1. Generate new commitment tx
// 2. Generate new transitions and anchor, commit into tx
// 3. Sign commitment tx
// 4. Generate HTLCs, tweak etc each of them
// 3. Send response

unimplemented!()
}
}
16 changes: 16 additions & 0 deletions src/cli/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,22 @@ impl Exec for Command {
runtime.report_progress()?;
}

Command::Transfer {
channel,
amount,
asset,
} => {
runtime.request(
channel.clone().into(),
Request::Transfer(request::Transfer {
channeld: channel.clone().into(),
amount: *amount,
asset: asset.map(|id| id.into()),
}),
)?;
runtime.report_progress()?;
}

Command::Refill {
channel,
consignment,
Expand Down
8 changes: 6 additions & 2 deletions src/cli/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use std::str::FromStr;

use lnpbp::bitcoin::OutPoint;
use lnpbp::lnp::{ChannelId, FramingProtocol, PartialNodeAddr, TempChannelId};
use lnpbp::rgb::ContractId;

/// Command-line tool for working with LNP node
#[derive(Clap, Clone, PartialEq, Eq, Debug)]
Expand Down Expand Up @@ -151,13 +152,16 @@ pub enum Command {

/// Do an invoiceless direct payment
Transfer {
/// Channel to which the funding must be added
channel: ChannelId,

/// Asset amount to invoice, in atomic unit (satoshis or smallest asset
/// unit type)
amount: u64,

/// Asset ticker in which the invoice should be issued
#[clap(default_value = "btc")]
asset: String,
#[clap(short, long)]
asset: Option<ContractId>,
},

/// Create an invoice
Expand Down
2 changes: 0 additions & 2 deletions src/peerd/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ use lnpbp_services::peer;
use crate::rpc::{request::PeerInfo, Request, ServiceBus};
use crate::{Config, CtlServer, Error, LogStyle, Service, ServiceId};

pub struct MessageFilter {}

pub fn run(
config: Config,
connection: PeerConnection,
Expand Down

0 comments on commit e9b30a4

Please sign in to comment.