Skip to content

Commit

Permalink
core: Add a function check if a script is P2WSH without allocating
Browse files Browse the repository at this point in the history
Processing blocks is rather slow at the moment, but one thing we can
do, is to prevent copying all output scripts, when really all we are
interested in are the couple of outputs that are P2WSH.

This builds the foundation of that by adding a method to introspect
the script without having to clone it first, saving us some
allocations, and deallocations.

Changelog-Changed: core: Processing blocks should now be faster
  • Loading branch information
cdecker committed Feb 21, 2024
1 parent 052542e commit c329756
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
3 changes: 0 additions & 3 deletions bitcoin/script.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@
#include <common/utils.h>
#include <sodium/randombytes.h>

/* To push 0-75 bytes onto stack. */
#define OP_PUSHBYTES(val) (val)

/* Bitcoin's OP_HASH160 is RIPEMD(SHA256()) */
static void hash160(struct ripemd160 *redeemhash, const void *mem, size_t len)
{
Expand Down
3 changes: 3 additions & 0 deletions bitcoin/script.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ struct ripemd160;
struct rel_locktime;
struct abs_locktime;

/* To push 0-75 bytes onto stack. */
#define OP_PUSHBYTES(val) (val)

/* tal_count() gives the length of the script. */
u8 *bitcoin_redeem_2of2(const tal_t *ctx,
const struct pubkey *key1,
Expand Down
10 changes: 10 additions & 0 deletions bitcoin/tx.c
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,16 @@ const u8 *bitcoin_tx_output_get_script(const tal_t *ctx,
return cln_wally_tx_output_get_script(ctx, output);
}

bool bitcoin_tx_output_script_is_p2wsh(const struct bitcoin_tx *tx, int outnum)
{ const struct wally_tx_output *output;
assert(outnum < tx->wtx->num_outputs);
output = &tx->wtx->outputs[outnum];

return output->script_len == BITCOIN_SCRIPTPUBKEY_P2WSH_LEN &&
output->script[0] == OP_0 &&
output->script[1] == OP_PUSHBYTES(sizeof(struct sha256));
}

u8 *bitcoin_tx_output_get_witscript(const tal_t *ctx, const struct bitcoin_tx *tx,
int outnum)
{
Expand Down
8 changes: 8 additions & 0 deletions bitcoin/tx.h
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,14 @@ void bitcoin_tx_output_set_amount(struct bitcoin_tx *tx, int outnum,
*/
const u8 *bitcoin_tx_output_get_script(const tal_t *ctx, const struct bitcoin_tx *tx, int outnum);

/**
* Return `true` if the given output is a P2WSH output.
*
* This is useful if you want to peek at the script, without having to
* extract it first.
*/
bool bitcoin_tx_output_script_is_p2wsh(const struct bitcoin_tx *tx, int outnum);

/**
* Helper to get the script of a script's output as a tal_arr
*
Expand Down

0 comments on commit c329756

Please sign in to comment.