Search in sources :

Example 1 with InvalidBlockException

use of org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException in project besu by hyperledger.

the class FastImportBlocksStep method accept.

@Override
public void accept(final List<BlockWithReceipts> blocksWithReceipts) {
    final long startTime = System.nanoTime();
    for (final BlockWithReceipts blockWithReceipts : blocksWithReceipts) {
        if (!importBlock(blockWithReceipts)) {
            throw new InvalidBlockException("Failed to import block", blockWithReceipts.getHeader().getNumber(), blockWithReceipts.getHash());
        }
        traceLambda(LOG, "Imported block {}", blockWithReceipts.getBlock()::toLogString);
    }
    if (logStartBlock.isEmpty()) {
        logStartBlock = OptionalLong.of(blocksWithReceipts.get(0).getNumber());
    }
    final long lastBlock = blocksWithReceipts.get(blocksWithReceipts.size() - 1).getNumber();
    // ethContext is not available in tests
    int peerCount = -1;
    if (ethContext != null && ethContext.getEthPeers().peerCount() >= 0) {
        peerCount = ethContext.getEthPeers().peerCount();
    }
    final long endTime = System.nanoTime();
    accumulatedTime += TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
    if (accumulatedTime > TEN_SECONDS) {
        LOG.info("Completed importing chain segment {} to {} ({} blocks in {}ms), Peers: {}", logStartBlock.getAsLong(), lastBlock, lastBlock - logStartBlock.getAsLong() + 1, accumulatedTime, peerCount);
        accumulatedTime = 0L;
        logStartBlock = OptionalLong.empty();
    }
}
Also used : InvalidBlockException(org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException) BlockWithReceipts(org.hyperledger.besu.ethereum.core.BlockWithReceipts)

Example 2 with InvalidBlockException

use of org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException in project besu by hyperledger.

the class RangeHeadersValidationStep method apply.

@Override
public Stream<BlockHeader> apply(final RangeHeaders rangeHeaders) {
    final BlockHeader rangeStart = rangeHeaders.getRange().getStart();
    final BlockHeader firstHeaderToImport = rangeHeaders.getFirstHeaderToImport();
    if (isValid(rangeStart, firstHeaderToImport)) {
        return rangeHeaders.getHeadersToImport().stream();
    } else {
        final String rangeEndDescription;
        if (rangeHeaders.getRange().hasEnd()) {
            final BlockHeader rangeEnd = rangeHeaders.getRange().getEnd();
            rangeEndDescription = String.format("#%d (%s)", rangeEnd.getNumber(), rangeEnd.getBlockHash());
        } else {
            rangeEndDescription = "chain head";
        }
        final String errorMessage = String.format("Invalid range headers.  Headers downloaded between #%d (%s) and %s do not connect at #%d (%s)", rangeStart.getNumber(), rangeStart.getHash(), rangeEndDescription, firstHeaderToImport.getNumber(), firstHeaderToImport.getHash());
        throw new InvalidBlockException(errorMessage, firstHeaderToImport.getNumber(), firstHeaderToImport.getHash());
    }
}
Also used : InvalidBlockException(org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 3 with InvalidBlockException

use of org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException in project besu by hyperledger.

the class FullImportBlockStep method accept.

@Override
public void accept(final Block block) {
    if (fullSyncTerminationCondition.shouldStopDownload()) {
        LOG.debug("Not importing another block, because terminal condition was reached.");
        return;
    }
    final long blockNumber = block.getHeader().getNumber();
    final String blockHash = block.getHash().toHexString();
    final BlockImporter importer = protocolSchedule.getByBlockNumber(blockNumber).getBlockImporter();
    if (!importer.importBlock(protocolContext, block, HeaderValidationMode.SKIP_DETACHED)) {
        throw new InvalidBlockException("Failed to import block", blockNumber, block.getHash());
    }
    gasAccumulator += block.getHeader().getGasUsed();
    // ethContext is not available in tests
    int peerCount = -1;
    if (ethContext != null && ethContext.getEthPeers().peerCount() >= 0) {
        peerCount = ethContext.getEthPeers().peerCount();
    }
    if (blockNumber % 200 == 0 || LOG.isTraceEnabled()) {
        final long nowMilli = Instant.now().toEpochMilli();
        final long deltaMilli = nowMilli - lastReportMillis;
        final String mgps = (lastReportMillis == 0 || gasAccumulator == 0) ? "-" : String.format("%.3f", gasAccumulator / 1000.0 / deltaMilli);
        LOG.info("Import reached block {} ({}), {} Mg/s, Peers: {}", blockNumber, blockHash, mgps, peerCount);
        lastReportMillis = nowMilli;
        gasAccumulator = 0;
    }
}
Also used : InvalidBlockException(org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException) BlockImporter(org.hyperledger.besu.ethereum.core.BlockImporter)

Example 4 with InvalidBlockException

use of org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException in project besu by hyperledger.

the class DownloadHeaderSequenceTask method processHeaders.

private CompletableFuture<List<BlockHeader>> processHeaders(final PeerTaskResult<List<BlockHeader>> headersResult) {
    return executeWorkerSubTask(ethContext.getScheduler(), () -> {
        final CompletableFuture<List<BlockHeader>> future = new CompletableFuture<>();
        BlockHeader child = null;
        boolean firstSkipped = false;
        final int previousHeaderIndex = lastFilledHeaderIndex;
        for (final BlockHeader header : headersResult.getResult()) {
            final int headerIndex = Ints.checkedCast(segmentLength - (referenceHeader.getNumber() - header.getNumber()));
            if (!firstSkipped) {
                // Skip over reference header
                firstSkipped = true;
                continue;
            }
            if (child == null) {
                child = (headerIndex == segmentLength - 1) ? referenceHeader : headers[headerIndex + 1];
            }
            final ProtocolSpec protocolSpec = protocolSchedule.getByBlockNumber(child.getNumber());
            final BadBlockManager badBlockManager = protocolSpec.getBadBlocksManager();
            if (!validateHeader(child, header)) {
                // Invalid headers - disconnect from peer
                final BlockHeader invalidBlock = child;
                // even though the header is known bad we are downloading the block body for the
                // debug_badBlocks RPC
                final AbstractPeerTask<Block> getBlockTask = GetBlockFromPeerTask.create(protocolSchedule, ethContext, Optional.of(child.getHash()), child.getNumber(), metricsSystem).assignPeer(headersResult.getPeer());
                getBlockTask.run().whenComplete((blockPeerTaskResult, error) -> {
                    if (error == null && blockPeerTaskResult.getResult() != null) {
                        badBlockManager.addBadBlock(blockPeerTaskResult.getResult());
                    }
                    headersResult.getPeer().disconnect(DisconnectReason.BREACH_OF_PROTOCOL);
                    LOG.debug("Received invalid headers from peer, disconnecting from: {}", headersResult.getPeer());
                    future.completeExceptionally(new InvalidBlockException("Header failed validation.", invalidBlock.getNumber(), invalidBlock.getHash()));
                });
                return future;
            }
            headers[headerIndex] = header;
            lastFilledHeaderIndex = headerIndex;
            child = header;
        }
        future.complete(asList(headers).subList(lastFilledHeaderIndex, previousHeaderIndex));
        return future;
    });
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) InvalidBlockException(org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException) ProtocolSpec(org.hyperledger.besu.ethereum.mainnet.ProtocolSpec) Block(org.hyperledger.besu.ethereum.core.Block) Arrays.asList(java.util.Arrays.asList) List(java.util.List) BadBlockManager(org.hyperledger.besu.ethereum.chain.BadBlockManager) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 5 with InvalidBlockException

use of org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException in project besu by hyperledger.

the class PersistBlockTask method executeTask.

@Override
protected void executeTask() {
    try {
        final ProtocolSpec protocolSpec = protocolSchedule.getByBlockNumber(block.getHeader().getNumber());
        final BlockImporter blockImporter = protocolSpec.getBlockImporter();
        debugLambda(LOG, "Running import task for block {}", block::toLogString);
        blockImported = blockImporter.importBlock(protocolContext, block, validateHeaders);
        if (!blockImported) {
            result.completeExceptionally(new InvalidBlockException("Failed to import block", block.getHeader().getNumber(), block.getHash()));
            return;
        }
        result.complete(block);
    } catch (final Exception e) {
        result.completeExceptionally(e);
    }
}
Also used : InvalidBlockException(org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException) ProtocolSpec(org.hyperledger.besu.ethereum.mainnet.ProtocolSpec) BlockImporter(org.hyperledger.besu.ethereum.core.BlockImporter) InvalidBlockException(org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException)

Aggregations

InvalidBlockException (org.hyperledger.besu.ethereum.eth.sync.tasks.exceptions.InvalidBlockException)7 BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)3 CompletableFuture (java.util.concurrent.CompletableFuture)2 BlockImporter (org.hyperledger.besu.ethereum.core.BlockImporter)2 ProtocolSpec (org.hyperledger.besu.ethereum.mainnet.ProtocolSpec)2 Arrays.asList (java.util.Arrays.asList)1 List (java.util.List)1 BadBlockManager (org.hyperledger.besu.ethereum.chain.BadBlockManager)1 Block (org.hyperledger.besu.ethereum.core.Block)1 BlockWithReceipts (org.hyperledger.besu.ethereum.core.BlockWithReceipts)1 SyncTarget (org.hyperledger.besu.ethereum.eth.sync.state.SyncTarget)1