本文整理汇总了C++中CBlock::ReadFromDisk方法的典型用法代码示例。如果您正苦于以下问题:C++ CBlock::ReadFromDisk方法的具体用法?C++ CBlock::ReadFromDisk怎么用?C++ CBlock::ReadFromDisk使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CBlock
的用法示例。
在下文中一共展示了CBlock::ReadFromDisk方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: ResetSyncCheckpoint
// Czecoin: reset synchronized checkpoint to last hardened checkpoint
bool ResetSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
const uint256& hash = mapCheckpoints.rbegin()->second;
if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
{
// checkpoint block accepted but not yet in main chain
printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
CTxDB txdb;
CBlock block;
if (!block.ReadFromDisk(mapBlockIndex[hash]))
return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
{
return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
}
}
else if(!mapBlockIndex.count(hash))
{
// checkpoint block not yet accepted
hashPendingCheckpoint = hash;
checkpointMessagePending.SetNull();
printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
}
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
{
if (!WriteSyncCheckpoint(hash))
return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
return true;
}
}
return false;
}
示例2: dumpbootstrap
Value dumpbootstrap(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"dumpbootstrap \"destination\" \"blocks\"\n"
"\nCreates a bootstrap format block dump of the blockchain in destination, which can be a directory or a path with filename, up to the given block number.");
string strDest = params[0].get_str();
int nBlocks = params[1].get_int();
if (nBlocks < 0 || nBlocks > nBestHeight)
throw runtime_error("Block number out of range.");
boost::filesystem::path pathDest(strDest);
if (boost::filesystem::is_directory(pathDest))
pathDest /= "bootstrap.dat";
try {
FILE* file = fopen(pathDest.string().c_str(), "wb");
if (!file)
throw JSONRPCError(RPC_MISC_ERROR, "Error: Could not open bootstrap file for writing.");
CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
if (!fileout)
throw JSONRPCError(RPC_MISC_ERROR, "Error: Could not open bootstrap file for writing.");
for (int nHeight = 0; nHeight <= nBlocks; nHeight++)
{
CBlock block;
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
block.ReadFromDisk(pblockindex, true);
fileout << FLATDATA(Params().MessageStart()) << fileout.GetSerializeSize(block) << block;
}
} catch(const boost::filesystem::filesystem_error &e) {
throw JSONRPCError(RPC_MISC_ERROR, "Error: Bootstrap dump failed!");
}
return Value::null;
}
示例3: getblock
Value getblock(const Array& params, bool fHelp, CACLUser &user) {
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [verbose=true]\n"
"If verbose is false, returns a string that is serialized, hex-encoded data for block <hash>.\n"
"If verbose is true, returns an Object with information about block <hash>."
);
if(!user.check(ACL_PUBLICREAD)) {
throw JSONRPCError(RPC_PERMISSION_DENIED, "Permission denied!");
}
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex);
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
示例4: getblockbynumber
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
示例5: LoadBlockIndex
//.........这里部分代码省略.........
pindexBest = mapBlockIndex[hashBestChain];
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexBest->nChainTrust;
printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// CurrentCoin: load hashSyncCheckpoint
if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
// Load bnBestInvalidTrust, OK if it doesn't exist
CBigNum bnBestInvalidTrust;
ReadBestInvalidTrust(bnBestInvalidTrust);
nBestInvalidTrust = bnBestInvalidTrust.getuint256();
// Verify blocks in the best chain
int nCheckLevel = GetArg("-checklevel", 1);
int nCheckDepth = GetArg( "-checkblocks", 2500);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
// check level 1: verify block validity
// check level 7: verify block signature too
if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
uint256 hashTx = tx.GetHash();
CTxIndex txindex;
if (ReadTxIndex(hashTx, txindex))
{
// check level 3: checker transaction hashes
if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
{
// either an error or a duplicate transaction
CTransaction txFound;
if (!txFound.ReadFromDisk(txindex.pos))
{
printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
else
if (txFound.GetHash() != hashTx) // not a duplicate tx
{
示例6: gameDb
// pindex must belong to the main branch, i.e. corresponding blocks must be connected
// Returns a copy of the game state
bool
GetGameState (DatabaseSet& dbset, CBlockIndex *pindex, GameState &outState)
{
if (!pindex)
{
outState = GameState();
return true;
}
/* See if we have the block in the state cache. */
if (stateCache.query (*pindex->phashBlock, outState))
return true;
// Get the latest saved state
CGameDB gameDb("r", dbset.tx ());
if (gameDb.Read(pindex->nHeight, outState))
{
if (outState.nHeight != pindex->nHeight)
return error("GetGameState: wrong height");
if (outState.hashBlock != *pindex->phashBlock)
return error("GetGameState: wrong hash");
return true;
}
if (!pindex->IsInMainChain())
return error("GetGameState called for non-main chain");
printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
printf("GetGameState: need to integrate state for height %d (current %d)\n",
pindex->nHeight, nBestHeight);
CBlockIndex *plast = pindex;
GameState lastState;
for (; plast->pprev; plast = plast->pprev)
{
if (stateCache.query (*plast->pprev->phashBlock, lastState))
break;
if (gameDb.Read(plast->pprev->nHeight, lastState))
break;
}
printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
printf("GetGameState: last saved block has height %d\n", lastState.nHeight);
// Integrate steps starting from the last saved state
// FIXME: Might want to store intermediate steps in stateCache, too.
loop
{
std::vector<CTransaction> vgametx;
CBlock block;
block.ReadFromDisk(plast);
int64 nTax;
if (!PerformStep (dbset.name (), lastState, &block, nTax,
outState, vgametx))
return false;
if (block.vgametx != vgametx)
{
printf("Error: GetGameState: computed vgametx is different from the stored one\n");
printf(" block %s (height = %d) vgametx:\n", block.GetHash().ToString().c_str(), plast->nHeight);
BOOST_FOREACH (const CTransaction &tx, block.vgametx)
{
printf(" ");
tx.print();
}
printf(" computed vgametx (height = %d):\n", outState.nHeight);
BOOST_FOREACH (const CTransaction &tx, vgametx)
{
printf(" ");
tx.print();
}
return false;
}
示例7: rewindchain
//.........这里部分代码省略.........
CAutoFile blkdat(fp, SER_DISK, CLIENT_VERSION);
if (fseek(blkdat, fpos+foundPos, SEEK_SET) != 0)
{
LogPrintf("fseek blkdat failed: %s\n", strerror(errno));
break;
};
unsigned int nSize;
blkdat >> nSize;
LogPrintf("nSize %u .\n", nSize);
if (nSize < 1 || nSize > MAX_BLOCK_SIZE)
{
LogPrintf("block size error %u\n", nSize);
};
CBlock block;
blkdat >> block;
uint256 hashblock = block.GetHash();
LogPrintf("hashblock %s .\n", hashblock.ToString().c_str());
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashblock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
LogPrintf("block is in main chain.\n");
if (!mi->second->pprev)
{
LogPrintf("! mi->second.pprev\n");
} else
{
{
CBlock blockPrev; // strange way SetBestChain works, TODO: does it need the full block?
if (!blockPrev.ReadFromDisk(mi->second->pprev))
{
LogPrintf("blockPrev.ReadFromDisk failed %s.\n", mi->second->pprev->GetBlockHash().ToString().c_str());
break;
};
CTxDB txdb;
if (!blockPrev.SetBestChain(txdb, mi->second->pprev))
{
LogPrintf("SetBestChain failed.\n");
};
}
mi->second->pprev->pnext = NULL;
};
delete mi->second;
mapBlockIndex.erase(mi);
};
std::map<uint256, COrphanBlock*>::iterator miOph = mapOrphanBlocks.find(hashblock);
if (miOph != mapOrphanBlocks.end())
{
LogPrintf("block is an orphan.\n");
mapOrphanBlocks.erase(miOph);
};
CTxDB txdb;
for (vector<CTransaction>::iterator it = block.vtx.begin(); it != block.vtx.end(); ++it)
{
LogPrintf("EraseTxIndex().\n");
txdb.EraseTxIndex(*it);
};
LogPrintf("EraseBlockIndex().\n");
txdb.EraseBlockIndex(hashblock);
errno = 0;
if (ftruncate(fileno(fp), fpos+foundPos-MESSAGE_START_SIZE) != 0)
{
LogPrintf("ftruncate failed: %s\n", strerror(errno));
};
LogPrintf("hashBestChain %s, nBestHeight %d\n", hashBestChain.ToString().c_str(), nBestHeight);
//fclose(fp); // ~CAutoFile() will close the file
nRemoved++;
};
}
result.push_back(Pair("no. blocks removed", itostr(nRemoved)));
result.push_back(Pair("hashBestChain", hashBestChain.ToString()));
result.push_back(Pair("nBestHeight", itostr(nBestHeight)));
// -- need restart, setStakeSeen etc
if (nRemoved > 0)
result.push_back(Pair("Please restart Taurus", ""));
if (nRemoved == nNumber)
result.push_back(Pair("result", "success"));
else
result.push_back(Pair("result", "failure"));
return result;
}
示例8: GetGameState
// pindex must belong to the main branch, i.e. corresponding blocks must be connected
// Returns a copy of the game state
bool GetGameState(CTxDB &txdb, CBlockIndex *pindex, GameState &outState)
{
if (!pindex)
{
outState = GameState();
return true;
}
if (*pindex->phashBlock == currentState.hashBlock)
{
outState = currentState;
return true;
}
// Get the latest saved state
CGameDB gameDb("cr", txdb);
if (gameDb.Read(pindex->nHeight, outState))
{
if (outState.nHeight != pindex->nHeight)
return error("GetGameState: wrong height");
if (outState.hashBlock != *pindex->phashBlock)
return error("GetGameState: wrong hash");
return true;
}
if (!pindex->IsInMainChain())
return error("GetGameState called for non-main chain");
CBlockIndex *plast = pindex;
GameState lastState;
for (; plast->pprev; plast = plast->pprev)
{
if (gameDb.Read(plast->pprev->nHeight, lastState))
break;
}
// When connecting genesis block, there is no nameindexfull.dat file yet
std::auto_ptr<CNameDB> nameDb(pindex == pindexGenesisBlock ? NULL : new CNameDB("r", txdb));
// Integrate steps starting from the last saved state
loop
{
std::vector<CTransaction> vgametx;
CBlock block;
block.ReadFromDisk(plast);
int64 nTax;
if (!PerformStep(nameDb.get(), lastState, &block, nTax, outState, vgametx))
return false;
if (block.vgametx != vgametx)
{
printf("Error: GetGameState: computed vgametx is different from the stored one\n");
printf(" block %s (height = %d) vgametx:\n", block.GetHash().ToString().c_str(), plast->nHeight);
BOOST_FOREACH (const CTransaction &tx, block.vgametx)
{
printf(" ");
tx.print();
}
printf(" computed vgametx (height = %d):\n", outState.nHeight);
BOOST_FOREACH (const CTransaction &tx, vgametx)
{
printf(" ");
tx.print();
}
return false;
}
示例9: AppInit2
//.........这里部分代码省略.........
uiInterface.InitMessage(_("Loading block index..."));
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)
示例10: listtopprimes
// pNut: list top prime chain within pnut network
Value listtopprimes(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"listtopprimes <primechain length> [primechain type]\n"
"Returns the list of top prime chains in pnut network.\n"
"<primechain length> is integer like 10, 11, 12 etc.\n"
"[primechain type] is optional type, among 1CC, 2CC and TWN");
int nPrimeChainLength = params[0].get_int();
unsigned int nPrimeChainType = 0;
if (params.size() > 1)
{
std::string strPrimeChainType = params[1].get_str();
if (strPrimeChainType.compare("1CC") == 0)
nPrimeChainType = PRIME_CHAIN_CUNNINGHAM1;
else if (strPrimeChainType.compare("2CC") == 0)
nPrimeChainType = PRIME_CHAIN_CUNNINGHAM2;
else if (strPrimeChainType.compare("TWN") == 0)
nPrimeChainType = PRIME_CHAIN_BI_TWIN;
else
throw runtime_error("Prime chain type must be 1CC, 2CC or TWN.");
}
// Search for top prime chains
unsigned int nRankingSize = 10; // ranking list size
unsigned int nSortVectorSize = 64; // vector size for sort operation
CBigNum bnPrimeQualify = 0; // minimum qualify value for ranking list
vector<pair<CBigNum, uint256> > vSortedByOrigin;
for (CBlockIndex* pindex = pindexGenesisBlock; pindex; pindex = pindex->pnext)
{
if (nPrimeChainLength != (int) TargetGetLength(pindex->nPrimeChainLength))
continue; // length not matching, next block
if (nPrimeChainType && nPrimeChainType != pindex->nPrimeChainType)
continue; // type not matching, next block
CBlock block;
block.ReadFromDisk(pindex); // read block
CBigNum bnPrimeChainOrigin = CBigNum(block.GetHeaderHash()) * block.bnPrimeChainMultiplier; // compute prime chain origin
if (bnPrimeChainOrigin > bnPrimeQualify)
vSortedByOrigin.push_back(make_pair(bnPrimeChainOrigin, block.GetHash()));
if (vSortedByOrigin.size() >= nSortVectorSize)
{
// Sort prime chain candidates
sort(vSortedByOrigin.begin(), vSortedByOrigin.end());
reverse(vSortedByOrigin.begin(), vSortedByOrigin.end());
// Truncate candidate list
while (vSortedByOrigin.size() > nRankingSize)
vSortedByOrigin.pop_back();
// Update minimum qualify value for top prime chains
bnPrimeQualify = vSortedByOrigin.back().first;
}
}
// Final sort of prime chain candidates
sort(vSortedByOrigin.begin(), vSortedByOrigin.end());
reverse(vSortedByOrigin.begin(), vSortedByOrigin.end());
// Truncate candidate list
while (vSortedByOrigin.size() > nRankingSize)
vSortedByOrigin.pop_back();
// Output top prime chains
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBigNum, uint256)& item, vSortedByOrigin)
{
CBigNum bnPrimeChainOrigin = item.first;
CBlockIndex* pindex = mapBlockIndex[item.second];
CBlock block;
block.ReadFromDisk(pindex); // read block
Object entry;
entry.push_back(Pair("time", DateTimeStrFormat("%Y-%m-%d %H:%M:%S UTC", pindex->GetBlockTime()).c_str()));
entry.push_back(Pair("epoch", (boost::int64_t) pindex->GetBlockTime()));
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("ismine", pwalletMain->IsMine(block.vtx[0])));
CTxDestination address;
entry.push_back(Pair("mineraddress", (block.vtx[0].vout.size() > 1)? "multiple" : ExtractDestination(block.vtx[0].vout[0].scriptPubKey, address)? CBitcoinAddress(address).ToString().c_str() : "invalid"));
entry.push_back(Pair("primedigit", (int) bnPrimeChainOrigin.ToString().length()));
entry.push_back(Pair("primechain", GetPrimeChainName(pindex->nPrimeChainType, pindex->nPrimeChainLength).c_str()));
entry.push_back(Pair("primeorigin", bnPrimeChainOrigin.ToString().c_str()));
entry.push_back(Pair("primorialform", GetPrimeOriginPrimorialForm(bnPrimeChainOrigin).c_str()));
ret.push_back(entry);
}
return ret;
}
示例11: scaninput
Value scaninput(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 4 || params.size() < 2)
throw runtime_error(
"scaninput <txid> <nout> [difficulty] [days]\n"
"Scan specified input for suitable kernel solutions.\n"
" [difficulty] - upper limit for difficulty, current difficulty by default;\n"
" [days] - time window, 365 days by default.\n"
);
uint256 hash;
hash.SetHex(params[0].get_str());
uint32_t nOut = params[1].get_int(), nBits = GetNextTargetRequired(pindexBest, true), nDays = 365;
if (params.size() > 2)
{
CBigNum bnTarget(nPoWBase);
bnTarget *= 1000;
bnTarget /= (int) (params[2].get_real() * 1000);
nBits = bnTarget.GetCompact();
}
if (params.size() > 3)
{
nDays = params[3].get_int();
}
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
if (nOut > tx.vout.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect output number");
if (hashBlock == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
CTxDB txdb("r");
CBlock block;
CTxIndex txindex;
// Load transaction index item
if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
// Read block header
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
uint64_t nStakeModifier = 0;
if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
std::pair<uint32_t, uint32_t> interval;
interval.first = GetTime();
// Only count coins meeting min age requirement
if (nStakeMinAge + block.nTime > interval.first)
interval.first += (nStakeMinAge + block.nTime - interval.first);
interval.second = interval.first + nDays * 86400;
SHA256_CTX ctx;
GetKernelMidstate(nStakeModifier, block.nTime, txindex.pos.nTxPos - txindex.pos.nBlockPos, tx.nTime, nOut, ctx);
std::pair<uint256, uint32_t> solution;
if (ScanMidstateForward(ctx, nBits, tx.nTime, tx.vout[nOut].nValue, interval, solution))
{
Object r;
r.push_back(Pair("hash", solution.first.GetHex()));
r.push_back(Pair("time", DateTimeStrFormat(solution.second)));
return r;
}
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
return Value::null;
}
示例12: getstakers
Value getstakers(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"getstakers <min block> <max block> [total]"
"Returns array of stakers in between min and max block, inclusive."
" If [total] is provided, outputs an array of stakers with proportionate amounts. Can be used as input to sendmany for dividends.");
int nHeight = params[0].get_int();
int max = params[1].get_int();
double amount = 0.0, amountEach = 0.0;
int amtProvided = 0;
int iCount = 0;
std::string outStr(" '{");
if (max < nHeight)
throw runtime_error("Max Block is less than Min Block.");
if (nHeight < 20161 || nHeight > nBestHeight)
throw runtime_error("Min Block number out of range. (First PoS Block: 20,161)");
if (max < 0 || max > nBestHeight)
throw runtime_error("Max Block number out of range.");
if(params.size() >= 3)
{
amount = params[2].get_real();
if( amount / (max - nHeight + 1) < 1)
throw runtime_error("Amount is less than 1 BTCD per staker.");
amountEach = amount/(max-nHeight+1);
amtProvided = 1;
}
//Find Min. Block
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
CTransaction tx;
CTxOut txout;
uint256 txHash = 0;
uint256 hash;
vector<CTxDestination> addresses;
int nRequired;
txnouttype type;
Object entry;
Object result;
std::ostringstream s;
s << amountEach;
std::string strAmount = s.str();
for(iCount = nHeight; iCount <= max; iCount++)
{
hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
tx = block.vtx[1];
txout = tx.vout[1];
txHash = tx.GetHash();
addresses.clear();
ExtractDestinations(txout.scriptPubKey, type, addresses, nRequired);
outStr += std::string("\"") +
CBitcoinAddress(addresses[0]).ToString() +
std::string("\"");
if(amtProvided == 1)
{
outStr += std::string(": ") +
strAmount;
if( iCount != max)
outStr += std::string(", ");
}
else
if( iCount != max)
outStr += std::string(", ");
pblockindex = pblockindex->pnext;
}
outStr += std::string("}' ");
char *finalString = (char*)outStr.c_str();
result.push_back(Pair("Addresses:", std::string(unstringify(finalString))));
return result;
}
示例13: loadStakeChart
void ProfitExplorerPage::loadStakeChart(bool firstRun)
{
if(fShutdown)
return;
nTimeData.clear();
netStakeData.clear();
myStakeData.clear();
difficultyData.clear();
velTimeData.clear();
velAmountData.clear();
// go back this many blocks max
int max = ui->spinBox->value();
int i = 0;
//BOOST_REVERSE_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& b, mapBlockIndex)
//{
// if(i >= max)
// break;
CBlockIndex* pindex = pindexBest;
while(i < max && pindex != NULL)
{
//CBlockIndex* pindex = b.second;
if(pindex->IsProofOfStake())
{
nTimeData.append(pindex->nTime);
netStakeData.append(pindex->nMint / COIN);
// Read the block in and check if the coinstake is ours
CBlock block;
block.ReadFromDisk(pindex, true);
if(block.IsProofOfStake()) // this should always be true here
{
velTimeData.append(pindex->nTime);
double blockOutAmount = 0;
for(int j=0; j<block.vtx.size(); j++)
{
blockOutAmount += block.vtx[j].GetValueOut() / COIN;
}
velAmountData.append(blockOutAmount);
difficultyData.append(GetDifficulty(pindex));
if(pwalletMain->IsMine(block.vtx[1]))
{
myStakeData.append(pindex->nMint / COIN);
}
else
{
myStakeData.append(0);
}
}
else
{
myStakeData.append(0); // should never happen
}
i = i + 1;
}
pindex = pindex->pprev;
//++i;
}
if(!firstRun)
{
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
uint64_t nNetworkWeight = 0;
if(pindexBest)
nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1;
ui->stakingLabel->setText(staking ? "Enabled" : "Disabled");
if(pindexBest)
ui->difficultyLabel->setText(QString::number(GetDifficulty(GetLastBlockIndex(pindexBest, true))));
ui->weightLabel->setText(QString::number(nWeight));
ui->netWeightLabel->setText(QString::number(nNetworkWeight));
ui->timeToStakeLabel->setText(QString::number(nExpectedTime) + " secs");
}
//qDebug() << "Stake blocks processed:";
//qDebug() << i;
ui->customPlot->clearPlottables();
ui->customPlot->clearGraphs();
ui->customPlot->clearItems();
ui->customPlot->addGraph();
ui->customPlot->graph(0)->setPen(QPen(QColor(206, 206, 206))); // line color green for first graph
ui->customPlot->graph(0)->setBrush(QBrush(QColor(206, 206, 206, 20))); // first graph will be filled with translucent green
ui->customPlot->addGraph();
ui->customPlot->graph(1)->setPen(QPen(QColor(76, 255, 0))); // line color red for second graph
ui->customPlot->graph(1)->setBrush(QBrush(QColor(76, 255, 0, 20)));
if(ui->networkCheckBox->isChecked())
ui->customPlot->graph(0)->setData(nTimeData, netStakeData);
ui->customPlot->graph(1)->setData(nTimeData, myStakeData);
//ui->customPlot->xAxis->setRangeLower(nTimeData.first());
//ui->customPlot->xAxis->setRangeUpper(nTimeData.last());
QLinearGradient plotGradient;
//.........这里部分代码省略.........
示例14: LoadBlockIndex
//.........这里部分代码省略.........
nCounter = 0;
//#ifdef _MSC_VER
#ifdef _DEBUG
/****************
const int
nMINUTESperBLOCK = 1, // or whatever you want to do in this *coin
nMINUTESperHOUR = 60,
nBLOCKSperHOUR = nMINUTESperHOUR / nMINUTESperBLOCK,
nHOURStoCHECK = 1, //12, // this could be a variable
nBLOCKSinLASTwhateverHOURS = nBLOCKSperHOUR * nHOURStoCHECK;
nCheckDepth = nBLOCKSinLASTwhateverHOURS;
****************/
#endif
//#endif
#ifdef QT_GUI
std::string
sX;
uiInterface.InitMessage(
strprintf( _("Verifying the last %i blocks at level %i"),
nCheckDepth, nCheckLevel
).c_str()
);
#endif
#endif
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
// check level 1: verify block validity
// check level 7: verify block signature too
if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
uint256 hashTx = tx.GetHash();
CTxIndex txindex;
if (ReadTxIndex(hashTx, txindex))
{
// check level 3: checker transaction hashes
if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
{
// either an error or a duplicate transaction
CTransaction txFound;
if (!txFound.ReadFromDisk(txindex.pos))
{
printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
else
if (txFound.GetHash() != hashTx) // not a duplicate tx
{
示例15: LoadBlockIndex
bool CTxDB::LoadBlockIndex()
{
if (!LoadBlockIndexGuts())
return false;
if (fRequestShutdown)
return true;
// Calculate bnChainTrust
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->bnChainTrust = (pindex->pprev ? pindex->pprev->bnChainTrust : 0) + pindex->GetBlockTrust();
// ppcoin: calculate stake modifier checksum
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
}
// Load hashBestChain pointer to end of best chain
if (!ReadHashBestChain(hashBestChain))
{
if (pindexGenesisBlock == NULL)
return true;
return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
}
if (!mapBlockIndex.count(hashBestChain))
return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
pindexBest = mapBlockIndex[hashBestChain];
nBestHeight = pindexBest->nHeight;
bnBestChainTrust = pindexBest->bnChainTrust;
printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// ppcoin: load hashSyncCheckpoint
if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
// Load bnBestInvalidTrust, OK if it doesn't exist
ReadBestInvalidTrust(bnBestInvalidTrust);
// Verify blocks in the best chain
int nCheckLevel = GetArg("-checklevel", 1);
int nCheckDepth = GetArg( "-checkblocks", 2500);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
// check level 1: verify block validity
if (nCheckLevel>0 && !block.CheckBlock())
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
uint256 hashTx = tx.GetHash();
CTxIndex txindex;
if (ReadTxIndex(hashTx, txindex))
{
// check level 3: checker transaction hashes
if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
{
// either an error or a duplicate transaction
CTransaction txFound;
if (!txFound.ReadFromDisk(txindex.pos))
{
printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
else
if (txFound.GetHash() != hashTx) // not a duplicate tx
{
printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
//.........这里部分代码省略.........