Created
December 10, 2017 09:27
-
-
Save jngbng/77b73802ff9e26b99ce5e1104eeed9b6 to your computer and use it in GitHub Desktop.
bitcoincore read block snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// rest.cpp | |
// will be called with http request /rest/block/[BLOCK_HASH_VALUE] | |
static bool rest_block(HTTPRequest* req, const std::string& strURIPart, bool showTxDetails) | |
{ | |
// ... | |
uint256 hash; // will be parsed from `strURIPart` | |
CBlock block; | |
CBlockIndex* pblockindex = nullptr; | |
{ | |
LOCK(cs_main); | |
if (mapBlockIndex.count(hash) == 0) | |
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); | |
pblockindex = mapBlockIndex[hash]; | |
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) | |
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)"); | |
if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) | |
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); | |
} | |
// ... | |
} | |
// validation.cpp | |
// in-memory block index | |
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap; | |
BlockMap mapBlockIndex; | |
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams) | |
{ | |
// pindex->GetBlockPos() returns nFile(file number) and nDataPos(offset in the file) | |
if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams)) | |
return false; | |
// ... | |
} | |
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams) | |
{ | |
block.SetNull(); | |
// Open history file to read | |
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); | |
// ... | |
// Read block | |
try { | |
filein >> block; | |
} | |
catch (const std::exception& e) { | |
// ... | |
} | |
// ... | |
} | |
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) { | |
return OpenDiskFile(pos, "blk", fReadOnly); | |
} | |
static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) | |
{ | |
// ... | |
fs::path path = GetBlockPosFilename(pos, prefix); | |
// => GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile); | |
// ... | |
FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+"); | |
// ... | |
if (pos.nPos) { | |
if (fseek(file, pos.nPos, SEEK_SET)) { | |
// ... | |
} | |
} | |
return file; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment