Skip to content

Commit

Permalink
Make Result unwrap include source
Browse files Browse the repository at this point in the history
  • Loading branch information
TheQuantumPhysicist authored and nebliodev committed Apr 26, 2021
1 parent ac27097 commit 76605e2
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 48 deletions.
34 changes: 18 additions & 16 deletions wallet/block.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ CBlock::GetBlocksUpToCommonAncestorInMainChain(const ITxDB& txdb) const
CommonAncestorSuccessorBlocks res;

// fork part
CBlockIndexSmartPtr T = nullptr;
const uint256 prevBlockHash = this->hashPrevBlock;
const auto biTarget = mapBlockIndex.get(prevBlockHash).value_or(nullptr);
CBlockIndexSmartPtr T = nullptr;
const uint256 prevBlockHash = this->hashPrevBlock;
const auto biTarget = mapBlockIndex.get(prevBlockHash).value_or(nullptr);

if (biTarget) {
T = biTarget;
Expand Down Expand Up @@ -283,8 +283,8 @@ CBlock::ChainReplaceTxs CBlock::GetAlternateChainTxsUpToCommonAncestor(const ITx
continue;
}

uint256 spenderBlockHash = txindex.vSpent[outputNumInTx].nBlockPos;
const auto bi = mapBlockIndex.get(spenderBlockHash).value_or(nullptr);
uint256 spenderBlockHash = txindex.vSpent[outputNumInTx].nBlockPos;
const auto bi = mapBlockIndex.get(spenderBlockHash).value_or(nullptr);
if (!bi) {
throw std::runtime_error(
std::string(__PRETTY_FUNCTION__) + ": The input of transaction " +
Expand Down Expand Up @@ -1073,7 +1073,7 @@ bool CBlock::AddToBlockIndex(uint256 nBlockPos, const uint256& hashProof, CTxDB&
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = hash;
const auto biPrev = mapBlockIndex.get(hashPrevBlock).value_or(nullptr);
const auto biPrev = mapBlockIndex.get(hashPrevBlock).value_or(nullptr);
if (biPrev) {
pindexNew->pprev = biPrev;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
Expand Down Expand Up @@ -1216,14 +1216,15 @@ bool CBlock::CheckBlock(const ITxDB& txdb, bool fCheckPOW, bool fCheckMerkleRoot
const auto checkTxResult = tx.CheckTransaction(txdb, this);
if (checkTxResult.isErr())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed: (Msg: %s) - (Debug: %s)",
checkTxResult.unwrapErr().GetRejectReason().c_str(),
checkTxResult.unwrapErr().GetDebugMessage().c_str()));
checkTxResult.unwrapErr(RESULT_PRE).GetRejectReason().c_str(),
checkTxResult.unwrapErr(RESULT_PRE).GetDebugMessage().c_str()));

// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64_t)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp (%" PRIu64 ") is earlier than transaction "
"(tx number %" PRIu32 " in block) timestamp (%" PRIi64 ")",
GetBlockTime(), i, (int64_t)tx.nTime));
return DoS(50,
error("CheckBlock() : block timestamp (%" PRIu64 ") is earlier than transaction "
"(tx number %" PRIu32 " in block) timestamp (%" PRIi64 ")",
GetBlockTime(), i, (int64_t)tx.nTime));
}

// Check for duplicate txids. This is caught by ConnectInputs(),
Expand Down Expand Up @@ -1281,7 +1282,7 @@ bool CBlock::AcceptBlock()
int64_t maxCheckpointBlockHeight = Checkpoints::GetLastCheckpointBlockHeight();
if (CTxDB().GetBestChainHeight().value_or(0) > maxCheckpointBlockHeight + 1) {
const uint256 prevBlockHash = this->hashPrevBlock;
const auto bi = mapBlockIndex.get(prevBlockHash).value_or(nullptr);
const auto bi = mapBlockIndex.get(prevBlockHash).value_or(nullptr);
if (bi) {
int64_t newBlockPrevBlockHeight = bi->nHeight;
if (newBlockPrevBlockHeight + 1 < maxCheckpointBlockHeight) {
Expand Down Expand Up @@ -1323,12 +1324,12 @@ bool CBlock::AcceptBlock()

{
const CTxDB txdb;
const auto hasColdStakingResult = HasColdStaking(txdb);
const auto hasColdStakingResult = HasColdStaking(txdb);
if (hasColdStakingResult.isErr()) {
return DoS(100, error("AcceptBlock() : reject cold-stake at height %d with error", nHeight));
}

if (hasColdStakingResult.unwrap() && !Params().IsColdStakingEnabled(txdb)) {
if (hasColdStakingResult.unwrap(RESULT_PRE) && !Params().IsColdStakingEnabled(txdb)) {
return DoS(100, error("AcceptBlock() : reject cold-staked at height %d", nHeight));
}
}
Expand Down Expand Up @@ -1607,7 +1608,7 @@ bool CBlock::CheckBlockSignature(const ITxDB& txdb) const
if (keyResult.isErr()) {
return error("CheckBlockSignature(): ColdStaking key extraction failed");
}
key = keyResult.unwrap();
key = keyResult.unwrap(RESULT_PRE);
return key.Verify(GetHash(), vchBlockSig);
}

Expand Down Expand Up @@ -1695,7 +1696,8 @@ void UpdateWallets(const uint256& prevBestChain)
*/
if (txdb.GetBestChainHeight().value_or(0) > 0) {
// get the highest block in the previous check that's main chain
CBlockIndexSmartPtr ancestorOfPrevInMainChain = mapBlockIndex.get(prevBestChain).value_or(nullptr);
CBlockIndexSmartPtr ancestorOfPrevInMainChain =
mapBlockIndex.get(prevBestChain).value_or(nullptr);
assert(ancestorOfPrevInMainChain);
while (ancestorOfPrevInMainChain->pprev && !ancestorOfPrevInMainChain->IsInMainChain(txdb)) {
ancestorOfPrevInMainChain = ancestorOfPrevInMainChain->pprev;
Expand Down
5 changes: 3 additions & 2 deletions wallet/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2101,7 +2101,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
vWorkQueue.push_back(orphanTxHash);
vEraseQueue.push_back(orphanTxHash);
} else if (mempoolRes.unwrapErr().GetResult() !=
} else if (mempoolOrphanRes.unwrapErr(RESULT_PRE).GetResult() !=
TxValidationResult::TX_MISSING_INPUTS) {
// invalid orphan
vEraseQueue.push_back(orphanTxHash);
Expand All @@ -2112,7 +2112,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)

for (uint256 hash : vEraseQueue)
EraseOrphanTx(hash);
} else if (mempoolRes.unwrapErr().GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
} else if (mempoolRes.unwrapErr(RESULT_PRE).GetResult() ==
TxValidationResult::TX_MISSING_INPUTS) {
AddOrphanTx(tx);

// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
Expand Down
5 changes: 3 additions & 2 deletions wallet/qt/newstakedelegationdialog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,11 @@ void NewStakeDelegationDialog::slot_createColdStake()
fForceExternalAddr, fUseDelegated, false);

if (delegRes.isErr()) {
return makeError(QString::fromStdString(ColdStakeDelegationErrorStr(delegRes.unwrapErr())));
return makeError(
QString::fromStdString(ColdStakeDelegationErrorStr(delegRes.unwrapErr(RESULT_PRE))));
}

const CoinStakeDelegationResult res = delegRes.unwrap();
const CoinStakeDelegationResult res = delegRes.unwrap(RESULT_PRE);

const CAmount currBalance =
pwalletMain->GetBalance() - (fUseDelegated ? 0 : pwalletMain->GetDelegatedBalance());
Expand Down
14 changes: 11 additions & 3 deletions wallet/result.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@

#pragma once

#include <boost/filesystem/path.hpp>
#include <functional>
#include <iostream>
#include <type_traits>

#define RESULT_PRE \
"[" + boost::filesystem::path(__FILE__).filename().string() + ":" + std::to_string(__LINE__) + "]"

namespace types {
template <typename T>
struct Ok
Expand Down Expand Up @@ -870,10 +874,11 @@ struct Result

bool isErr() const { return !ok_; }

T expect(const char* str) const
T expect(const char* str, const std::string& caller_source) const
{
if (!isOk()) {
std::fprintf(stderr, "%s\n", str);
std::cerr << caller_source << std::endl;
std::terminate();
}
return expect_impl(std::is_same<T, void>());
Expand Down Expand Up @@ -929,23 +934,26 @@ struct Result
}

template <typename U = T>
typename std::enable_if<!std::is_same<U, void>::value, U>::type unwrap() const
typename std::enable_if<!std::is_same<U, void>::value, U>::type
unwrap(const std::string& caller_source) const
{
if (isOk()) {
return storage().template get<U>();
}

std::fprintf(stderr, "Attempting to unwrap an error Result\n");
std::cerr << caller_source << std::endl;
std::terminate();
}

E unwrapErr() const
E unwrapErr(const std::string& caller_source) const
{
if (isErr()) {
return storage().template get<E>();
}

std::fprintf(stderr, "Attempting to unwrapErr an ok Result\n");
std::cerr << caller_source << std::endl;
std::terminate();
}

Expand Down
10 changes: 5 additions & 5 deletions wallet/rpcrawtransaction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ Value getrawtransaction(const Array& params, bool fHelp)
// if a specific block was mentioned, get it from the database and look for the tx in it
CTxDB txdb;
{
uint256 blockhash = ParseHashV(params[3], "parameter 3");
uint256 blockhash = ParseHashV(params[3], "parameter 3");
const auto bi = mapBlockIndex.get(blockhash).value_or(nullptr);
if (!bi) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
Expand Down Expand Up @@ -1035,12 +1035,12 @@ Value sendrawtransaction(const Array& params, bool fHelp)
// push to local node
const auto mempoolRes = AcceptToMemoryPool(mempool, tx);
if (mempoolRes.isErr()) {
std::string msg = mempoolRes.unwrapErr().GetRejectReason();
if (mempoolRes.unwrapErr().GetDebugMessage().empty()) {
msg += "; Debug: " + mempoolRes.unwrapErr().GetDebugMessage();
std::string msg = mempoolRes.unwrapErr(RESULT_PRE).GetRejectReason();
if (mempoolRes.unwrapErr(RESULT_PRE).GetDebugMessage().empty()) {
msg += "; Debug: " + mempoolRes.unwrapErr(RESULT_PRE).GetDebugMessage();
}

if (mempoolRes.unwrapErr().GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
if (mempoolRes.unwrapErr(RESULT_PRE).GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, msg);
}
throw JSONRPCError(RPC_TRANSACTION_REJECTED, msg);
Expand Down
14 changes: 7 additions & 7 deletions wallet/rpcwallet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
if (confirms > 0) {
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
const auto bi = mapBlockIndex.get(wtx.hashBlock).value_or(nullptr);
const auto bi = mapBlockIndex.get(wtx.hashBlock).value_or(nullptr);
const int64_t nTime = static_cast<int64_t>(bi ? bi->nTime : 0);
entry.push_back(Pair("blocktime", nTime));
}
Expand Down Expand Up @@ -292,11 +292,11 @@ Value delegatestake(const Array& params, bool fHelp)
pParams.fUseDelegated, pParams.fForceNotEnabled);

if (delegRes.isErr()) {
throw JSONRPCError(ColdStakeDelegationRPCErrorCode(delegRes.unwrapErr()),
ColdStakeDelegationErrorStr(delegRes.unwrapErr()));
throw JSONRPCError(ColdStakeDelegationRPCErrorCode(delegRes.unwrapErr(RESULT_PRE)),
ColdStakeDelegationErrorStr(delegRes.unwrapErr(RESULT_PRE)));
}

const CoinStakeDelegationResult res = delegRes.unwrap();
const CoinStakeDelegationResult res = delegRes.unwrap(RESULT_PRE);

const CWalletTx wtx =
SubmitColdStakeDelegationTx(reservekey, pParams.nValue, res.scriptPubKey, pParams.fUseDelegated);
Expand Down Expand Up @@ -398,11 +398,11 @@ Value rawdelegatestake(const Array& params, bool fHelp)
pParams.fUseDelegated, pParams.fForceNotEnabled);

if (delegRes.isErr()) {
throw JSONRPCError(ColdStakeDelegationRPCErrorCode(delegRes.unwrapErr()),
ColdStakeDelegationErrorStr(delegRes.unwrapErr()));
throw JSONRPCError(ColdStakeDelegationRPCErrorCode(delegRes.unwrapErr(RESULT_PRE)),
ColdStakeDelegationErrorStr(delegRes.unwrapErr(RESULT_PRE)));
}

CoinStakeDelegationResult res = delegRes.unwrap();
CoinStakeDelegationResult res = delegRes.unwrap(RESULT_PRE);

CWalletTx wtx =
SubmitColdStakeDelegationTx(reservekey, pParams.nValue, res.scriptPubKey, pParams.fUseDelegated);
Expand Down
16 changes: 8 additions & 8 deletions wallet/test/result_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ TEST(result_tests, basic_result)
{
Result<uint64_t, uint32_t> r1 = Ok(UINT64_C(3));

auto val = r1.expect("Failed to retrieve the value");
auto val = r1.expect("Failed to retrieve the value", RESULT_PRE);
EXPECT_EQ(val, 3);
}

TEST(result_tests, rvalue_result)
{
Result<std::string, uint32_t> r1 = Ok(std::string("Success!"));

auto val = r1.expect("Failed to retrieve the value");
auto val = r1.expect("Failed to retrieve the value", RESULT_PRE);
EXPECT_EQ(val, "Success!");
}

Expand All @@ -26,7 +26,7 @@ TEST(result_tests, rvalue_result_forced)

EXPECT_TRUE(str.empty());

auto val = r1.expect("Failed to retrieve the value");
auto val = r1.expect("Failed to retrieve the value", RESULT_PRE);
EXPECT_EQ(val, "Success!");
}

Expand All @@ -38,7 +38,7 @@ TEST(result_tests, rvalue_error_forced)
EXPECT_TRUE(str.empty());
EXPECT_TRUE(r1.isErr());

EXPECT_EQ(r1.unwrapErr(), "Success!");
EXPECT_EQ(r1.unwrapErr(RESULT_PRE), "Success!");
}

TEST(result_tests, lvalue_result)
Expand All @@ -47,7 +47,7 @@ TEST(result_tests, lvalue_result)

Result<std::string, uint32_t> r1 = Ok(str);

auto val = r1.expect("Failed to retrieve the value");
auto val = r1.expect("Failed to retrieve the value", RESULT_PRE);
EXPECT_EQ(val, "Success!");
}

Expand All @@ -56,15 +56,15 @@ TEST(result_tests, basic_error)
Result<std::string, uint32_t> r1 = Err(15u);

EXPECT_TRUE(r1.isErr());
EXPECT_EQ(r1.unwrapErr(), 15);
EXPECT_EQ(r1.unwrapErr(RESULT_PRE), 15);
}

TEST(result_tests, rvalue_error)
{
Result<uint32_t, std::string> r1 = Err(std::string("Error!"));

EXPECT_TRUE(r1.isErr());
EXPECT_EQ(r1.unwrapErr(), "Error!");
EXPECT_EQ(r1.unwrapErr(RESULT_PRE), "Error!");
}

TEST(result_tests, lvalue_error)
Expand All @@ -74,5 +74,5 @@ TEST(result_tests, lvalue_error)
Result<uint32_t, std::string> r1 = Err(str);

EXPECT_TRUE(r1.isErr());
EXPECT_EQ(r1.unwrapErr(), str);
EXPECT_EQ(r1.unwrapErr(RESULT_PRE), str);
}
3 changes: 2 additions & 1 deletion wallet/test/transaction_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ TEST(transaction_tests, basic_transaction_tests)
tx.vin.push_back(tx.vin[0]);
ASSERT_TRUE(tx.CheckTransaction(*dbMock).isErr())
<< "Transaction with duplicate txins should be invalid.";
EXPECT_EQ(tx.CheckTransaction(*dbMock).unwrapErr().GetRejectReason(), "bad-txns-inputs-duplicate")
EXPECT_EQ(tx.CheckTransaction(*dbMock).unwrapErr(RESULT_PRE).GetRejectReason(),
"bad-txns-inputs-duplicate")
<< "Transaction with duplicate has invalid rejection reason.";
}

Expand Down
7 changes: 4 additions & 3 deletions wallet/transaction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -601,14 +601,15 @@ Result<void, TxValidationState> CTransaction::ConnectInputs(const ITxDB& txdb, M
return Err(MakeInvalidTxState(
TxValidationResult::TX_NOT_STANDARD,
strprintf("non-mandatory-script-verify-flag (%s)",
ScriptErrorString(verifyResP2SH.unwrapErr())),
ScriptErrorString(verifyResP2SH.unwrapErr(RESULT_PRE))),
strprintf("ConnectInputs() : %s P2SH VerifySignature failed",
GetHash().ToString().c_str())));
}
}

const std::string msg = strprintf("mandatory-script-verify-flag-failed (%s)",
ScriptErrorString(verifyRes.unwrapErr()));
const std::string msg =
strprintf("mandatory-script-verify-flag-failed (%s)",
ScriptErrorString(verifyRes.unwrapErr(RESULT_PRE)));

if (sourceBlockPtr) {
sourceBlockPtr->reject =
Expand Down
2 changes: 1 addition & 1 deletion wallet/wallet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2437,7 +2437,7 @@ bool CWallet::CommitTransaction(const CWalletTx& wtxNew, CReserveKey& reservekey
if (mempoolRes.isErr()) {
// This must not fail. The transaction has already been signed and recorded.
printf("CommitTransaction() : Error: Transaction not valid. Error: %s\n",
mempoolRes.unwrapErr().GetRejectReason().c_str());
mempoolRes.unwrapErr(RESULT_PRE).GetRejectReason().c_str());
return false;
}
wtxNew.RelayWalletTransaction();
Expand Down

0 comments on commit 76605e2

Please sign in to comment.