merge bitcoin#19326: Simplify hash.h interface using Spans

includes:
- 2a2182c387f607cd8284f33890bd285a81077b7f
- 77c507358bda9bd6c496f33e0f4418c0603bb08d

completion of partial merge done in dash#4164 as 56f1b2d (blocker
bitcoin#17938 was merged in dash#5246 as 00802bb)
This commit is contained in:
Kittywhiskers Van Gogh 2023-09-08 19:04:57 +05:30 committed by PastaPastaPasta
parent 7ddf2ff59b
commit 65ff12c303
18 changed files with 41 additions and 61 deletions

View File

@ -136,7 +136,7 @@ std::string EncodeBase58Check(Span<const unsigned char> input)
{ {
// add 4-byte hash check to the end // add 4-byte hash check to the end
std::vector<unsigned char> vch(input.begin(), input.end()); std::vector<unsigned char> vch(input.begin(), input.end());
uint256 hash = Hash(vch.begin(), vch.end()); uint256 hash = Hash(vch);
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch); return EncodeBase58(vch);
} }
@ -149,7 +149,7 @@ bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet, int
return false; return false;
} }
// re-calculate the checksum, ensure it matches the included 4-byte checksum // re-calculate the checksum, ensure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); uint256 hash = Hash(MakeSpan(vchRet).first(vchRet.size() - 4));
if (memcmp(&hash, &vchRet[vchRet.size() - 4], 4) != 0) { if (memcmp(&hash, &vchRet[vchRet.size() - 4], 4) != 0) {
vchRet.clear(); vchRet.clear();
return false; return false;

View File

@ -47,7 +47,7 @@ private:
ssObj << strMagicMessage; // specific magic message for this type of object ssObj << strMagicMessage; // specific magic message for this type of object
ssObj << Params().MessageStart(); // network specific magic number ssObj << Params().MessageStart(); // network specific magic number
ssObj << objToSave; ssObj << objToSave;
uint256 hash = Hash(ssObj.begin(), ssObj.end()); uint256 hash = Hash(ssObj);
ssObj << hash; ssObj << hash;
// open output file, and associate with CAutoFile // open output file, and associate with CAutoFile
@ -109,7 +109,7 @@ private:
CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data // verify stored checksum matches input data
uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); uint256 hashTmp = Hash(ssObj);
if (hashIn != hashTmp) if (hashIn != hashTmp)
{ {
error("%s: Checksum mismatch, data corrupted", __func__); error("%s: Checksum mismatch, data corrupted", __func__);

View File

@ -84,52 +84,31 @@ public:
}; };
/** Compute the 256-bit hash of an object. */ /** Compute the 256-bit hash of an object. */
template<typename T1> template<typename T>
inline uint256 Hash(const T1 pbegin, const T1 pend) inline uint256 Hash(const T& in1)
{ {
static const unsigned char pblank[1] = {};
uint256 result; uint256 result;
CHash256().Write({pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0])}) CHash256().Write(MakeUCharSpan(in1)).Finalize(result);
.Finalize(result);
return result; return result;
} }
/** Compute the 256-bit hash of the concatenation of two objects. */ /** Compute the 256-bit hash of the concatenation of two objects. */
template<typename T1, typename T2> template<typename T1, typename T2>
inline uint256 Hash(const T1 p1begin, const T1 p1end, inline uint256 Hash(const T1& in1, const T2& in2) {
const T2 p2begin, const T2 p2end) {
static const unsigned char pblank[1] = {};
uint256 result; uint256 result;
CHash256().Write({p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])}) CHash256().Write(MakeUCharSpan(in1)).Write(MakeUCharSpan(in2)).Finalize(result);
.Write({p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])})
.Finalize(result);
return result; return result;
} }
/** Compute the 160-bit hash an object. */ /** Compute the 160-bit hash an object. */
template<typename T1> template<typename T1>
inline uint160 Hash160(const T1 pbegin, const T1 pend) inline uint160 Hash160(const T1& in1)
{ {
static unsigned char pblank[1] = {};
uint160 result; uint160 result;
CHash160().Write({pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0])}) CHash160().Write(MakeUCharSpan(in1)).Finalize(result);
.Finalize(result);
return result; return result;
} }
/** Compute the 160-bit hash of a vector. */
inline uint160 Hash160(const std::vector<unsigned char>& vch)
{
return Hash160(vch.begin(), vch.end());
}
/** Compute the 160-bit hash of a vector. */
template<unsigned int N>
inline uint160 Hash160(const prevector<N, unsigned char>& vch)
{
return Hash160(vch.begin(), vch.end());
}
/** A writer stream (for serialization) that computes a 256-bit hash. */ /** A writer stream (for serialization) that computes a 256-bit hash. */
class CHashWriter class CHashWriter
{ {

View File

@ -153,7 +153,7 @@ SecureVector CHDChain::GetSeed() const
uint256 CHDChain::GetSeedHash() uint256 CHDChain::GetSeedHash()
{ {
LOCK(cs); LOCK(cs);
return Hash(vchSeed.begin(), vchSeed.end()); return Hash(vchSeed);
} }
void CHDChain::DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey& extKeyRet, KeyOriginInfo& key_origin) void CHDChain::DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey& extKeyRet, KeyOriginInfo& key_origin)

View File

@ -84,7 +84,7 @@ uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::ve
else else
right = left; right = left;
// combine subhashes // combine subhashes
return Hash(left.begin(), left.end(), right.begin(), right.end()); return Hash(left, right);
} }
} }
@ -140,7 +140,7 @@ uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, uns
right = left; right = left;
} }
// and combine them before returning // and combine them before returning
return Hash(left.begin(), left.end(), right.begin(), right.end()); return Hash(left, right);
} }
} }

View File

@ -850,7 +850,7 @@ std::optional<CNetMessage> V1TransportDeserializer::GetMessage(int64_t time, uin
void V1TransportSerializer::prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) { void V1TransportSerializer::prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) {
// create dbl-sha256 checksum // create dbl-sha256 checksum
uint256 hash = Hash(msg.data.begin(), msg.data.end()); uint256 hash = Hash(msg.data);
// create header // create header
CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), msg.data.size()); CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), msg.data.size());

View File

@ -830,7 +830,7 @@ std::vector<unsigned char> CNetAddr::GetAddrBytes() const
uint64_t CNetAddr::GetHash() const uint64_t CNetAddr::GetHash() const
{ {
uint256 hash = Hash(m_addr.begin(), m_addr.end()); uint256 hash = Hash(m_addr);
uint64_t nRet; uint64_t nRet;
memcpy(&nRet, &hash, sizeof(nRet)); memcpy(&nRet, &hash, sizeof(nRet));
return nRet; return nRet;

View File

@ -157,13 +157,13 @@ public:
//! Get the KeyID of this public key (hash of its serialization) //! Get the KeyID of this public key (hash of its serialization)
CKeyID GetID() const CKeyID GetID() const
{ {
return CKeyID(Hash160(vch, vch + size())); return CKeyID(Hash160(MakeSpan(vch).first(size())));
} }
//! Get the 256-bit hash of this public key. //! Get the 256-bit hash of this public key.
uint256 GetHash() const uint256 GetHash() const
{ {
return Hash(vch, vch + size()); return Hash(MakeSpan(vch).first(size()));
} }
/* /*

View File

@ -13,10 +13,10 @@ typedef std::vector<unsigned char> valtype;
bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER;
unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;
CScriptID::CScriptID(const CScript& in) : BaseHash(Hash160(in.begin(), in.end())) {} CScriptID::CScriptID(const CScript& in) : BaseHash(Hash160(in)) {}
CScriptID::CScriptID(const ScriptHash& in) : BaseHash(static_cast<uint160>(in)) {} CScriptID::CScriptID(const ScriptHash& in) : BaseHash(static_cast<uint160>(in)) {}
ScriptHash::ScriptHash(const CScript& in) : BaseHash(Hash160(in.begin(), in.end())) {} ScriptHash::ScriptHash(const CScript& in) : BaseHash(Hash160(in)) {}
ScriptHash::ScriptHash(const CScriptID& in) : BaseHash(static_cast<uint160>(in)) {} ScriptHash::ScriptHash(const CScriptID& in) : BaseHash(static_cast<uint160>(in)) {}
PKHash::PKHash(const CPubKey& pubkey) : BaseHash(pubkey.GetID()) {} PKHash::PKHash(const CPubKey& pubkey) : BaseHash(pubkey.GetID()) {}
@ -242,7 +242,6 @@ CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
return script; return script;
} }
bool IsValidDestination(const CTxDestination& dest) { bool IsValidDestination(const CTxDestination& dest) {
return dest.index() != 0; return dest.index() != 0;
} }

View File

@ -62,8 +62,8 @@ FUZZ_TARGET(crypto)
(void)sha512.Write(data.data(), data.size()); (void)sha512.Write(data.data(), data.size());
(void)sip_hasher.Write(data.data(), data.size()); (void)sip_hasher.Write(data.data(), data.size());
(void)Hash(data);
(void)Hash160(data); (void)Hash160(data);
(void)Hash160(data.begin(), data.end());
(void)sha512.Size(); (void)sha512.Size();
}, },
[&] { [&] {

View File

@ -81,7 +81,7 @@ FUZZ_TARGET_INIT(key, initialize_key)
assert(negated_key == key); assert(negated_key == key);
} }
const uint256 random_uint256 = Hash(buffer.begin(), buffer.end()); const uint256 random_uint256 = Hash(buffer);
{ {
CKey child_key; CKey child_key;

View File

@ -77,7 +77,7 @@ BOOST_AUTO_TEST_CASE(key_test1)
for (int n=0; n<16; n++) for (int n=0; n<16; n++)
{ {
std::string strMsg = strprintf("Very secret message %i: 11", n); std::string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); uint256 hashMsg = Hash(strMsg);
// normal signatures // normal signatures
@ -134,7 +134,7 @@ BOOST_AUTO_TEST_CASE(key_test1)
std::vector<unsigned char> detsig, detsigc; std::vector<unsigned char> detsig, detsigc;
std::string strMsg = "Very deterministic message"; std::string strMsg = "Very deterministic message";
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); uint256 hashMsg = Hash(strMsg);
BOOST_CHECK(key1.Sign(hashMsg, detsig)); BOOST_CHECK(key1.Sign(hashMsg, detsig));
BOOST_CHECK(key1C.Sign(hashMsg, detsigc)); BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc); BOOST_CHECK(detsig == detsigc);
@ -158,7 +158,7 @@ BOOST_AUTO_TEST_CASE(key_signature_tests)
// When entropy is specified, we should see at least one high R signature within 20 signatures // When entropy is specified, we should see at least one high R signature within 20 signatures
CKey key = DecodeSecret(strSecret1); CKey key = DecodeSecret(strSecret1);
std::string msg = "A message to be signed"; std::string msg = "A message to be signed";
uint256 msg_hash = Hash(msg.begin(), msg.end()); uint256 msg_hash = Hash(msg);
std::vector<unsigned char> sig; std::vector<unsigned char> sig;
bool found = false; bool found = false;
@ -179,7 +179,7 @@ BOOST_AUTO_TEST_CASE(key_signature_tests)
for (int i = 0; i < 256; ++i) { for (int i = 0; i < 256; ++i) {
sig.clear(); sig.clear();
std::string msg = "A message to be signed" + ToString(i); std::string msg = "A message to be signed" + ToString(i);
msg_hash = Hash(msg.begin(), msg.end()); msg_hash = Hash(msg);
BOOST_CHECK(key.Sign(msg_hash, sig)); BOOST_CHECK(key.Sign(msg_hash, sig));
found = sig[3] == 0x20; found = sig[3] == 0x20;
BOOST_CHECK(sig.size() <= 70); BOOST_CHECK(sig.size() <= 70);

View File

@ -13,9 +13,9 @@ static uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vecto
uint256 hash = leaf; uint256 hash = leaf;
for (std::vector<uint256>::const_iterator it = vMerkleBranch.begin(); it != vMerkleBranch.end(); ++it) { for (std::vector<uint256>::const_iterator it = vMerkleBranch.begin(); it != vMerkleBranch.end(); ++it) {
if (nIndex & 1) { if (nIndex & 1) {
hash = Hash(it->begin(), it->end(), hash.begin(), hash.end()); hash = Hash(*it, hash);
} else { } else {
hash = Hash(hash.begin(), hash.end(), it->begin(), it->end()); hash = Hash(hash, *it);
} }
nIndex >>= 1; nIndex >>= 1;
} }
@ -144,8 +144,7 @@ static uint256 BlockBuildMerkleTree(const CBlock& block, bool* fMutated, std::ve
// Two identical hashes at the end of the list at a particular level. // Two identical hashes at the end of the list at a particular level.
mutated = true; mutated = true;
} }
vMerkleTree.push_back(Hash(vMerkleTree[j+i].begin(), vMerkleTree[j+i].end(), vMerkleTree.push_back(Hash(vMerkleTree[j+i], vMerkleTree[j+i2]));
vMerkleTree[j+i2].begin(), vMerkleTree[j+i2].end()));
} }
j += nSize; j += nSize;
} }

View File

@ -145,7 +145,7 @@ BOOST_AUTO_TEST_CASE(floats)
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
ss << float(i); ss << float(i);
} }
BOOST_CHECK(Hash(ss.begin(), ss.end()) == uint256S("8e8b4cf3e4df8b332057e3e23af42ebc663b61e0495d5e7e32d85099d7f3fe0c")); BOOST_CHECK(Hash(ss) == uint256S("8e8b4cf3e4df8b332057e3e23af42ebc663b61e0495d5e7e32d85099d7f3fe0c"));
// decode // decode
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
@ -162,7 +162,7 @@ BOOST_AUTO_TEST_CASE(doubles)
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
ss << double(i); ss << double(i);
} }
BOOST_CHECK(Hash(ss.begin(), ss.end()) == uint256S("43d0c82591953c4eafe114590d392676a01585d25b25d433557f0d7878b23f96")); BOOST_CHECK(Hash(ss) == uint256S("43d0c82591953c4eafe114590d392676a01585d25b25d433557f0d7878b23f96"));
// decode // decode
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {

View File

@ -2576,8 +2576,8 @@ BOOST_AUTO_TEST_CASE(message_hash)
std::string(1, (char)unsigned_tx.length()) + std::string(1, (char)unsigned_tx.length()) +
unsigned_tx; unsigned_tx;
const uint256 signature_hash = Hash(unsigned_tx.begin(), unsigned_tx.end()); const uint256 signature_hash = Hash(unsigned_tx);
const uint256 message_hash1 = Hash(prefixed_message.begin(), prefixed_message.end()); const uint256 message_hash1 = Hash(prefixed_message);
const uint256 message_hash2 = MessageHash(unsigned_tx); const uint256 message_hash2 = MessageHash(unsigned_tx);
BOOST_CHECK_EQUAL(message_hash1, message_hash2); BOOST_CHECK_EQUAL(message_hash1, message_hash2);

View File

@ -64,6 +64,9 @@ public:
{ {
return m_hash.size(); return m_hash.size();
} }
unsigned char* data() { return m_hash.data(); }
const unsigned char* data() const { return m_hash.data(); }
}; };
#endif // BITCOIN_UTIL_HASH_TYPE_H #endif // BITCOIN_UTIL_HASH_TYPE_H

View File

@ -1323,7 +1323,7 @@ static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
CPubKey pubkey = key.GetPubKey(); CPubKey pubkey = key.GetPubKey();
// Generate pubkey hash // Generate pubkey hash
uint160 key_hash(Hash160(pubkey.begin(), pubkey.end())); uint160 key_hash(Hash160(pubkey));
// Create inner-script to enter into keystore. Key hash can't be 0... // Create inner-script to enter into keystore. Key hash can't be 0...
CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end()); CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());

View File

@ -113,7 +113,7 @@ bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey,
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end()); vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false); return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey)), false);
} }
bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey, bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
@ -125,7 +125,7 @@ bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
} }
// Compute a checksum of the encrypted key // Compute a checksum of the encrypted key
uint256 checksum = Hash(vchCryptedSecret.begin(), vchCryptedSecret.end()); uint256 checksum = Hash(vchCryptedSecret);
const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey); const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) { if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
@ -339,7 +339,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end()); vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash) if (Hash(vchKey) != hash)
{ {
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt"; strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false; return false;
@ -388,7 +388,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
if (!ssValue.eof()) { if (!ssValue.eof()) {
uint256 checksum; uint256 checksum;
ssValue >> checksum; ssValue >> checksum;
if ((checksum_valid = Hash(vchPrivKey.begin(), vchPrivKey.end()) != checksum)) { if ((checksum_valid = Hash(vchPrivKey) != checksum)) {
strErr = "Error reading wallet database: Crypted key corrupt"; strErr = "Error reading wallet database: Crypted key corrupt";
return false; return false;
} }