| 4596 | } |
| 4597 | |
| 4598 | void CChainState::LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp) |
| 4599 | { |
| 4600 | AssertLockNotHeld(m_chainstate_mutex); |
| 4601 | // Map of disk positions for blocks with unknown parent (only used for reindex) |
| 4602 | static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent; |
| 4603 | int64_t nStart = GetTimeMillis(); |
| 4604 | |
| 4605 | int nLoaded = 0; |
| 4606 | try { |
| 4607 | // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor |
| 4608 | CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION); |
| 4609 | uint64_t nRewind = blkdat.GetPos(); |
| 4610 | while (!blkdat.eof()) { |
| 4611 | if (ShutdownRequested()) return; |
| 4612 | |
| 4613 | blkdat.SetPos(nRewind); |
| 4614 | nRewind++; // start one byte further next time, in case of failure |
| 4615 | blkdat.SetLimit(); // remove former limit |
| 4616 | unsigned int nSize = 0; |
| 4617 | try { |
| 4618 | // locate a header |
| 4619 | unsigned char buf[CMessageHeader::MESSAGE_START_SIZE]; |
| 4620 | blkdat.FindByte(m_params.MessageStart()[0]); |
| 4621 | nRewind = blkdat.GetPos() + 1; |
| 4622 | blkdat >> buf; |
| 4623 | if (memcmp(buf, m_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) { |
| 4624 | continue; |
| 4625 | } |
| 4626 | // read size |
| 4627 | blkdat >> nSize; |
| 4628 | if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE) |
| 4629 | continue; |
| 4630 | } catch (const std::exception&) { |
| 4631 | // no valid block header found; don't complain |
| 4632 | break; |
| 4633 | } |
| 4634 | try { |
| 4635 | // read block |
| 4636 | uint64_t nBlockPos = blkdat.GetPos(); |
| 4637 | if (dbp) |
| 4638 | dbp->nPos = nBlockPos; |
| 4639 | blkdat.SetLimit(nBlockPos + nSize); |
| 4640 | std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); |
| 4641 | CBlock& block = *pblock; |
| 4642 | blkdat >> block; |
| 4643 | nRewind = blkdat.GetPos(); |
| 4644 | |
| 4645 | uint256 hash = block.GetHash(); |
| 4646 | { |
| 4647 | LOCK(cs_main); |
| 4648 | // detect out of order blocks, and store them for later |
| 4649 | if (hash != m_params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(block.hashPrevBlock)) { |
| 4650 | LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(), |
| 4651 | block.hashPrevBlock.ToString()); |
| 4652 | if (dbp) |
| 4653 | mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); |
| 4654 | continue; |
| 4655 | } |