Skip to content

Commit 8fc41b9

Browse files
committed
tx_io: avoid caching sha256 context for external sha256 impls
For example, mbedtls hardware hashing requires (at least) semaphore initialization/aquisition performed by sha256_init() to be done before the context is considered valid. Openssl with HW hashers is likely the same for at least some configs. so, for non-standard setups like these, avoid caching the initial bip340 tagged hash context. Many thanks to github users @advorzhak and @hazrulnizam for helping to reproduce the issue!
1 parent abbe82a commit 8fc41b9

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

src/tx_io.c

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@
1010

1111
#define SIGTYPE_ALL (WALLY_SIGTYPE_PRE_SW | WALLY_SIGTYPE_SW_V0 | WALLY_SIGTYPE_SW_V1)
1212

13+
#if defined(CCAN_CRYPTO_SHA256_USE_OPENSSL) || defined(CCAN_CRYPTO_SHA256_USE_MBEDTLS)
14+
/* For external sha256 implementations, we cannot cache the sha256 context as
15+
* they require extra setup before use that only sha256_init() provides.
16+
*/
17+
#define TXIO_CTX_CACHEABLE 0
18+
#else
19+
/* For our built-in sha256 implementation we can cache and use the context */
20+
#define TXIO_CTX_CACHEABLE 1
21+
#endif
22+
1323
/* Cache keys for data that is constant while signing a given tx.
1424
* We also cache other data keyed by their binary value directly.
1525
*/
@@ -761,20 +771,22 @@ static int bip143_signature_hash(
761771
static void txio_bip341_init(cursor_io *io,
762772
const unsigned char *genesis_blockhash, size_t genesis_blockhash_len)
763773
{
764-
const struct wally_map_item *item;
765-
item = io->cache ? wally_map_get_integer(io->cache, TXIO_SHA_TAPSIGHASH_CTX) : NULL;
766-
if (item) {
767-
/* Note we hash the intial sha256_ctx itself here and so memcpy it */
768-
memcpy(&io->ctx, item->value, item->value_len);
769-
return;
774+
if (TXIO_CTX_CACHEABLE && io->cache) {
775+
const struct wally_map_item *item = NULL;
776+
item = wally_map_get_integer(io->cache, TXIO_SHA_TAPSIGHASH_CTX);
777+
if (item) {
778+
/* Note we cached the intial sha256_ctx itself here and so memcpy it */
779+
memcpy(&io->ctx, item->value, item->value_len);
780+
return;
781+
}
770782
}
771783

772784
tagged_hash_init(&io->ctx, TAPSIGHASH_SHA256(genesis_blockhash != NULL), SHA256_LEN);
773785
if (genesis_blockhash) {
774786
hash_bytes(&io->ctx, genesis_blockhash, genesis_blockhash_len);
775787
hash_bytes(&io->ctx, genesis_blockhash, genesis_blockhash_len);
776788
}
777-
if (io->cache)
789+
if (TXIO_CTX_CACHEABLE && io->cache)
778790
wally_map_add_integer(io->cache, TXIO_SHA_TAPSIGHASH_CTX,
779791
(const unsigned char*)&io->ctx, sizeof(io->ctx));
780792
}

0 commit comments

Comments
 (0)