Skip to content

Commit

Permalink
Add bip340 tagged hash functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
instagibbs committed Dec 5, 2022
1 parent 38b85bf commit dfa8d28
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
14 changes: 14 additions & 0 deletions include/wally_crypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,20 @@ WALLY_CORE_API int wally_sha512(
unsigned char *bytes_out,
size_t len);

/**
* BIP340 tagged hash: SHA-256(SHA-256(tag) || SHA-256(tag) || m)
*
* :param bytes: The message to hash.
* :param bytes_len: The length of ``bytes`` in bytes.
* :param tag: The BIP340 UTF-8 domain tag.
* :param bytes_out: Destination for the resulting 32-byte hash.
*/
WALLY_CORE_API int wally_tagged_hash(
const unsigned char *bytes,
size_t bytes_len,
const char *tag,
unsigned char *hash_out);

/** Output length for `wally_ripemd160` */
#define RIPEMD160_LEN 20

Expand Down
22 changes: 22 additions & 0 deletions src/internal.c
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,28 @@ int wally_bzero(void *bytes, size_t len)
return WALLY_OK;
}

int wally_tagged_hash(const unsigned char *bytes, size_t bytes_len,
const char *tag, unsigned char *hash_out)
{
struct sha256 sha;
struct sha256_ctx ctx;

if ((!bytes && bytes_len != 0) || !hash_out)
return WALLY_EINVAL;

/* SHA256(SHA256(tag) || SHA256(tag) || msg) */
sha256(&sha, tag, strlen(tag));
sha256_init(&ctx);
sha256_update(&ctx, &sha, sizeof(sha));
sha256_update(&ctx, &sha, sizeof(sha));
sha256_update(&ctx, bytes, bytes_len);
sha256_done(&ctx, &sha);

memcpy(hash_out, &sha, sizeof(sha));
wally_clear(&sha, sizeof(sha));
return WALLY_OK;
}

int wally_sha256(const unsigned char *bytes, size_t bytes_len,
unsigned char *bytes_out, size_t len)
{
Expand Down

0 comments on commit dfa8d28

Please sign in to comment.