本文整理汇总了C++中CBlock::BuildMerkleTree方法的典型用法代码示例。如果您正苦于以下问题:C++ CBlock::BuildMerkleTree方法的具体用法?C++ CBlock::BuildMerkleTree怎么用?C++ CBlock::BuildMerkleTree使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CBlock
的用法示例。
在下文中一共展示了CBlock::BuildMerkleTree方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1:
void
CAuxpowBuilder::setCoinbase (const CScript& scr)
{
CMutableTransaction mtx;
mtx.vin.resize (1);
mtx.vin[0].prevout.SetNull ();
mtx.vin[0].scriptSig = scr;
parentBlock.vtx.clear ();
parentBlock.vtx.push_back (mtx);
parentBlock.hashMerkleRoot = parentBlock.BuildMerkleTree ();
}
示例2: IsTxInTipBlock
bool SysTestBase::IsTxInTipBlock(const uint256& txHash) {
CBlockIndex* pindex = chainActive.Tip();
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
return false;
block.BuildMerkleTree();
std::tuple<bool, int> ret = block.GetTxIndex(txHash);
if (!std::get<0>(ret)) {
return false;
}
return true;
}
示例3: GetTxIndexInBlock
bool GetTxIndexInBlock(const uint256& txHash, int& nIndex) {
CBlockIndex* pindex = chainActive.Tip();
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
return false;
block.BuildMerkleTree();
std::tuple<bool,int> ret = block.GetTxIndex(txHash);
if (!std::get<0>(ret)) {
return false;
}
nIndex = std::get<1>(ret);
return true;
}
示例4: getscriptid
Value getscriptid(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1) {
throw runtime_error("getscriptid \n"
"\nreturn an object containing regid and script\n"
"\nArguments:\n"
"1. txhash (string, required) the transaction hash.\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("getscriptid", "5zQPcC1YpFMtwxiH787pSXanUECoGsxUq3KZieJxVG")
+ HelpExampleRpc("getscriptid","5zQPcC1YpFMtwxiH787pSXanUECoGsxUq3KZieJxVG"));
}
uint256 txhash(uint256S(params[0].get_str()));
int nIndex = 0;
int BlockHeight =GetTxComfirmHigh(txhash, *pScriptDBTip) ;
if(BlockHeight > chainActive.Height())
{
throw runtime_error("height larger than tip block \n");
}
else if(BlockHeight == -1){
throw runtime_error("tx hash unconfirmed \n");
}
CBlockIndex* pindex = chainActive[BlockHeight];
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
return false;
block.BuildMerkleTree();
std::tuple<bool,int> ret = block.GetTxIndex(txhash);
if (!std::get<0>(ret)) {
throw runtime_error("tx not exit in block");
}
nIndex = std::get<1>(ret);
CRegID striptID(BlockHeight, nIndex);
Object result;
result.push_back(Pair("regid:", striptID.ToString()));
result.push_back(Pair("script", HexStr(striptID.GetVec6())));
return result;
}
示例5: GetValidReceive
TEST(wallet_tests, nullifier_is_spent) {
CWallet wallet;
auto sk = libzcash::SpendingKey::random();
wallet.AddSpendingKey(sk);
auto wtx = GetValidReceive(sk, 10, true);
auto note = GetNote(sk, wtx, 0, 1);
auto nullifier = note.nullifier(sk);
EXPECT_FALSE(wallet.IsSpent(nullifier));
wallet.AddToWallet(wtx, true, NULL);
EXPECT_FALSE(wallet.IsSpent(nullifier));
auto wtx2 = GetValidSpend(sk, note, 5);
wallet.AddToWallet(wtx2, true, NULL);
EXPECT_FALSE(wallet.IsSpent(nullifier));
// Fake-mine the transaction
EXPECT_EQ(-1, chainActive.Height());
CBlock block;
block.vtx.push_back(wtx2);
block.hashMerkleRoot = block.BuildMerkleTree();
auto blockHash = block.GetHash();
CBlockIndex fakeIndex {block};
mapBlockIndex.insert(std::make_pair(blockHash, &fakeIndex));
chainActive.SetTip(&fakeIndex);
EXPECT_TRUE(chainActive.Contains(&fakeIndex));
EXPECT_EQ(0, chainActive.Height());
wtx2.SetMerkleBranch(block);
wallet.AddToWallet(wtx2, true, NULL);
EXPECT_TRUE(wallet.IsSpent(nullifier));
// Tear down
chainActive.SetTip(NULL);
mapBlockIndex.erase(blockHash);
}
示例6: SignStakeBlock
bool SignStakeBlock(CBlock &block, CKey &key, vector<const CWalletTx*> &StakeInputs, CWallet *pwallet, MiningCPID& BoincData)
{
//Append beacon signature to coinbase
std::string PublicKey = GlobalCPUMiningCPID.BoincPublicKey;
if (!PublicKey.empty())
{
std::string sBoincSignature;
std::string sError;
bool bResult = SignBlockWithCPID(GlobalCPUMiningCPID.cpid, GlobalCPUMiningCPID.lastblockhash, sBoincSignature, sError);
if (!bResult)
{
return error("SignStakeBlock: Failed to sign boinchash -> %s\n", sError);
}
BoincData.BoincSignature = sBoincSignature;
if(fDebug2) LogPrintf("Signing BoincBlock for cpid %s and blockhash %s with sig %s\n", GlobalCPUMiningCPID.cpid, GlobalCPUMiningCPID.lastblockhash, BoincData.BoincSignature);
}
block.vtx[0].hashBoinc = SerializeBoincBlock(BoincData,block.nVersion);
//if (fDebug2) LogPrintf("SignStakeBlock: %s\n",SerializedBoincData.c_str());
//Sign the coinstake transaction
unsigned nIn = 0;
for (auto const& pcoin : StakeInputs)
{
if (!SignSignature(*pwallet, *pcoin, block.vtx[1], nIn++))
{
return error("SignStakeBlock: failed to sign coinstake");
}
}
//Sign the whole block
block.hashMerkleRoot = block.BuildMerkleTree();
if( !key.Sign(block.GetHash(), block.vchBlockSig) )
{
return error("SignStakeBlock: failed to sign block");
}
return true;
}
示例7: getworkaux
//.........这里部分代码省略.........
IncrementExtraNonceWithAux(pblock, pindexPrev, nExtraNonce, nPrevTime, vchAux);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
if (params[0].get_str() != "submit" && params[0].get_str() != "")
throw JSONRPCError(RPC_INVALID_PARAMETER, "<aux> must be the empty string or 'submit' if work is being submitted");
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
// Get the aux merkle root from the coinbase
CScript script = pblock->vtx[0].vin[0].scriptSig;
opcodetype opcode;
CScript::const_iterator pc = script.begin();
script.GetOp(pc, opcode);
script.GetOp(pc, opcode);
script.GetOp(pc, opcode);
if (opcode != OP_2)
throw JSONRPCError(RPC_MISC_ERROR, "invalid aux pow script");
vector<unsigned char> vchAux;
script.GetOp(pc, opcode, vchAux);
RemoveMergedMiningHeader(vchAux);
pblock->vtx[0].vin[0].scriptSig = MakeCoinbaseWithAux(pblock->nBits, nExtraNonce, vchAux);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
if (params.size() > 2)
{
// Requested aux proof of work
int nChainIndex = params[2].get_int();
CAuxPow pow(pblock->vtx[0]);
for (int i = 3 ; (unsigned int)i < params.size() ; i++)
{
uint256 nHash;
nHash.SetHex(params[i].get_str());
pow.vChainMerkleBranch.push_back(nHash);
}
pow.SetMerkleBranch(pblock);
pow.nChainIndex = nChainIndex;
pow.parentBlock = *pblock;
CDataStream ss(SER_GETHASH|SER_BLOCKHEADERONLY, PROTOCOL_VERSION);
ss << pow;
Object result;
result.push_back(Pair("auxpow", HexStr(ss.begin(), ss.end())));
return result;
}
else
{
if (params[0].get_str() == "submit")
{
return CheckWork(pblock, *pwalletMain, reservekey);
}
else
{
Object result;
result.push_back(Pair("aux", HexStr(vchAux.begin(), vchAux.end())));
result.push_back(Pair("hash", pblock->GetPoWHash().GetHex()));
return result;
}
}
}
}
示例8: getwork
//.........这里部分代码省略.........
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Xedoscoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Xedoscoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlock(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(*pblock, pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
示例9: getauxblock
//.........这里部分代码省略.........
/* The variables below are used to keep track of created and not yet
submitted auxpow blocks. Lock them to be sure even for multiple
RPC threads running in parallel. */
static CCriticalSection cs_auxblockCache;
LOCK(cs_auxblockCache);
static std::map<uint256, CBlock*> mapNewBlock;
static std::vector<CBlockTemplate*> vNewBlockTemplate;
/* Create a new block? */
if (params.size() == 0)
{
static unsigned nTransactionsUpdatedLast;
static const CBlockIndex* pindexPrev = NULL;
static uint64_t nStart;
static CBlockTemplate* pblocktemplate;
static unsigned nExtraNonce = 0;
// Update block
{
LOCK(cs_main);
if (pindexPrev != chainActive.Tip()
|| (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast
&& GetTime() - nStart > 60))
{
if (pindexPrev != chainActive.Tip())
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pbt, vNewBlockTemplate)
delete pbt;
vNewBlockTemplate.clear();
}
// Create new block with nonce = 0 and extraNonce = 1
pblocktemplate = CreateNewBlock(coinbaseScript->reserveScript);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "out of memory");
// Update state only when CreateNewBlock succeeded
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
pindexPrev = chainActive.Tip();
nStart = GetTime();
// Finalise it by setting the version and building the merkle root
CBlock* pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
pblock->nVersion.SetAuxpow(true);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
// Save
mapNewBlock[pblock->GetHash()] = pblock;
vNewBlockTemplate.push_back(pblocktemplate);
}
}
const CBlock& block = pblocktemplate->block;
arith_uint256 target;
bool fNegative, fOverflow;
target.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || target == 0)
throw std::runtime_error("invalid difficulty bits in block");
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", block.GetHash().GetHex()));
result.push_back(Pair("chainid", block.nVersion.GetChainId()));
result.push_back(Pair("previousblockhash", block.hashPrevBlock.GetHex()));
result.push_back(Pair("coinbasevalue", (int64_t)block.vtx[0].vout[0].nValue));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("height", static_cast<int64_t> (pindexPrev->nHeight + 1)));
result.push_back(Pair("_target", HexStr(BEGIN(target), END(target))));
return result;
}
/* Submit a block instead. Note that this need not lock cs_main,
since ProcessBlockFound below locks it instead. */
assert(params.size() == 2);
uint256 hash;
hash.SetHex(params[0].get_str());
const std::map<uint256, CBlock*>::iterator mit = mapNewBlock.find(hash);
if (mit == mapNewBlock.end())
throw JSONRPCError(RPC_INVALID_PARAMETER, "block hash unknown");
CBlock& block = *mit->second;
const std::vector<unsigned char> vchAuxPow = ParseHex(params[1].get_str());
CDataStream ss(vchAuxPow, SER_GETHASH, PROTOCOL_VERSION);
CAuxPow pow;
ss >> pow;
block.SetAuxpow(new CAuxPow(pow));
assert(block.GetHash() == hash);
const bool ok = ProcessBlockFound(&block, Params());
if (ok)
coinbaseScript->KeepScript();
return ok;
}
示例10: AppInit2
//.........这里部分代码省略.........
LogPrintf("Loading block index...");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
return InitError(_("Error loading blkindex.dat"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
LogPrintf("Shutdown requested. Exiting.");
return false;
}
LogPrintf(" block index %15" PRId64 "ms", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (BlockMap::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
LogPrintf("");
nFound++;
}
}
if (nFound == 0)
LogPrintf("No blocks matching %s were found", strMatch);
return false;
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
LogPrintf("Loading wallet...");
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFileName);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
uiInterface.ThreadSafeMessageBox(msg, _("Gridcoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Gridcoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
示例11: SelectParams
TEST(wallet_tests, find_unspent_notes) {
SelectParams(CBaseChainParams::TESTNET);
CWallet wallet;
auto sk = libzcash::SpendingKey::random();
wallet.AddSpendingKey(sk);
auto wtx = GetValidReceive(sk, 10, true);
auto note = GetNote(sk, wtx, 0, 1);
auto nullifier = note.nullifier(sk);
mapNoteData_t noteData;
JSOutPoint jsoutpt {wtx.GetHash(), 0, 1};
CNoteData nd {sk.address(), nullifier};
noteData[jsoutpt] = nd;
wtx.SetNoteData(noteData);
wallet.AddToWallet(wtx, true, NULL);
EXPECT_FALSE(wallet.IsSpent(nullifier));
// We currently have an unspent and unconfirmed note in the wallet (depth of -1)
std::vector<CNotePlaintextEntry> entries;
wallet.GetFilteredNotes(entries, "", 0);
EXPECT_EQ(0, entries.size());
entries.clear();
wallet.GetFilteredNotes(entries, "", -1);
EXPECT_EQ(1, entries.size());
entries.clear();
// Fake-mine the transaction
EXPECT_EQ(-1, chainActive.Height());
CBlock block;
block.vtx.push_back(wtx);
block.hashMerkleRoot = block.BuildMerkleTree();
auto blockHash = block.GetHash();
CBlockIndex fakeIndex {block};
mapBlockIndex.insert(std::make_pair(blockHash, &fakeIndex));
chainActive.SetTip(&fakeIndex);
EXPECT_TRUE(chainActive.Contains(&fakeIndex));
EXPECT_EQ(0, chainActive.Height());
wtx.SetMerkleBranch(block);
wallet.AddToWallet(wtx, true, NULL);
EXPECT_FALSE(wallet.IsSpent(nullifier));
// We now have an unspent and confirmed note in the wallet (depth of 1)
wallet.GetFilteredNotes(entries, "", 0);
EXPECT_EQ(1, entries.size());
entries.clear();
wallet.GetFilteredNotes(entries, "", 1);
EXPECT_EQ(1, entries.size());
entries.clear();
wallet.GetFilteredNotes(entries, "", 2);
EXPECT_EQ(0, entries.size());
entries.clear();
// Let's spend the note.
auto wtx2 = GetValidSpend(sk, note, 5);
wallet.AddToWallet(wtx2, true, NULL);
EXPECT_FALSE(wallet.IsSpent(nullifier));
// Fake-mine a spend transaction
EXPECT_EQ(0, chainActive.Height());
CBlock block2;
block2.vtx.push_back(wtx2);
block2.hashMerkleRoot = block2.BuildMerkleTree();
block2.hashPrevBlock = blockHash;
auto blockHash2 = block2.GetHash();
CBlockIndex fakeIndex2 {block2};
mapBlockIndex.insert(std::make_pair(blockHash2, &fakeIndex2));
fakeIndex2.nHeight = 1;
chainActive.SetTip(&fakeIndex2);
EXPECT_TRUE(chainActive.Contains(&fakeIndex2));
EXPECT_EQ(1, chainActive.Height());
wtx2.SetMerkleBranch(block2);
wallet.AddToWallet(wtx2, true, NULL);
EXPECT_TRUE(wallet.IsSpent(nullifier));
// The note has been spent. By default, GetFilteredNotes() ignores spent notes.
wallet.GetFilteredNotes(entries, "", 0);
EXPECT_EQ(0, entries.size());
entries.clear();
// Let's include spent notes to retrieve it.
wallet.GetFilteredNotes(entries, "", 0, false);
EXPECT_EQ(1, entries.size());
entries.clear();
// The spent note has two confirmations.
wallet.GetFilteredNotes(entries, "", 2, false);
EXPECT_EQ(1, entries.size());
entries.clear();
// It does not have 3 confirmations.
wallet.GetFilteredNotes(entries, "", 3, false);
EXPECT_EQ(0, entries.size());
entries.clear();
// Let's receive a new note
CWalletTx wtx3;
//.........这里部分代码省略.........