core-lightning/common/close_tx.c
Christian Decker 42a63e4416 tx: Strengthen transaction construction checks
We roll the `elements_add_fee_output` function and the cropping of
overallocated arrays into the `bitcoin_tx_finalize` function. This is supposed
to be the final cleanup and compaction step before a tx can be sent to bitcoin
or passed off to other daemons.

This is the cleanup promised in #3491
2020-03-24 09:52:33 +10:30

68 lines
1.7 KiB
C

#include "bitcoin/script.h"
#include "bitcoin/tx.h"
#include "close_tx.h"
#include "permute_tx.h"
#include <assert.h>
#include <common/utils.h>
struct bitcoin_tx *create_close_tx(const tal_t *ctx,
const struct chainparams *chainparams,
const u8 *our_script,
const u8 *their_script,
const struct bitcoin_txid *anchor_txid,
unsigned int anchor_index,
struct amount_sat funding,
struct amount_sat to_us,
struct amount_sat to_them,
struct amount_sat dust_limit)
{
struct bitcoin_tx *tx;
size_t num_outputs = 0;
struct amount_sat total_out;
u8 *script;
assert(amount_sat_add(&total_out, to_us, to_them));
assert(amount_sat_less_eq(total_out, funding));
/* BOLT #3:
*
* ## Closing Transaction
*
* Note that there are two possible variants for each node.
*
* * version: 2
* * locktime: 0
* * txin count: 1
*/
/* Now create close tx: one input, two outputs. */
tx = bitcoin_tx(ctx, chainparams, 1, 2, 0);
/* Our input spends the anchor tx output. */
bitcoin_tx_add_input(tx, anchor_txid, anchor_index,
BITCOIN_TX_DEFAULT_SEQUENCE, funding, NULL);
if (amount_sat_greater_eq(to_us, dust_limit)) {
script = tal_dup_talarr(tx, u8, our_script);
/* One output is to us. */
bitcoin_tx_add_output(tx, script, to_us);
num_outputs++;
}
if (amount_sat_greater_eq(to_them, dust_limit)) {
script = tal_dup_talarr(tx, u8, their_script);
/* Other output is to them. */
bitcoin_tx_add_output(tx, script, to_them);
num_outputs++;
}
/* Can't have no outputs at all! */
if (num_outputs == 0)
return tal_free(tx);
permute_outputs(tx, NULL, NULL);
bitcoin_tx_finalize(tx);
assert(bitcoin_tx_check(tx));
return tx;
}