From 772a960c415bcd3223cff870b4a1c31f7a81ba81 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Tue, 12 Apr 2016 13:07:04 +0930 Subject: [PATCH] tx: add measure_tx_len() helper. We currently linearize and then measure the string; this is better since we're about to do it in a second place. Signed-off-by: Rusty Russell --- bitcoin/tx.c | 12 ++++++++++++ bitcoin/tx.h | 3 +++ daemon/peer.c | 6 ++---- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/bitcoin/tx.c b/bitcoin/tx.c index 8a1d7e60c..8bd8ef436 100644 --- a/bitcoin/tx.c +++ b/bitcoin/tx.c @@ -295,6 +295,18 @@ u8 *linearize_tx_force_extended(const tal_t *ctx, return arr; } +static void add_measure(const void *data, size_t len, void *lenp) +{ + *(size_t *)lenp += len; +} + +size_t measure_tx_len(const struct bitcoin_tx *tx) +{ + size_t len = 0; + add_tx(tx, add_measure, &len, uses_witness(tx)); + return len; +} + void bitcoin_txid(const struct bitcoin_tx *tx, struct sha256_double *txid) { struct sha256_ctx ctx = SHA256_INIT; diff --git a/bitcoin/tx.h b/bitcoin/tx.h index b4b75712a..5f6e8ff61 100644 --- a/bitcoin/tx.h +++ b/bitcoin/tx.h @@ -53,6 +53,9 @@ u8 *linearize_tx(const tal_t *ctx, const struct bitcoin_tx *tx); u8 *linearize_tx_force_extended(const tal_t *ctx, const struct bitcoin_tx *tx); +/* Get length of tx in bytes. */ +size_t measure_tx_len(const struct bitcoin_tx *tx); + /* Allocate a tx: you just need to fill in inputs and outputs (they're * zeroed with inputs' sequence_number set to FFFFFFFF) */ struct bitcoin_tx *bitcoin_tx(const tal_t *ctx, varint_t input_count, diff --git a/daemon/peer.c b/daemon/peer.c index 7bae33d41..4c5209f65 100644 --- a/daemon/peer.c +++ b/daemon/peer.c @@ -1105,7 +1105,7 @@ const struct bitcoin_tx *bitcoin_close(struct peer *peer) /* Create a bitcoin spend tx (to spend our commit's outputs) */ const struct bitcoin_tx *bitcoin_spend_ours(struct peer *peer) { - u8 *redeemscript, *linear; + u8 *redeemscript; const struct bitcoin_tx *commit = peer->us.commit->tx; struct bitcoin_signature sig; struct bitcoin_tx *tx; @@ -1146,10 +1146,8 @@ const struct bitcoin_tx *bitcoin_spend_ours(struct peer *peer) /* Now, calculate the fee, given length. */ /* FIXME: Dynamic fees! */ - linear = linearize_tx(peer, tx); - fee = fee_by_feerate(tal_count(linear), + fee = fee_by_feerate(measure_tx_len(tx), peer->dstate->config.closing_fee_rate); - tal_free(linear); /* FIXME: Fail gracefully in these cases (not worth collecting) */ if (fee > tx->output[0].amount