From 76605e2b369d65bc35de1beaaeb45ba1fe1c76f8 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Mon, 26 Apr 2021 20:32:40 +0200 Subject: [PATCH] Make Result unwrap include source --- wallet/block.cpp | 34 ++++++++++++++------------ wallet/main.cpp | 5 ++-- wallet/qt/newstakedelegationdialog.cpp | 5 ++-- wallet/result.h | 14 ++++++++--- wallet/rpcrawtransaction.cpp | 10 ++++---- wallet/rpcwallet.cpp | 14 +++++------ wallet/test/result_tests.cpp | 16 ++++++------ wallet/test/transaction_tests.cpp | 3 ++- wallet/transaction.cpp | 7 +++--- wallet/wallet.cpp | 2 +- 10 files changed, 62 insertions(+), 48 deletions(-) diff --git a/wallet/block.cpp b/wallet/block.cpp index d165613e1..cb9a40cba 100644 --- a/wallet/block.cpp +++ b/wallet/block.cpp @@ -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; @@ -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 " + @@ -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; @@ -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(), @@ -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) { @@ -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)); } } @@ -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); } @@ -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; diff --git a/wallet/main.cpp b/wallet/main.cpp index d3641e7bb..b187ac070 100644 --- a/wallet/main.cpp +++ b/wallet/main.cpp @@ -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); @@ -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 diff --git a/wallet/qt/newstakedelegationdialog.cpp b/wallet/qt/newstakedelegationdialog.cpp index 19a81f722..982d4eae8 100644 --- a/wallet/qt/newstakedelegationdialog.cpp +++ b/wallet/qt/newstakedelegationdialog.cpp @@ -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()); diff --git a/wallet/result.h b/wallet/result.h index affecdeb4..582440336 100644 --- a/wallet/result.h +++ b/wallet/result.h @@ -10,10 +10,14 @@ #pragma once +#include #include #include #include +#define RESULT_PRE \ + "[" + boost::filesystem::path(__FILE__).filename().string() + ":" + std::to_string(__LINE__) + "]" + namespace types { template struct Ok @@ -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()); @@ -929,23 +934,26 @@ struct Result } template - typename std::enable_if::value, U>::type unwrap() const + typename std::enable_if::value, U>::type + unwrap(const std::string& caller_source) const { if (isOk()) { return storage().template get(); } 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(); } std::fprintf(stderr, "Attempting to unwrapErr an ok Result\n"); + std::cerr << caller_source << std::endl; std::terminate(); } diff --git a/wallet/rpcrawtransaction.cpp b/wallet/rpcrawtransaction.cpp index 7d65b094b..2eee4bca1 100644 --- a/wallet/rpcrawtransaction.cpp +++ b/wallet/rpcrawtransaction.cpp @@ -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"); @@ -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); diff --git a/wallet/rpcwallet.cpp b/wallet/rpcwallet.cpp index 3737c5381..f811b8cc3 100644 --- a/wallet/rpcwallet.cpp +++ b/wallet/rpcwallet.cpp @@ -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(bi ? bi->nTime : 0); entry.push_back(Pair("blocktime", nTime)); } @@ -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); @@ -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); diff --git a/wallet/test/result_tests.cpp b/wallet/test/result_tests.cpp index 5c9dd3a2e..bf1b88f55 100644 --- a/wallet/test/result_tests.cpp +++ b/wallet/test/result_tests.cpp @@ -6,7 +6,7 @@ TEST(result_tests, basic_result) { Result 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); } @@ -14,7 +14,7 @@ TEST(result_tests, rvalue_result) { Result 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!"); } @@ -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!"); } @@ -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) @@ -47,7 +47,7 @@ TEST(result_tests, lvalue_result) Result 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!"); } @@ -56,7 +56,7 @@ TEST(result_tests, basic_error) Result r1 = Err(15u); EXPECT_TRUE(r1.isErr()); - EXPECT_EQ(r1.unwrapErr(), 15); + EXPECT_EQ(r1.unwrapErr(RESULT_PRE), 15); } TEST(result_tests, rvalue_error) @@ -64,7 +64,7 @@ TEST(result_tests, rvalue_error) Result 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) @@ -74,5 +74,5 @@ TEST(result_tests, lvalue_error) Result r1 = Err(str); EXPECT_TRUE(r1.isErr()); - EXPECT_EQ(r1.unwrapErr(), str); + EXPECT_EQ(r1.unwrapErr(RESULT_PRE), str); } diff --git a/wallet/test/transaction_tests.cpp b/wallet/test/transaction_tests.cpp index e1965b90f..6ade04903 100644 --- a/wallet/test/transaction_tests.cpp +++ b/wallet/test/transaction_tests.cpp @@ -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."; } diff --git a/wallet/transaction.cpp b/wallet/transaction.cpp index f46f304b4..bc96c4f7f 100644 --- a/wallet/transaction.cpp +++ b/wallet/transaction.cpp @@ -601,14 +601,15 @@ Result 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 = diff --git a/wallet/wallet.cpp b/wallet/wallet.cpp index aa556c7b7..4a7aee12d 100644 --- a/wallet/wallet.cpp +++ b/wallet/wallet.cpp @@ -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();