Skip to content

Commit 94ddc2d

Browse files
committed
Merge bitcoin#34113: refactor: [rpc] Remove confusing and brittle integral casts
fa66e2d refactor: [rpc] Remove confusing and brittle integral casts (MarcoFalke) Pull request description: When constructing an UniValue from integral values, historically (long ago), in some cases casts where needed. With the current UniValue constructor, only very few are actually needed. Keeping the unused casts around is: * confusing, because code readers do not understand why they are needed * brittle, because some may copy them into new places, where they will lead to hard-to-find logic bugs, such as the ones fixed in pull bitcoin#34112 So fix all issues by removing them, except for a few cases, where casting was required: * `ret.pushKV("coinbase", static_cast<bool>(coin->fCoinBase));`, or * `static_cast<std::underlying_type_t<decltype(info.nServices)>>(info.nServices)`. This hardening refactor does not fix any bugs and does not change any behavior. ACKs for top commit: sedited: ACK fa66e2d rkrux: ACK fa66e2d Tree-SHA512: 13c9c59ad021ea03cdabe10d58850cef96d792634c499e62227cc2e7e5cace066ebd9a8ef3f979eaba98cadf8a525c6e6df909a07115559c0450bd9fc3a9763e
2 parents c575990 + fa66e2d commit 94ddc2d

File tree

9 files changed

+36
-36
lines changed

9 files changed

+36
-36
lines changed

src/rpc/blockchain.cpp

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,10 +1084,10 @@ static RPCHelpMan gettxoutsetinfo()
10841084
const std::optional<CCoinsStats> maybe_stats = GetUTXOStats(coins_view, *blockman, hash_type, node.rpc_interruption_point, pindex, index_requested);
10851085
if (maybe_stats.has_value()) {
10861086
const CCoinsStats& stats = maybe_stats.value();
1087-
ret.pushKV("height", (int64_t)stats.nHeight);
1087+
ret.pushKV("height", stats.nHeight);
10881088
ret.pushKV("bestblock", stats.hashBlock.GetHex());
1089-
ret.pushKV("txouts", (int64_t)stats.nTransactionOutputs);
1090-
ret.pushKV("bogosize", (int64_t)stats.nBogoSize);
1089+
ret.pushKV("txouts", stats.nTransactionOutputs);
1090+
ret.pushKV("bogosize", stats.nBogoSize);
10911091
if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
10921092
ret.pushKV("hash_serialized_3", stats.hashSerialized.GetHex());
10931093
}
@@ -1217,13 +1217,13 @@ static RPCHelpMan gettxout()
12171217
if (coin->nHeight == MEMPOOL_HEIGHT) {
12181218
ret.pushKV("confirmations", 0);
12191219
} else {
1220-
ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin->nHeight + 1));
1220+
ret.pushKV("confirmations", pindex->nHeight - coin->nHeight + 1);
12211221
}
12221222
ret.pushKV("value", ValueFromAmount(coin->out.nValue));
12231223
UniValue o(UniValue::VOBJ);
12241224
ScriptToUniv(coin->out.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
12251225
ret.pushKV("scriptPubKey", std::move(o));
1226-
ret.pushKV("coinbase", (bool)coin->fCoinBase);
1226+
ret.pushKV("coinbase", static_cast<bool>(coin->fCoinBase));
12271227

12281228
return ret;
12291229
},
@@ -1823,7 +1823,7 @@ static RPCHelpMan getchaintxstats()
18231823
const int64_t nTimeDiff{pindex->GetMedianTimePast() - past_block.GetMedianTimePast()};
18241824

18251825
UniValue ret(UniValue::VOBJ);
1826-
ret.pushKV("time", (int64_t)pindex->nTime);
1826+
ret.pushKV("time", pindex->nTime);
18271827
if (pindex->m_chain_tx_count) {
18281828
ret.pushKV("txcount", pindex->m_chain_tx_count);
18291829
}
@@ -2119,7 +2119,7 @@ static RPCHelpMan getblockstats()
21192119
ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
21202120
ret_all.pushKV("blockhash", pindex.GetBlockHash().GetHex());
21212121
ret_all.pushKV("feerate_percentiles", std::move(feerates_res));
2122-
ret_all.pushKV("height", (int64_t)pindex.nHeight);
2122+
ret_all.pushKV("height", pindex.nHeight);
21232123
ret_all.pushKV("ins", inputs);
21242124
ret_all.pushKV("maxfee", maxfee);
21252125
ret_all.pushKV("maxfeerate", maxfeerate);
@@ -2140,7 +2140,7 @@ static RPCHelpMan getblockstats()
21402140
ret_all.pushKV("total_size", total_size);
21412141
ret_all.pushKV("total_weight", total_weight);
21422142
ret_all.pushKV("totalfee", totalfee);
2143-
ret_all.pushKV("txs", (int64_t)block.vtx.size());
2143+
ret_all.pushKV("txs", block.vtx.size());
21442144
ret_all.pushKV("utxo_increase", outputs - inputs);
21452145
ret_all.pushKV("utxo_size_inc", utxo_size_inc);
21462146
ret_all.pushKV("utxo_increase_actual", utxos - inputs);
@@ -3437,7 +3437,7 @@ return RPCHelpMan{
34373437
const CChain& chain = cs.m_chain;
34383438
const CBlockIndex* tip = chain.Tip();
34393439

3440-
data.pushKV("blocks", (int)chain.Height());
3440+
data.pushKV("blocks", chain.Height());
34413441
data.pushKV("bestblockhash", tip->GetBlockHash().GetHex());
34423442
data.pushKV("bits", strprintf("%08x", tip->nBits));
34433443
data.pushKV("target", GetTarget(*tip, chainman.GetConsensus().powLimit).GetHex());

src/rpc/fees.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,14 +195,14 @@ static RPCHelpMan estimaterawfee()
195195
if (feeRate != CFeeRate(0)) {
196196
horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
197197
horizon_result.pushKV("decay", buckets.decay);
198-
horizon_result.pushKV("scale", (int)buckets.scale);
198+
horizon_result.pushKV("scale", buckets.scale);
199199
horizon_result.pushKV("pass", std::move(passbucket));
200200
// buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
201201
if (buckets.fail.start != -1) horizon_result.pushKV("fail", std::move(failbucket));
202202
} else {
203203
// Output only information that is still meaningful in the event of error
204204
horizon_result.pushKV("decay", buckets.decay);
205-
horizon_result.pushKV("scale", (int)buckets.scale);
205+
horizon_result.pushKV("scale", buckets.scale);
206206
horizon_result.pushKV("fail", std::move(failbucket));
207207
errors.push_back("Insufficient data or no feerate found which meets threshold");
208208
horizon_result.pushKV("errors", std::move(errors));

src/rpc/mempool.cpp

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ static void clusterToJSON(const CTxMemPool& pool, UniValue& info, std::vector<co
333333
total_weight += tx->GetAdjustedWeight();
334334
}
335335
info.pushKV("clusterweight", total_weight);
336-
info.pushKV("txcount", (int)cluster.size());
336+
info.pushKV("txcount", cluster.size());
337337

338338
// Output the cluster by chunk. This isn't handed to us by the mempool, but
339339
// we can calculate it by looking at the chunk feerates of each transaction
@@ -366,10 +366,10 @@ static void entryToJSON(const CTxMemPool& pool, UniValue& info, const CTxMemPool
366366
auto [ancestor_count, ancestor_size, ancestor_fees] = pool.CalculateAncestorData(e);
367367
auto [descendant_count, descendant_size, descendant_fees] = pool.CalculateDescendantData(e);
368368

369-
info.pushKV("vsize", (int)e.GetTxSize());
370-
info.pushKV("weight", (int)e.GetTxWeight());
369+
info.pushKV("vsize", e.GetTxSize());
370+
info.pushKV("weight", e.GetTxWeight());
371371
info.pushKV("time", count_seconds(e.GetTime()));
372-
info.pushKV("height", (int)e.GetHeight());
372+
info.pushKV("height", e.GetHeight());
373373
info.pushKV("descendantcount", descendant_count);
374374
info.pushKV("descendantsize", descendant_size);
375375
info.pushKV("ancestorcount", ancestor_count);
@@ -815,7 +815,7 @@ static RPCHelpMan gettxspendingprevout()
815815
for (const COutPoint& prevout : prevouts) {
816816
UniValue o(UniValue::VOBJ);
817817
o.pushKV("txid", prevout.hash.ToString());
818-
o.pushKV("vout", (uint64_t)prevout.n);
818+
o.pushKV("vout", prevout.n);
819819

820820
const CTransaction* spendingTx = mempool.GetConflictTx(prevout);
821821
if (spendingTx != nullptr) {
@@ -836,15 +836,15 @@ UniValue MempoolInfoToJSON(const CTxMemPool& pool)
836836
LOCK(pool.cs);
837837
UniValue ret(UniValue::VOBJ);
838838
ret.pushKV("loaded", pool.GetLoadTried());
839-
ret.pushKV("size", (int64_t)pool.size());
840-
ret.pushKV("bytes", (int64_t)pool.GetTotalTxSize());
841-
ret.pushKV("usage", (int64_t)pool.DynamicMemoryUsage());
839+
ret.pushKV("size", pool.size());
840+
ret.pushKV("bytes", pool.GetTotalTxSize());
841+
ret.pushKV("usage", pool.DynamicMemoryUsage());
842842
ret.pushKV("total_fee", ValueFromAmount(pool.GetTotalFee()));
843843
ret.pushKV("maxmempool", pool.m_opts.max_size_bytes);
844844
ret.pushKV("mempoolminfee", ValueFromAmount(std::max(pool.GetMinFee(), pool.m_opts.min_relay_feerate).GetFeePerK()));
845845
ret.pushKV("minrelaytxfee", ValueFromAmount(pool.m_opts.min_relay_feerate.GetFeePerK()));
846846
ret.pushKV("incrementalrelayfee", ValueFromAmount(pool.m_opts.incremental_relay_feerate.GetFeePerK()));
847-
ret.pushKV("unbroadcastcount", uint64_t{pool.GetUnbroadcastTxs().size()});
847+
ret.pushKV("unbroadcastcount", pool.GetUnbroadcastTxs().size());
848848
ret.pushKV("fullrbf", true);
849849
ret.pushKV("permitbaremultisig", pool.m_opts.permit_bare_multisig);
850850
ret.pushKV("maxdatacarriersize", pool.m_opts.max_datacarrier_bytes.value_or(0));
@@ -1270,7 +1270,7 @@ static RPCHelpMan submitpackage()
12701270
break;
12711271
case MempoolAcceptResult::ResultType::VALID:
12721272
case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
1273-
result_inner.pushKV("vsize", int64_t{it->second.m_vsize.value()});
1273+
result_inner.pushKV("vsize", it->second.m_vsize.value());
12741274
UniValue fees(UniValue::VOBJ);
12751275
fees.pushKV("base", ValueFromAmount(it->second.m_base_fees.value()));
12761276
if (tx_result.m_result_type == MempoolAcceptResult::ResultType::VALID) {

src/rpc/mining.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ static RPCHelpMan getmininginfo()
469469
obj.pushKV("difficulty", GetDifficulty(tip));
470470
obj.pushKV("target", GetTarget(tip, chainman.GetConsensus().powLimit).GetHex());
471471
obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
472-
obj.pushKV("pooledtx", (uint64_t)mempool.size());
472+
obj.pushKV("pooledtx", mempool.size());
473473
BlockAssembler::Options assembler_options;
474474
ApplyArgsManOptions(*node.args, assembler_options);
475475
obj.pushKV("blockmintxfee", ValueFromAmount(assembler_options.blockMinFeeRate.GetFeePerK()));
@@ -988,7 +988,7 @@ static RPCHelpMan getblocktemplate()
988988
result.pushKV("previousblockhash", block.hashPrevBlock.GetHex());
989989
result.pushKV("transactions", std::move(transactions));
990990
result.pushKV("coinbaseaux", std::move(aux));
991-
result.pushKV("coinbasevalue", (int64_t)block.vtx[0]->vout[0].nValue);
991+
result.pushKV("coinbasevalue", block.vtx[0]->vout[0].nValue);
992992
result.pushKV("longpollid", tip.GetHex() + ToString(nTransactionsUpdatedLast));
993993
result.pushKV("target", hashTarget.GetHex());
994994
result.pushKV("mintime", GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()));
@@ -1005,11 +1005,11 @@ static RPCHelpMan getblocktemplate()
10051005
result.pushKV("sigoplimit", nSigOpLimit);
10061006
result.pushKV("sizelimit", nSizeLimit);
10071007
if (!fPreSegWit) {
1008-
result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
1008+
result.pushKV("weightlimit", MAX_BLOCK_WEIGHT);
10091009
}
10101010
result.pushKV("curtime", block.GetBlockTime());
10111011
result.pushKV("bits", strprintf("%08x", block.nBits));
1012-
result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
1012+
result.pushKV("height", pindexPrev->nHeight + 1);
10131013

10141014
if (consensusParams.signet_blocks) {
10151015
result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));

src/rpc/net.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -956,7 +956,7 @@ static RPCHelpMan getnodeaddresses()
956956
for (const CAddress& addr : vAddr) {
957957
UniValue obj(UniValue::VOBJ);
958958
obj.pushKV("time", int64_t{TicksSinceEpoch<std::chrono::seconds>(addr.nTime)});
959-
obj.pushKV("services", (uint64_t)addr.nServices);
959+
obj.pushKV("services", static_cast<std::underlying_type_t<decltype(addr.nServices)>>(addr.nServices));
960960
obj.pushKV("address", addr.ToStringAddr());
961961
obj.pushKV("port", addr.GetPort());
962962
obj.pushKV("network", GetNetworkName(addr.GetNetClass()));
@@ -1123,7 +1123,7 @@ UniValue AddrmanEntryToJSON(const AddrInfo& info, const CConnman& connman)
11231123
ret.pushKV("mapped_as", mapped_as);
11241124
}
11251125
ret.pushKV("port", info.GetPort());
1126-
ret.pushKV("services", (uint64_t)info.nServices);
1126+
ret.pushKV("services", static_cast<std::underlying_type_t<decltype(info.nServices)>>(info.nServices));
11271127
ret.pushKV("time", int64_t{TicksSinceEpoch<std::chrono::seconds>(info.nTime)});
11281128
ret.pushKV("network", GetNetworkName(info.GetNetClass()));
11291129
ret.pushKV("source", info.source.ToStringAddr());

src/rpc/rawtransaction.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,8 +1428,8 @@ static RPCHelpMan decodepsbt()
14281428
UniValue tree(UniValue::VARR);
14291429
for (const auto& [depth, leaf_ver, script] : output.m_tap_tree) {
14301430
UniValue elem(UniValue::VOBJ);
1431-
elem.pushKV("depth", (int)depth);
1432-
elem.pushKV("leaf_ver", (int)leaf_ver);
1431+
elem.pushKV("depth", depth);
1432+
elem.pushKV("leaf_ver", leaf_ver);
14331433
elem.pushKV("script", HexStr(script));
14341434
tree.push_back(std::move(elem));
14351435
}
@@ -1971,7 +1971,7 @@ static RPCHelpMan analyzepsbt()
19711971
if (!inputs_result.empty()) result.pushKV("inputs", std::move(inputs_result));
19721972

19731973
if (psbta.estimated_vsize != std::nullopt) {
1974-
result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
1974+
result.pushKV("estimated_vsize", *psbta.estimated_vsize);
19751975
}
19761976
if (psbta.estimated_feerate != std::nullopt) {
19771977
result.pushKV("estimated_feerate", ValueFromAmount(psbta.estimated_feerate->GetFeePerK()));

src/rpc/rawtransaction_util.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,14 @@ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::
175175
{
176176
UniValue entry(UniValue::VOBJ);
177177
entry.pushKV("txid", txin.prevout.hash.ToString());
178-
entry.pushKV("vout", (uint64_t)txin.prevout.n);
178+
entry.pushKV("vout", txin.prevout.n);
179179
UniValue witness(UniValue::VARR);
180180
for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
181181
witness.push_back(HexStr(txin.scriptWitness.stack[i]));
182182
}
183183
entry.pushKV("witness", std::move(witness));
184184
entry.pushKV("scriptSig", HexStr(txin.scriptSig));
185-
entry.pushKV("sequence", (uint64_t)txin.nSequence);
185+
entry.pushKV("sequence", txin.nSequence);
186186
entry.pushKV("error", strMessage);
187187
vErrorsRet.push_back(std::move(entry));
188188
}

src/wallet/rpc/coins.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ RPCHelpMan listlockunspent()
389389
UniValue o(UniValue::VOBJ);
390390

391391
o.pushKV("txid", outpt.hash.GetHex());
392-
o.pushKV("vout", (int)outpt.n);
392+
o.pushKV("vout", outpt.n);
393393
ret.push_back(std::move(o));
394394
}
395395

@@ -617,7 +617,7 @@ RPCHelpMan listunspent()
617617

618618
UniValue entry(UniValue::VOBJ);
619619
entry.pushKV("txid", out.outpoint.hash.GetHex());
620-
entry.pushKV("vout", (int)out.outpoint.n);
620+
entry.pushKV("vout", out.outpoint.n);
621621

622622
if (fValidAddress) {
623623
entry.pushKV("address", EncodeDestination(address));

src/wallet/rpc/wallet.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ static RPCHelpMan getwalletinfo()
8989
obj.pushKV("walletname", pwallet->GetName());
9090
obj.pushKV("walletversion", latest_legacy_wallet_minversion);
9191
obj.pushKV("format", pwallet->GetDatabase().Format());
92-
obj.pushKV("txcount", (int)pwallet->mapWallet.size());
93-
obj.pushKV("keypoolsize", (int64_t)kpExternalSize);
92+
obj.pushKV("txcount", pwallet->mapWallet.size());
93+
obj.pushKV("keypoolsize", kpExternalSize);
9494
obj.pushKV("keypoolsize_hd_internal", pwallet->GetKeyPoolSize() - kpExternalSize);
9595

9696
if (pwallet->HasEncryptionKeys()) {

0 commit comments

Comments
 (0)