0
0
Fork 0
mirror of https://github.com/bitcoin/bitcoin.git synced 2025-03-10 15:46:48 -04:00

refactor: Replace ParseHashStr with FromHex

No need to have two functions with different names that achieve the
exact same thing.
This commit is contained in:
MarcoFalke 2024-07-18 22:54:38 +02:00
parent fa90777245
commit fa7b57e5f5
No known key found for this signature in database
7 changed files with 34 additions and 55 deletions

View file

@ -264,8 +264,8 @@ static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInpu
throw std::runtime_error("TX input missing separator"); throw std::runtime_error("TX input missing separator");
// extract and validate TXID // extract and validate TXID
uint256 txid; auto txid{Txid::FromHex(vStrInputParts[0])};
if (!ParseHashStr(vStrInputParts[0], txid)) { if (!txid) {
throw std::runtime_error("invalid TX input txid"); throw std::runtime_error("invalid TX input txid");
} }
@ -285,7 +285,7 @@ static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInpu
} }
// append to transaction input list // append to transaction input list
CTxIn txin(Txid::FromUint256(txid), vout, CScript(), nSequenceIn); CTxIn txin(*txid, vout, CScript(), nSequenceIn);
tx.vin.push_back(txin); tx.vin.push_back(txin);
} }
@ -625,8 +625,8 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
if (!prevOut.checkObject(types)) if (!prevOut.checkObject(types))
throw std::runtime_error("prevtxs internal object typecheck fail"); throw std::runtime_error("prevtxs internal object typecheck fail");
uint256 txid; auto txid{Txid::FromHex(prevOut["txid"].get_str())};
if (!ParseHashStr(prevOut["txid"].get_str(), txid)) { if (!txid) {
throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')"); throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')");
} }
@ -634,7 +634,7 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
if (nOut < 0) if (nOut < 0)
throw std::runtime_error("vout cannot be negative"); throw std::runtime_error("vout cannot be negative");
COutPoint out(Txid::FromUint256(txid), nOut); COutPoint out(*txid, nOut);
std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end()); CScript scriptPubKey(pkData.begin(), pkData.end());

View file

@ -37,15 +37,6 @@ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDeco
[[nodiscard]] bool DecodeHexBlk(CBlock&, const std::string& strHexBlk); [[nodiscard]] bool DecodeHexBlk(CBlock&, const std::string& strHexBlk);
bool DecodeHexBlockHeader(CBlockHeader&, const std::string& hex_header); bool DecodeHexBlockHeader(CBlockHeader&, const std::string& hex_header);
/**
* Parse a hex string into 256 bits
* @param[in] strHex a hex-formatted, 64-character string
* @param[out] result the result of the parsing
* @returns true if successful, false if not
*
* @see ParseHashV for an RPC-oriented version of this
*/
bool ParseHashStr(const std::string& strHex, uint256& result);
[[nodiscard]] util::Result<int> SighashFromStr(const std::string& sighash); [[nodiscard]] util::Result<int> SighashFromStr(const std::string& sighash);
// core_write.cpp // core_write.cpp

View file

@ -234,15 +234,6 @@ bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
return true; return true;
} }
bool ParseHashStr(const std::string& strHex, uint256& result)
{
if ((strHex.size() != 64) || !IsHex(strHex))
return false;
result.SetHexDeprecated(strHex);
return true;
}
util::Result<int> SighashFromStr(const std::string& sighash) util::Result<int> SighashFromStr(const std::string& sighash)
{ {
static const std::map<std::string, int> map_sighash_values = { static const std::map<std::string, int> map_sighash_values = {

View file

@ -217,9 +217,10 @@ static bool rest_headers(const std::any& context,
return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Header count is invalid or out of acceptable range (1-%u): %s", MAX_REST_HEADERS_RESULTS, raw_count)); return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Header count is invalid or out of acceptable range (1-%u): %s", MAX_REST_HEADERS_RESULTS, raw_count));
} }
uint256 hash; auto hash{uint256::FromHex(hashStr)};
if (!ParseHashStr(hashStr, hash)) if (!hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
}
const CBlockIndex* tip = nullptr; const CBlockIndex* tip = nullptr;
std::vector<const CBlockIndex*> headers; std::vector<const CBlockIndex*> headers;
@ -231,7 +232,7 @@ static bool rest_headers(const std::any& context,
LOCK(cs_main); LOCK(cs_main);
CChain& active_chain = chainman.ActiveChain(); CChain& active_chain = chainman.ActiveChain();
tip = active_chain.Tip(); tip = active_chain.Tip();
const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash); const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*hash)};
while (pindex != nullptr && active_chain.Contains(pindex)) { while (pindex != nullptr && active_chain.Contains(pindex)) {
headers.push_back(pindex); headers.push_back(pindex);
if (headers.size() == *parsed_count) { if (headers.size() == *parsed_count) {
@ -290,9 +291,10 @@ static bool rest_block(const std::any& context,
std::string hashStr; std::string hashStr;
const RESTResponseFormat rf = ParseDataFormat(hashStr, strURIPart); const RESTResponseFormat rf = ParseDataFormat(hashStr, strURIPart);
uint256 hash; auto hash{uint256::FromHex(hashStr)};
if (!ParseHashStr(hashStr, hash)) if (!hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
}
FlatFilePos pos{}; FlatFilePos pos{};
const CBlockIndex* pblockindex = nullptr; const CBlockIndex* pblockindex = nullptr;
@ -303,7 +305,7 @@ static bool rest_block(const std::any& context,
{ {
LOCK(cs_main); LOCK(cs_main);
tip = chainman.ActiveChain().Tip(); tip = chainman.ActiveChain().Tip();
pblockindex = chainman.m_blockman.LookupBlockIndex(hash); pblockindex = chainman.m_blockman.LookupBlockIndex(*hash);
if (!pblockindex) { if (!pblockindex) {
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
} }
@ -390,8 +392,8 @@ static bool rest_filter_header(const std::any& context, HTTPRequest* req, const
return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Header count is invalid or out of acceptable range (1-%u): %s", MAX_REST_HEADERS_RESULTS, raw_count)); return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Header count is invalid or out of acceptable range (1-%u): %s", MAX_REST_HEADERS_RESULTS, raw_count));
} }
uint256 block_hash; auto block_hash{uint256::FromHex(raw_blockhash)};
if (!ParseHashStr(raw_blockhash, block_hash)) { if (!block_hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + raw_blockhash); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + raw_blockhash);
} }
@ -413,7 +415,7 @@ static bool rest_filter_header(const std::any& context, HTTPRequest* req, const
ChainstateManager& chainman = *maybe_chainman; ChainstateManager& chainman = *maybe_chainman;
LOCK(cs_main); LOCK(cs_main);
CChain& active_chain = chainman.ActiveChain(); CChain& active_chain = chainman.ActiveChain();
const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block_hash); const CBlockIndex* pindex{chainman.m_blockman.LookupBlockIndex(*block_hash)};
while (pindex != nullptr && active_chain.Contains(pindex)) { while (pindex != nullptr && active_chain.Contains(pindex)) {
headers.push_back(pindex); headers.push_back(pindex);
if (headers.size() == *parsed_count) if (headers.size() == *parsed_count)
@ -494,8 +496,8 @@ static bool rest_block_filter(const std::any& context, HTTPRequest* req, const s
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilter/<filtertype>/<blockhash>"); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid URI format. Expected /rest/blockfilter/<filtertype>/<blockhash>");
} }
uint256 block_hash; auto block_hash{uint256::FromHex(uri_parts[1])};
if (!ParseHashStr(uri_parts[1], block_hash)) { if (!block_hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + uri_parts[1]); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + uri_parts[1]);
} }
@ -516,7 +518,7 @@ static bool rest_block_filter(const std::any& context, HTTPRequest* req, const s
if (!maybe_chainman) return false; if (!maybe_chainman) return false;
ChainstateManager& chainman = *maybe_chainman; ChainstateManager& chainman = *maybe_chainman;
LOCK(cs_main); LOCK(cs_main);
block_index = chainman.m_blockman.LookupBlockIndex(block_hash); block_index = chainman.m_blockman.LookupBlockIndex(*block_hash);
if (!block_index) { if (!block_index) {
return RESTERR(req, HTTP_NOT_FOUND, uri_parts[1] + " not found"); return RESTERR(req, HTTP_NOT_FOUND, uri_parts[1] + " not found");
} }
@ -616,14 +618,14 @@ static bool rest_deploymentinfo(const std::any& context, HTTPRequest* req, const
jsonRequest.params = UniValue(UniValue::VARR); jsonRequest.params = UniValue(UniValue::VARR);
if (!hash_str.empty()) { if (!hash_str.empty()) {
uint256 hash; auto hash{uint256::FromHex(hash_str)};
if (!ParseHashStr(hash_str, hash)) { if (!hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hash_str); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hash_str);
} }
const ChainstateManager* chainman = GetChainman(context, req); const ChainstateManager* chainman = GetChainman(context, req);
if (!chainman) return false; if (!chainman) return false;
if (!WITH_LOCK(::cs_main, return chainman->m_blockman.LookupBlockIndex(ParseHashV(hash_str, "blockhash")))) { if (!WITH_LOCK(::cs_main, return chainman->m_blockman.LookupBlockIndex(*hash))) {
return RESTERR(req, HTTP_BAD_REQUEST, "Block not found"); return RESTERR(req, HTTP_BAD_REQUEST, "Block not found");
} }
@ -704,9 +706,10 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string
std::string hashStr; std::string hashStr;
const RESTResponseFormat rf = ParseDataFormat(hashStr, strURIPart); const RESTResponseFormat rf = ParseDataFormat(hashStr, strURIPart);
uint256 hash; auto hash{uint256::FromHex(hashStr)};
if (!ParseHashStr(hashStr, hash)) if (!hash) {
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
}
if (g_txindex) { if (g_txindex) {
g_txindex->BlockUntilSyncedToCurrentChain(); g_txindex->BlockUntilSyncedToCurrentChain();
@ -715,7 +718,7 @@ static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string
const NodeContext* const node = GetNodeContext(context, req); const NodeContext* const node = GetNodeContext(context, req);
if (!node) return false; if (!node) return false;
uint256 hashBlock = uint256(); uint256 hashBlock = uint256();
const CTransactionRef tx = GetTransaction(/*block_index=*/nullptr, node->mempool.get(), hash, hashBlock, node->chainman->m_blockman); const CTransactionRef tx{GetTransaction(/*block_index=*/nullptr, node->mempool.get(), *hash, hashBlock, node->chainman->m_blockman)};
if (!tx) { if (!tx) {
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
} }

View file

@ -345,13 +345,11 @@ static RPCHelpMan generateblock()
std::vector<CTransactionRef> txs; std::vector<CTransactionRef> txs;
const auto raw_txs_or_txids = request.params[1].get_array(); const auto raw_txs_or_txids = request.params[1].get_array();
for (size_t i = 0; i < raw_txs_or_txids.size(); i++) { for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
const auto str(raw_txs_or_txids[i].get_str()); const auto& str{raw_txs_or_txids[i].get_str()};
uint256 hash;
CMutableTransaction mtx; CMutableTransaction mtx;
if (ParseHashStr(str, hash)) { if (auto hash{uint256::FromHex(str)}) {
const auto tx{mempool.get(*hash)};
const auto tx = mempool.get(hash);
if (!tx) { if (!tx) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str)); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
} }

View file

@ -149,8 +149,7 @@ BOOST_AUTO_TEST_CASE(blockfilters_json_test)
unsigned int pos = 0; unsigned int pos = 0;
/*int block_height =*/ test[pos++].getInt<int>(); /*int block_height =*/ test[pos++].getInt<int>();
uint256 block_hash; BOOST_CHECK(uint256::FromHex(test[pos++].get_str()));
BOOST_CHECK(ParseHashStr(test[pos++].get_str(), block_hash));
CBlock block; CBlock block;
BOOST_REQUIRE(DecodeHexBlk(block, test[pos++].get_str())); BOOST_REQUIRE(DecodeHexBlk(block, test[pos++].get_str()));
@ -165,11 +164,9 @@ BOOST_AUTO_TEST_CASE(blockfilters_json_test)
tx_undo.vprevout.emplace_back(txout, 0, false); tx_undo.vprevout.emplace_back(txout, 0, false);
} }
uint256 prev_filter_header_basic; uint256 prev_filter_header_basic{*Assert(uint256::FromHex(test[pos++].get_str()))};
BOOST_CHECK(ParseHashStr(test[pos++].get_str(), prev_filter_header_basic));
std::vector<unsigned char> filter_basic = ParseHex(test[pos++].get_str()); std::vector<unsigned char> filter_basic = ParseHex(test[pos++].get_str());
uint256 filter_header_basic; uint256 filter_header_basic{*Assert(uint256::FromHex(test[pos++].get_str()))};
BOOST_CHECK(ParseHashStr(test[pos++].get_str(), filter_header_basic));
BlockFilter computed_filter_basic(BlockFilterType::BASIC, block, block_undo); BlockFilter computed_filter_basic(BlockFilterType::BASIC, block, block_undo);
BOOST_CHECK(computed_filter_basic.GetFilter().GetEncoded() == filter_basic); BOOST_CHECK(computed_filter_basic.GetFilter().GetEncoded() == filter_basic);

View file

@ -27,8 +27,7 @@ FUZZ_TARGET(hex)
assert(ToLower(random_hex_string) == hex_data); assert(ToLower(random_hex_string) == hex_data);
} }
(void)IsHexNumber(random_hex_string); (void)IsHexNumber(random_hex_string);
uint256 result; (void)uint256::FromHex(random_hex_string);
(void)ParseHashStr(random_hex_string, result);
(void)uint256S(random_hex_string); (void)uint256S(random_hex_string);
try { try {
(void)HexToPubKey(random_hex_string); (void)HexToPubKey(random_hex_string);