diff --git a/bitcoin/psbt.c b/bitcoin/psbt.c index fab224afc..015a0eb42 100644 --- a/bitcoin/psbt.c +++ b/bitcoin/psbt.c @@ -820,3 +820,30 @@ void psbt_txid(const tal_t *ctx, else wally_tx_free(tx); } + +struct amount_sat psbt_compute_fee(struct wally_psbt *psbt) +{ + struct amount_sat fee, input_amt; + struct amount_asset asset; + bool ok; + + fee = AMOUNT_SAT(0); + for (size_t i = 0; i < psbt->num_inputs; i++) { + input_amt = psbt_input_get_amount(psbt, i); + ok = amount_sat_add(&fee, fee, input_amt); + assert(ok); + } + + for (size_t i = 0; i < psbt->num_outputs; i++) { + asset = wally_tx_output_get_amount(&psbt->tx->outputs[i]); + if (!amount_asset_is_main(&asset) + || elements_wtx_output_is_fee(psbt->tx, i)) + continue; + + ok = amount_sat_sub(&fee, fee, amount_asset_to_sat(&asset)); + if (!ok) + return AMOUNT_SAT(0); + } + + return fee; +} diff --git a/bitcoin/psbt.h b/bitcoin/psbt.h index 459eef93c..18b29862a 100644 --- a/bitcoin/psbt.h +++ b/bitcoin/psbt.h @@ -245,6 +245,12 @@ struct amount_sat psbt_input_get_amount(const struct wally_psbt *psbt, struct amount_sat psbt_output_get_amount(const struct wally_psbt *psbt, size_t out); +/* psbt_compute_fee - Returns value of fee for PSBT + * + * @psbt -psbt + */ +struct amount_sat psbt_compute_fee(struct wally_psbt *psbt); + /* psbt_has_input - Is this input present on this psbt * * @psbt - psbt