use crate::chain::ClaimId;
use crate::io_extras::sink;
use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
+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::sign::{
ChannelDerivationParameters, HTLCDescriptor, SignerProvider, P2WPKH_WITNESS_WEIGHT
};
-use crate::sign::ecdsa::{EcdsaChannelSigner, WriteableEcdsaChannelSigner};
+use crate::sign::ecdsa::EcdsaChannelSigner;
use crate::sync::Mutex;
use crate::util::logger::Logger;
-use bitcoin::{OutPoint, PubkeyHash, Sequence, ScriptBuf, Transaction, TxIn, TxOut, Witness, WPubkeyHash};
+use bitcoin::{OutPoint, Psbt, PubkeyHash, Sequence, ScriptBuf, Transaction, TxIn, TxOut, Witness, WPubkeyHash};
+use bitcoin::amount::Amount;
use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::consensus::Encodable;
use bitcoin::secp256k1;
-use bitcoin::secp256k1::Secp256k1;
+use bitcoin::secp256k1::{PublicKey, Secp256k1};
use bitcoin::secp256k1::ecdsa::Signature;
+use bitcoin::transaction::Version;
-const EMPTY_SCRIPT_SIG_WEIGHT: u64 = 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64;
+pub(crate) const EMPTY_SCRIPT_SIG_WEIGHT: u64 = 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64;
const BASE_INPUT_SIZE: u64 = 32 /* txid */ + 4 /* vout */ + 4 /* sequence */;
-const BASE_INPUT_WEIGHT: u64 = BASE_INPUT_SIZE * WITNESS_SCALE_FACTOR as u64;
+pub(crate) const BASE_INPUT_WEIGHT: u64 = BASE_INPUT_SIZE * WITNESS_SCALE_FACTOR as u64;
/// A descriptor used to sign for a commitment transaction's anchor output.
#[derive(Clone, Debug, PartialEq, Eq)]
/// [`Self::unsigned_tx_input`].
pub fn previous_utxo(&self) -> TxOut {
TxOut {
- script_pubkey: self.witness_script().to_v0_p2wsh(),
- value: ANCHOR_OUTPUT_VALUE_SATOSHI,
+ script_pubkey: self.witness_script().to_p2wsh(),
+ value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
}
}
}
/// Derives the channel signer required to sign the anchor input.
- pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
+ pub fn derive_channel_signer<S: EcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
where
SP::Target: SignerProvider<EcdsaSigner= S>
{
/// [`EcdsaChannelSigner::sign_holder_anchor_input`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_holder_anchor_input
/// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
ChannelClose {
+ /// The `channel_id` of the channel which has been closed.
+ channel_id: ChannelId,
+ /// Counterparty in the closed channel.
+ counterparty_node_id: PublicKey,
/// The unique identifier for the claim of the anchor output in the commitment transaction.
///
/// The identifier must map to the set of external UTXOs assigned to the claim, such that
/// [`EcdsaChannelSigner`]: crate::sign::ecdsa::EcdsaChannelSigner
/// [`EcdsaChannelSigner::sign_holder_htlc_transaction`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_holder_htlc_transaction
HTLCResolution {
+ /// The `channel_id` of the channel which has been closed.
+ channel_id: ChannelId,
+ /// Counterparty in the closed channel.
+ counterparty_node_id: PublicKey,
/// The unique identifier for the claim of the HTLCs in the confirmed commitment
/// transaction.
///
impl Utxo {
/// Returns a `Utxo` with the `satisfaction_weight` estimate for a legacy P2PKH output.
- pub fn new_p2pkh(outpoint: OutPoint, value: u64, pubkey_hash: &PubkeyHash) -> Self {
+ pub fn new_p2pkh(outpoint: OutPoint, value: Amount, pubkey_hash: &PubkeyHash) -> Self {
let script_sig_size = 1 /* script_sig length */ +
1 /* OP_PUSH73 */ +
73 /* sig including sighash flag */ +
}
/// Returns a `Utxo` with the `satisfaction_weight` estimate for a P2WPKH nested in P2SH output.
- pub fn new_nested_p2wpkh(outpoint: OutPoint, value: u64, pubkey_hash: &WPubkeyHash) -> Self {
+ pub fn new_nested_p2wpkh(outpoint: OutPoint, value: Amount, pubkey_hash: &WPubkeyHash) -> Self {
let script_sig_size = 1 /* script_sig length */ +
1 /* OP_0 */ +
1 /* OP_PUSH20 */ +
outpoint,
output: TxOut {
value,
- script_pubkey: ScriptBuf::new_p2sh(&ScriptBuf::new_v0_p2wpkh(pubkey_hash).script_hash()),
+ script_pubkey: ScriptBuf::new_p2sh(&ScriptBuf::new_p2wpkh(pubkey_hash).script_hash()),
},
satisfaction_weight: script_sig_size * WITNESS_SCALE_FACTOR as u64 + P2WPKH_WITNESS_WEIGHT,
}
}
/// Returns a `Utxo` with the `satisfaction_weight` estimate for a SegWit v0 P2WPKH output.
- pub fn new_v0_p2wpkh(outpoint: OutPoint, value: u64, pubkey_hash: &WPubkeyHash) -> Self {
+ pub fn new_v0_p2wpkh(outpoint: OutPoint, value: Amount, pubkey_hash: &WPubkeyHash) -> Self {
Self {
outpoint,
output: TxOut {
value,
- script_pubkey: ScriptBuf::new_v0_p2wpkh(pubkey_hash),
+ script_pubkey: ScriptBuf::new_p2wpkh(pubkey_hash),
},
satisfaction_weight: EMPTY_SCRIPT_SIG_WEIGHT + P2WPKH_WITNESS_WEIGHT,
}
) -> Result<CoinSelection, ()>;
/// Signs and provides the full witness for all inputs within the transaction known to the
/// trait (i.e., any provided via [`CoinSelectionSource::select_confirmed_utxos`]).
- fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()>;
+ ///
+ /// If your wallet does not support signing PSBTs you can call `psbt.extract_tx()` to get the
+ /// unsigned transaction and then sign it with your wallet.
+ fn sign_psbt(&self, psbt: Psbt) -> Result<Transaction, ()>;
}
/// An alternative to [`CoinSelectionSource`] that can be implemented and used along [`Wallet`] to
/// Signs and provides the full [`TxIn::script_sig`] and [`TxIn::witness`] for all inputs within
/// the transaction known to the wallet (i.e., any provided via
/// [`WalletSource::list_confirmed_utxos`]).
- fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()>;
+ ///
+ /// If your wallet does not support signing PSBTs you can call `psbt.extract_tx()` to get the
+ /// unsigned transaction and then sign it with your wallet.
+ fn sign_psbt(&self, psbt: Psbt) -> Result<Transaction, ()>;
}
/// A wrapper over [`WalletSource`] that implements [`CoinSelection`] by preferring UTXOs that would
/// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation
/// of [`CoinSelectionSource`].
pub fn new(source: W, logger: L) -> Self {
- Self { source, logger, locked_utxos: Mutex::new(HashMap::new()) }
+ Self { source, logger, locked_utxos: Mutex::new(new_hash_map()) }
}
/// Performs coin selection on the set of UTXOs obtained from
fn select_confirmed_utxos_internal(
&self, utxos: &[Utxo], claim_id: ClaimId, force_conflicting_utxo_spend: bool,
tolerate_high_network_feerates: bool, target_feerate_sat_per_1000_weight: u32,
- preexisting_tx_weight: u64, input_amount_sat: u64, target_amount_sat: u64,
+ preexisting_tx_weight: u64, input_amount_sat: Amount, target_amount_sat: Amount,
) -> Result<CoinSelection, ()> {
let mut locked_utxos = self.locked_utxos.lock().unwrap();
let mut eligible_utxos = utxos.iter().filter_map(|utxo| {
return None;
}
}
- let fee_to_spend_utxo = fee_for_weight(
+ let fee_to_spend_utxo = Amount::from_sat(fee_for_weight(
target_feerate_sat_per_1000_weight, BASE_INPUT_WEIGHT + utxo.satisfaction_weight,
- );
+ ));
let should_spend = if tolerate_high_network_feerates {
utxo.output.value > fee_to_spend_utxo
} else {
eligible_utxos.sort_unstable_by_key(|(utxo, _)| utxo.output.value);
let mut selected_amount = input_amount_sat;
- let mut total_fees = fee_for_weight(target_feerate_sat_per_1000_weight, preexisting_tx_weight);
+ let mut total_fees = Amount::from_sat(fee_for_weight(target_feerate_sat_per_1000_weight, preexisting_tx_weight));
let mut selected_utxos = Vec::new();
for (utxo, fee_to_spend_utxo) in eligible_utxos {
if selected_amount >= target_amount_sat + total_fees {
(8 /* value */ + change_script.consensus_encode(&mut sink()).unwrap() as u64) *
WITNESS_SCALE_FACTOR as u64,
);
- let change_output_amount = remaining_amount.saturating_sub(change_output_fee);
- let change_output = if change_output_amount < change_script.dust_value().to_sat() {
+ let change_output_amount = Amount::from_sat(remaining_amount.to_sat().saturating_sub(change_output_fee));
+ let change_output = if change_output_amount < change_script.dust_value() {
log_debug!(self.logger, "Coin selection attempt did not yield change output");
None
} else {
let preexisting_tx_weight = 2 /* segwit marker & flag */ + total_input_weight +
((BASE_TX_SIZE + total_output_size) * WITNESS_SCALE_FACTOR as u64);
- let input_amount_sat: u64 = must_spend.iter().map(|input| input.previous_utxo.value).sum();
+ let input_amount_sat = must_spend.iter().map(|input| input.previous_utxo.value).sum();
let target_amount_sat = must_pay_to.iter().map(|output| output.value).sum();
let do_coin_selection = |force_conflicting_utxo_spend: bool, tolerate_high_network_feerates: bool| {
log_debug!(self.logger, "Attempting coin selection targeting {} sat/kW (force_conflicting_utxo_spend = {}, tolerate_high_network_feerates = {})",
.or_else(|_| do_coin_selection(true, true))
}
- fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
- self.source.sign_tx(tx)
+ fn sign_psbt(&self, psbt: Psbt) -> Result<Transaction, ()> {
+ self.source.sign_psbt(psbt)
}
}
}
/// Updates a transaction with the result of a successful coin selection attempt.
- fn process_coin_selection(&self, tx: &mut Transaction, mut coin_selection: CoinSelection) {
- for utxo in coin_selection.confirmed_utxos.drain(..) {
+ fn process_coin_selection(&self, tx: &mut Transaction, coin_selection: &CoinSelection) {
+ for utxo in coin_selection.confirmed_utxos.iter() {
tx.input.push(TxIn {
previous_output: utxo.outpoint,
script_sig: ScriptBuf::new(),
witness: Witness::new(),
});
}
- if let Some(change_output) = coin_selection.change_output.take() {
+ if let Some(change_output) = coin_selection.change_output.clone() {
tx.output.push(change_output);
} else if tx.output.is_empty() {
// We weren't provided a change output, likely because the input set was a perfect
// way to include a dummy output.
log_debug!(self.logger, "Including dummy OP_RETURN output since an output is needed and a change output was not provided");
tx.output.push(TxOut {
- value: 0,
+ value: Amount::ZERO,
script_pubkey: ScriptBuf::new_op_return(&[]),
});
}
commitment_tx: &Transaction, commitment_tx_fee_sat: u64, anchor_descriptor: &AnchorDescriptor,
) -> Result<(), ()> {
// Our commitment transaction already has fees allocated to it, so we should take them into
- // account. We do so by pretending the commitment tranasction's fee and weight are part of
+ // account. We do so by pretending the commitment transaction's fee and weight are part of
// the anchor input.
let mut anchor_utxo = anchor_descriptor.previous_utxo();
+ let commitment_tx_fee_sat = Amount::from_sat(commitment_tx_fee_sat);
anchor_utxo.value += commitment_tx_fee_sat;
let must_spend = vec![Input {
outpoint: anchor_descriptor.outpoint,
satisfaction_weight: commitment_tx.weight().to_wu() + ANCHOR_INPUT_WITNESS_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT,
}];
#[cfg(debug_assertions)]
- let must_spend_amount = must_spend.iter().map(|input| input.previous_utxo.value).sum::<u64>();
+ let must_spend_amount = must_spend.iter().map(|input| input.previous_utxo.value).sum::<Amount>();
- log_debug!(self.logger, "Peforming coin selection for commitment package (commitment and anchor transaction) targeting {} sat/kW",
+ log_debug!(self.logger, "Performing coin selection for commitment package (commitment and anchor transaction) targeting {} sat/kW",
package_target_feerate_sat_per_1000_weight);
- let coin_selection = self.utxo_source.select_confirmed_utxos(
+ let coin_selection: CoinSelection = self.utxo_source.select_confirmed_utxos(
claim_id, must_spend, &[], package_target_feerate_sat_per_1000_weight,
)?;
let mut anchor_tx = Transaction {
- version: 2,
+ version: Version::TWO,
lock_time: LockTime::ZERO, // TODO: Use next best height.
input: vec![anchor_descriptor.unsigned_tx_input()],
output: vec![],
coin_selection.confirmed_utxos.iter().map(|utxo| utxo.satisfaction_weight).sum::<u64>();
#[cfg(debug_assertions)]
let total_input_amount = must_spend_amount +
- coin_selection.confirmed_utxos.iter().map(|utxo| utxo.output.value).sum::<u64>();
+ coin_selection.confirmed_utxos.iter().map(|utxo| utxo.output.value).sum();
- self.process_coin_selection(&mut anchor_tx, coin_selection);
+ self.process_coin_selection(&mut anchor_tx, &coin_selection);
let anchor_txid = anchor_tx.txid();
- debug_assert_eq!(anchor_tx.output.len(), 1);
+ // construct psbt
+ let mut anchor_psbt = Psbt::from_unsigned_tx(anchor_tx).unwrap();
+ // add witness_utxo to anchor input
+ anchor_psbt.inputs[0].witness_utxo = Some(anchor_descriptor.previous_utxo());
+ // add witness_utxo to remaining inputs
+ for (idx, utxo) in coin_selection.confirmed_utxos.into_iter().enumerate() {
+ // add 1 to skip the anchor input
+ let index = idx + 1;
+ debug_assert_eq!(anchor_psbt.unsigned_tx.input[index].previous_output, utxo.outpoint);
+ if utxo.output.script_pubkey.is_witness_program() {
+ anchor_psbt.inputs[index].witness_utxo = Some(utxo.output);
+ }
+ }
+
+ debug_assert_eq!(anchor_psbt.unsigned_tx.output.len(), 1);
#[cfg(debug_assertions)]
- let unsigned_tx_weight = anchor_tx.weight().to_wu() - (anchor_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
+ let unsigned_tx_weight = anchor_psbt.unsigned_tx.weight().to_wu() - (anchor_psbt.unsigned_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
log_debug!(self.logger, "Signing anchor transaction {}", anchor_txid);
- anchor_tx = self.utxo_source.sign_tx(anchor_tx)?;
+ anchor_tx = self.utxo_source.sign_psbt(anchor_psbt)?;
let signer = anchor_descriptor.derive_channel_signer(&self.signer_provider);
let anchor_sig = signer.sign_holder_anchor_input(&anchor_tx, 0, &self.secp)?;
assert!(expected_signed_tx_weight >= signed_tx_weight &&
expected_signed_tx_weight - (expected_signed_tx_weight / 100) <= signed_tx_weight);
- let expected_package_fee = fee_for_weight(package_target_feerate_sat_per_1000_weight,
- signed_tx_weight + commitment_tx.weight().to_wu());
+ let expected_package_fee = Amount::from_sat(fee_for_weight(package_target_feerate_sat_per_1000_weight,
+ signed_tx_weight + commitment_tx.weight().to_wu()));
let package_fee = total_input_amount -
- anchor_tx.output.iter().map(|output| output.value).sum::<u64>();
+ anchor_tx.output.iter().map(|output| output.value).sum();
// Our fee should be within a 5% error margin of the expected fee based on the
// feerate and transaction weight and we should never pay less than required.
let fee_error_margin = expected_package_fee * 5 / 100;
htlc_descriptors: &[HTLCDescriptor], tx_lock_time: LockTime,
) -> Result<(), ()> {
let mut htlc_tx = Transaction {
- version: 2,
+ version: Version::TWO,
lock_time: tx_lock_time,
input: vec![],
output: vec![],
htlc_tx.output.push(htlc_output);
}
- log_debug!(self.logger, "Peforming coin selection for HTLC transaction targeting {} sat/kW",
+ log_debug!(self.logger, "Performing coin selection for HTLC transaction targeting {} sat/kW",
target_feerate_sat_per_1000_weight);
#[cfg(debug_assertions)]
let must_spend_satisfaction_weight =
must_spend.iter().map(|input| input.satisfaction_weight).sum::<u64>();
#[cfg(debug_assertions)]
- let must_spend_amount = must_spend.iter().map(|input| input.previous_utxo.value).sum::<u64>();
+ let must_spend_amount = must_spend.iter().map(|input| input.previous_utxo.value.to_sat()).sum::<u64>();
- let coin_selection = self.utxo_source.select_confirmed_utxos(
+ let coin_selection: CoinSelection = self.utxo_source.select_confirmed_utxos(
claim_id, must_spend, &htlc_tx.output, target_feerate_sat_per_1000_weight,
)?;
coin_selection.confirmed_utxos.iter().map(|utxo| utxo.satisfaction_weight).sum::<u64>();
#[cfg(debug_assertions)]
let total_input_amount = must_spend_amount +
- coin_selection.confirmed_utxos.iter().map(|utxo| utxo.output.value).sum::<u64>();
+ coin_selection.confirmed_utxos.iter().map(|utxo| utxo.output.value.to_sat()).sum::<u64>();
- self.process_coin_selection(&mut htlc_tx, coin_selection);
+ self.process_coin_selection(&mut htlc_tx, &coin_selection);
+
+ // construct psbt
+ let mut htlc_psbt = Psbt::from_unsigned_tx(htlc_tx).unwrap();
+ // add witness_utxo to htlc inputs
+ for (i, htlc_descriptor) in htlc_descriptors.iter().enumerate() {
+ debug_assert_eq!(htlc_psbt.unsigned_tx.input[i].previous_output, htlc_descriptor.outpoint());
+ htlc_psbt.inputs[i].witness_utxo = Some(htlc_descriptor.previous_utxo(&self.secp));
+ }
+ // add witness_utxo to remaining inputs
+ for (idx, utxo) in coin_selection.confirmed_utxos.into_iter().enumerate() {
+ // offset to skip the htlc inputs
+ let index = idx + htlc_descriptors.len();
+ debug_assert_eq!(htlc_psbt.unsigned_tx.input[index].previous_output, utxo.outpoint);
+ if utxo.output.script_pubkey.is_witness_program() {
+ htlc_psbt.inputs[index].witness_utxo = Some(utxo.output);
+ }
+ }
#[cfg(debug_assertions)]
- let unsigned_tx_weight = htlc_tx.weight().to_wu() - (htlc_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
+ let unsigned_tx_weight = htlc_psbt.unsigned_tx.weight().to_wu() - (htlc_psbt.unsigned_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
- log_debug!(self.logger, "Signing HTLC transaction {}", htlc_tx.txid());
- htlc_tx = self.utxo_source.sign_tx(htlc_tx)?;
+ log_debug!(self.logger, "Signing HTLC transaction {}", htlc_psbt.unsigned_tx.txid());
+ htlc_tx = self.utxo_source.sign_psbt(htlc_psbt)?;
let mut signers = BTreeMap::new();
for (idx, htlc_descriptor) in htlc_descriptors.iter().enumerate() {
let expected_signed_tx_fee = fee_for_weight(target_feerate_sat_per_1000_weight, signed_tx_weight);
let signed_tx_fee = total_input_amount -
- htlc_tx.output.iter().map(|output| output.value).sum::<u64>();
+ htlc_tx.output.iter().map(|output| output.value.to_sat()).sum::<u64>();
// Our fee should be within a 5% error margin of the expected fee based on the
// feerate and transaction weight and we should never pay less than required.
let fee_error_margin = expected_signed_tx_fee * 5 / 100;
}
}
BumpTransactionEvent::HTLCResolution {
- claim_id, target_feerate_sat_per_1000_weight, htlc_descriptors, tx_lock_time,
+ claim_id, target_feerate_sat_per_1000_weight, htlc_descriptors, tx_lock_time, ..
} => {
log_info!(self.logger, "Handling HTLC bump (claim_id = {}, htlcs_to_claim = {})",
log_bytes!(claim_id.0), log_iter!(htlc_descriptors.iter().map(|d| d.outpoint())));