Skip to content

Commit 9eb5908

Browse files
committed
Add TaggedHash function (BIP 340)
This adds the TaggedHash function as defined by BIP340 to the hash module, which is used in BIP340 and BIP341 to produce domain-separated hashes.
1 parent 450d2b2 commit 9eb5908

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/hash.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <crypto/common.h>
77
#include <crypto/hmac_sha512.h>
88

9+
#include <string>
910

1011
inline uint32_t ROTL32(uint32_t x, int8_t r)
1112
{
@@ -84,3 +85,12 @@ uint256 SHA256Uint256(const uint256& input)
8485
CSHA256().Write(input.begin(), 32).Finalize(result.begin());
8586
return result;
8687
}
88+
89+
CHashWriter TaggedHash(const std::string& tag)
90+
{
91+
CHashWriter writer(SER_GETHASH, 0);
92+
uint256 taghash;
93+
CSHA256().Write((const unsigned char*)tag.data(), tag.size()).Finalize(taghash.begin());
94+
writer << taghash << taghash;
95+
return writer;
96+
}

src/hash.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include <uint256.h>
1616
#include <version.h>
1717

18+
#include <string>
1819
#include <vector>
1920

2021
typedef uint256 ChainCode;
@@ -202,4 +203,12 @@ unsigned int MurmurHash3(unsigned int nHashSeed, Span<const unsigned char> vData
202203

203204
void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]);
204205

206+
/** Return a CHashWriter primed for tagged hashes (as specified in BIP 340).
207+
*
208+
* The returned object will have SHA256(tag) written to it twice (= 64 bytes).
209+
* A tagged hash can be computed by feeding the message into this object, and
210+
* then calling CHashWriter::GetSHA256().
211+
*/
212+
CHashWriter TaggedHash(const std::string& tag);
213+
205214
#endif // BITCOIN_HASH_H

0 commit comments

Comments
 (0)