id
stringlengths
7
14
text
stringlengths
1
106k
206414745_1542
public CompletableFuture<FastSyncState> downloadPivotBlockHeader( final FastSyncState currentState) { if (currentState.getPivotBlockHeader().isPresent()) { return completedFuture(currentState); } return new PivotBlockRetriever( protocolSchedule, ethContext, metricsSystem, currentState.getPivotBlockNumber().getAsLong(), syncConfig.getFastSyncMinimumPeerCount(), syncConfig.getFastSyncPivotDistance()) .downloadPivotBlockHeader(); }
206414745_1543
public CompletableFuture<FastSyncState> downloadPivotBlockHeader( final FastSyncState currentState) { if (currentState.getPivotBlockHeader().isPresent()) { return completedFuture(currentState); } return new PivotBlockRetriever( protocolSchedule, ethContext, metricsSystem, currentState.getPivotBlockNumber().getAsLong(), syncConfig.getFastSyncMinimumPeerCount(), syncConfig.getFastSyncPivotDistance()) .downloadPivotBlockHeader(); }
206414745_1544
public static Optional<FastSyncDownloader> create( final SynchronizerConfiguration syncConfig, final Path dataDirectory, final ProtocolSchedule protocolSchedule, final ProtocolContext protocolContext, final MetricsSystem metricsSystem, final EthContext ethContext, final WorldStateStorage worldStateStorage, final SyncState syncState, final Clock clock) { final Path fastSyncDataDirectory = dataDirectory.resolve(FAST_SYNC_FOLDER); final FastSyncStateStorage fastSyncStateStorage = new FastSyncStateStorage(fastSyncDataDirectory); if (syncConfig.getSyncMode() != SyncMode.FAST) { if (fastSyncStateStorage.isFastSyncInProgress()) { throw new IllegalStateException( "Unable to change the sync mode when fast sync is incomplete, please restart with fast sync mode"); } else { return Optional.empty(); } } ensureDirectoryExists(fastSyncDataDirectory.toFile()); final FastSyncState fastSyncState = fastSyncStateStorage.loadState(ScheduleBasedBlockHeaderFunctions.create(protocolSchedule)); if (fastSyncState.getPivotBlockHeader().isEmpty() && protocolContext.getBlockchain().getChainHeadBlockNumber() != BlockHeader.GENESIS_BLOCK_NUMBER) { LOG.info( "Fast sync was requested, but cannot be enabled because the local blockchain is not empty."); return Optional.empty(); } final CachingTaskCollection<NodeDataRequest> taskCollection = createWorldStateDownloaderTaskCollection( getStateQueueDirectory(dataDirectory), metricsSystem, syncConfig.getWorldStateTaskCacheSize()); final WorldStateDownloader worldStateDownloader = new WorldStateDownloader( ethContext, worldStateStorage, taskCollection, syncConfig.getWorldStateHashCountPerRequest(), syncConfig.getWorldStateRequestParallelism(), syncConfig.getWorldStateMaxRequestsWithoutProgress(), syncConfig.getWorldStateMinMillisBeforeStalling(), clock, metricsSystem); final FastSyncDownloader fastSyncDownloader = new FastSyncDownloader( new FastSyncActions( syncConfig, protocolSchedule, protocolContext, ethContext, syncState, metricsSystem), worldStateDownloader, fastSyncStateStorage, taskCollection, fastSyncDataDirectory, fastSyncState); syncState.setWorldStateDownloadStatus(worldStateDownloader); return Optional.of(fastSyncDownloader); }
206414745_1545
public static Optional<FastSyncDownloader> create( final SynchronizerConfiguration syncConfig, final Path dataDirectory, final ProtocolSchedule protocolSchedule, final ProtocolContext protocolContext, final MetricsSystem metricsSystem, final EthContext ethContext, final WorldStateStorage worldStateStorage, final SyncState syncState, final Clock clock) { final Path fastSyncDataDirectory = dataDirectory.resolve(FAST_SYNC_FOLDER); final FastSyncStateStorage fastSyncStateStorage = new FastSyncStateStorage(fastSyncDataDirectory); if (syncConfig.getSyncMode() != SyncMode.FAST) { if (fastSyncStateStorage.isFastSyncInProgress()) { throw new IllegalStateException( "Unable to change the sync mode when fast sync is incomplete, please restart with fast sync mode"); } else { return Optional.empty(); } } ensureDirectoryExists(fastSyncDataDirectory.toFile()); final FastSyncState fastSyncState = fastSyncStateStorage.loadState(ScheduleBasedBlockHeaderFunctions.create(protocolSchedule)); if (fastSyncState.getPivotBlockHeader().isEmpty() && protocolContext.getBlockchain().getChainHeadBlockNumber() != BlockHeader.GENESIS_BLOCK_NUMBER) { LOG.info( "Fast sync was requested, but cannot be enabled because the local blockchain is not empty."); return Optional.empty(); } final CachingTaskCollection<NodeDataRequest> taskCollection = createWorldStateDownloaderTaskCollection( getStateQueueDirectory(dataDirectory), metricsSystem, syncConfig.getWorldStateTaskCacheSize()); final WorldStateDownloader worldStateDownloader = new WorldStateDownloader( ethContext, worldStateStorage, taskCollection, syncConfig.getWorldStateHashCountPerRequest(), syncConfig.getWorldStateRequestParallelism(), syncConfig.getWorldStateMaxRequestsWithoutProgress(), syncConfig.getWorldStateMinMillisBeforeStalling(), clock, metricsSystem); final FastSyncDownloader fastSyncDownloader = new FastSyncDownloader( new FastSyncActions( syncConfig, protocolSchedule, protocolContext, ethContext, syncState, metricsSystem), worldStateDownloader, fastSyncStateStorage, taskCollection, fastSyncDataDirectory, fastSyncState); syncState.setWorldStateDownloadStatus(worldStateDownloader); return Optional.of(fastSyncDownloader); }
206414745_1546
public static Optional<FastSyncDownloader> create( final SynchronizerConfiguration syncConfig, final Path dataDirectory, final ProtocolSchedule protocolSchedule, final ProtocolContext protocolContext, final MetricsSystem metricsSystem, final EthContext ethContext, final WorldStateStorage worldStateStorage, final SyncState syncState, final Clock clock) { final Path fastSyncDataDirectory = dataDirectory.resolve(FAST_SYNC_FOLDER); final FastSyncStateStorage fastSyncStateStorage = new FastSyncStateStorage(fastSyncDataDirectory); if (syncConfig.getSyncMode() != SyncMode.FAST) { if (fastSyncStateStorage.isFastSyncInProgress()) { throw new IllegalStateException( "Unable to change the sync mode when fast sync is incomplete, please restart with fast sync mode"); } else { return Optional.empty(); } } ensureDirectoryExists(fastSyncDataDirectory.toFile()); final FastSyncState fastSyncState = fastSyncStateStorage.loadState(ScheduleBasedBlockHeaderFunctions.create(protocolSchedule)); if (fastSyncState.getPivotBlockHeader().isEmpty() && protocolContext.getBlockchain().getChainHeadBlockNumber() != BlockHeader.GENESIS_BLOCK_NUMBER) { LOG.info( "Fast sync was requested, but cannot be enabled because the local blockchain is not empty."); return Optional.empty(); } final CachingTaskCollection<NodeDataRequest> taskCollection = createWorldStateDownloaderTaskCollection( getStateQueueDirectory(dataDirectory), metricsSystem, syncConfig.getWorldStateTaskCacheSize()); final WorldStateDownloader worldStateDownloader = new WorldStateDownloader( ethContext, worldStateStorage, taskCollection, syncConfig.getWorldStateHashCountPerRequest(), syncConfig.getWorldStateRequestParallelism(), syncConfig.getWorldStateMaxRequestsWithoutProgress(), syncConfig.getWorldStateMinMillisBeforeStalling(), clock, metricsSystem); final FastSyncDownloader fastSyncDownloader = new FastSyncDownloader( new FastSyncActions( syncConfig, protocolSchedule, protocolContext, ethContext, syncState, metricsSystem), worldStateDownloader, fastSyncStateStorage, taskCollection, fastSyncDataDirectory, fastSyncState); syncState.setWorldStateDownloadStatus(worldStateDownloader); return Optional.of(fastSyncDownloader); }
206414745_1547
public CompletableFuture<FastSyncState> confirmPivotBlock() { if (isStarted.compareAndSet(false, true)) { LOG.info( "Confirm pivot block {} with at least {} peers.", pivotBlockNumber, numberOfPeersToQuery); queryPeers(pivotBlockNumber); } return result; }
206414745_1548
public CompletableFuture<FastSyncState> confirmPivotBlock() { if (isStarted.compareAndSet(false, true)) { LOG.info( "Confirm pivot block {} with at least {} peers.", pivotBlockNumber, numberOfPeersToQuery); queryPeers(pivotBlockNumber); } return result; }
206414745_1549
public CompletableFuture<FastSyncState> confirmPivotBlock() { if (isStarted.compareAndSet(false, true)) { LOG.info( "Confirm pivot block {} with at least {} peers.", pivotBlockNumber, numberOfPeersToQuery); queryPeers(pivotBlockNumber); } return result; }
206414745_1550
public CompletableFuture<FastSyncState> confirmPivotBlock() { if (isStarted.compareAndSet(false, true)) { LOG.info( "Confirm pivot block {} with at least {} peers.", pivotBlockNumber, numberOfPeersToQuery); queryPeers(pivotBlockNumber); } return result; }
206414745_1551
public CompletableFuture<FastSyncState> confirmPivotBlock() { if (isStarted.compareAndSet(false, true)) { LOG.info( "Confirm pivot block {} with at least {} peers.", pivotBlockNumber, numberOfPeersToQuery); queryPeers(pivotBlockNumber); } return result; }
206414745_1552
public CompletableFuture<FastSyncState> confirmPivotBlock() { if (isStarted.compareAndSet(false, true)) { LOG.info( "Confirm pivot block {} with at least {} peers.", pivotBlockNumber, numberOfPeersToQuery); queryPeers(pivotBlockNumber); } return result; }
206414745_1553
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1554
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1555
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1556
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1557
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1558
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1559
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1560
public CompletableFuture<FastSyncState> downloadPivotBlockHeader() { if (isStarted.compareAndSet(false, true)) { LOG.info("Retrieve a pivot block that can be confirmed by at least {} peers.", peersToQuery); confirmBlock(pivotBlockNumber.get()); } return result; }
206414745_1561
public CompletableFuture<FastSyncState> start() { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("FastSyncDownloader already running"); } return start(initialFastSyncState); }
206414745_1562
public CompletableFuture<FastSyncState> start() { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("FastSyncDownloader already running"); } return start(initialFastSyncState); }
206414745_1563
public CompletableFuture<FastSyncState> start() { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("FastSyncDownloader already running"); } return start(initialFastSyncState); }
206414745_1564
public CompletableFuture<FastSyncState> start() { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("FastSyncDownloader already running"); } return start(initialFastSyncState); }
206414745_1565
public CompletableFuture<FastSyncState> start() { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("FastSyncDownloader already running"); } return start(initialFastSyncState); }
206414745_1566
@Override public void accept(final List<BlockWithReceipts> blocksWithReceipts) { for (final BlockWithReceipts blockWithReceipts : blocksWithReceipts) { if (!importBlock(blockWithReceipts)) { throw new InvalidBlockException( "Failed to import block", blockWithReceipts.getHeader().getNumber(), blockWithReceipts.getHash()); } } final long firstBlock = blocksWithReceipts.get(0).getNumber(); final long lastBlock = blocksWithReceipts.get(blocksWithReceipts.size() - 1).getNumber(); int peerCount = -1; // ethContext is not available in tests if (ethContext != null && ethContext.getEthPeers().peerCount() >= 0) { peerCount = ethContext.getEthPeers().peerCount(); } LOG.info( "Completed importing chain segment {} to {}, Peers: {}", firstBlock, lastBlock, peerCount); }
206414745_1567
@Override public void accept(final List<BlockWithReceipts> blocksWithReceipts) { for (final BlockWithReceipts blockWithReceipts : blocksWithReceipts) { if (!importBlock(blockWithReceipts)) { throw new InvalidBlockException( "Failed to import block", blockWithReceipts.getHeader().getNumber(), blockWithReceipts.getHash()); } } final long firstBlock = blocksWithReceipts.get(0).getNumber(); final long lastBlock = blocksWithReceipts.get(blocksWithReceipts.size() - 1).getNumber(); int peerCount = -1; // ethContext is not available in tests if (ethContext != null && ethContext.getEthPeers().peerCount() >= 0) { peerCount = ethContext.getEthPeers().peerCount(); } LOG.info( "Completed importing chain segment {} to {}, Peers: {}", firstBlock, lastBlock, peerCount); }
206414745_1568
@Override public CompletableFuture<List<BlockWithReceipts>> apply(final List<Block> blocks) { final List<BlockHeader> headers = blocks.stream().map(Block::getHeader).collect(toList()); final CompletableFuture<Map<BlockHeader, List<TransactionReceipt>>> getReceipts = GetReceiptsForHeadersTask.forHeaders(ethContext, headers, metricsSystem).run(); final CompletableFuture<List<BlockWithReceipts>> combineWithBlocks = getReceipts.thenApply( receiptsByHeader -> combineBlocksAndReceipts(blocks, receiptsByHeader)); FutureUtils.propagateCancellation(combineWithBlocks, getReceipts); return combineWithBlocks; }
206414745_1569
@Override public CompletableFuture<CheckpointRangeHeaders> apply(final CheckpointRange checkpointRange) { final CompletableFuture<List<BlockHeader>> taskFuture = downloadHeaders(checkpointRange); final CompletableFuture<CheckpointRangeHeaders> processedFuture = taskFuture.thenApply(headers -> processHeaders(checkpointRange, headers)); FutureUtils.propagateCancellation(processedFuture, taskFuture); return processedFuture; }
206414745_1570
@Override public CompletableFuture<CheckpointRangeHeaders> apply(final CheckpointRange checkpointRange) { final CompletableFuture<List<BlockHeader>> taskFuture = downloadHeaders(checkpointRange); final CompletableFuture<CheckpointRangeHeaders> processedFuture = taskFuture.thenApply(headers -> processHeaders(checkpointRange, headers)); FutureUtils.propagateCancellation(processedFuture, taskFuture); return processedFuture; }
206414745_1571
@Override public CompletableFuture<CheckpointRangeHeaders> apply(final CheckpointRange checkpointRange) { final CompletableFuture<List<BlockHeader>> taskFuture = downloadHeaders(checkpointRange); final CompletableFuture<CheckpointRangeHeaders> processedFuture = taskFuture.thenApply(headers -> processHeaders(checkpointRange, headers)); FutureUtils.propagateCancellation(processedFuture, taskFuture); return processedFuture; }
206414745_1572
@Override public CompletableFuture<CheckpointRangeHeaders> apply(final CheckpointRange checkpointRange) { final CompletableFuture<List<BlockHeader>> taskFuture = downloadHeaders(checkpointRange); final CompletableFuture<CheckpointRangeHeaders> processedFuture = taskFuture.thenApply(headers -> processHeaders(checkpointRange, headers)); FutureUtils.propagateCancellation(processedFuture, taskFuture); return processedFuture; }
206414745_1573
public CompletableFuture<List<BlockHeader>> getNextCheckpointHeaders( final EthPeer peer, final BlockHeader previousCheckpointHeader) { final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final int maximumHeaderRequestSize = syncConfig.getDownloaderHeaderRequestSize(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); final int additionalHeaderCount; if (finalCheckpointHeader.isPresent()) { final BlockHeader targetHeader = finalCheckpointHeader.get(); final long blocksUntilTarget = targetHeader.getNumber() - previousCheckpointNumber; if (blocksUntilTarget <= 0) { return completedFuture(emptyList()); } final long maxHeadersToRequest = blocksUntilTarget / (skip + 1); additionalHeaderCount = (int) Math.min(maxHeadersToRequest, maximumHeaderRequestSize); if (additionalHeaderCount == 0) { return completedFuture(singletonList(targetHeader)); } } else { additionalHeaderCount = maximumHeaderRequestSize; } return requestHeaders(peer, previousCheckpointHeader, additionalHeaderCount, skip); }
206414745_1574
public CompletableFuture<List<BlockHeader>> getNextCheckpointHeaders( final EthPeer peer, final BlockHeader previousCheckpointHeader) { final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final int maximumHeaderRequestSize = syncConfig.getDownloaderHeaderRequestSize(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); final int additionalHeaderCount; if (finalCheckpointHeader.isPresent()) { final BlockHeader targetHeader = finalCheckpointHeader.get(); final long blocksUntilTarget = targetHeader.getNumber() - previousCheckpointNumber; if (blocksUntilTarget <= 0) { return completedFuture(emptyList()); } final long maxHeadersToRequest = blocksUntilTarget / (skip + 1); additionalHeaderCount = (int) Math.min(maxHeadersToRequest, maximumHeaderRequestSize); if (additionalHeaderCount == 0) { return completedFuture(singletonList(targetHeader)); } } else { additionalHeaderCount = maximumHeaderRequestSize; } return requestHeaders(peer, previousCheckpointHeader, additionalHeaderCount, skip); }
206414745_1575
public CompletableFuture<List<BlockHeader>> getNextCheckpointHeaders( final EthPeer peer, final BlockHeader previousCheckpointHeader) { final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final int maximumHeaderRequestSize = syncConfig.getDownloaderHeaderRequestSize(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); final int additionalHeaderCount; if (finalCheckpointHeader.isPresent()) { final BlockHeader targetHeader = finalCheckpointHeader.get(); final long blocksUntilTarget = targetHeader.getNumber() - previousCheckpointNumber; if (blocksUntilTarget <= 0) { return completedFuture(emptyList()); } final long maxHeadersToRequest = blocksUntilTarget / (skip + 1); additionalHeaderCount = (int) Math.min(maxHeadersToRequest, maximumHeaderRequestSize); if (additionalHeaderCount == 0) { return completedFuture(singletonList(targetHeader)); } } else { additionalHeaderCount = maximumHeaderRequestSize; } return requestHeaders(peer, previousCheckpointHeader, additionalHeaderCount, skip); }
206414745_1576
public CompletableFuture<List<BlockHeader>> getNextCheckpointHeaders( final EthPeer peer, final BlockHeader previousCheckpointHeader) { final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final int maximumHeaderRequestSize = syncConfig.getDownloaderHeaderRequestSize(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); final int additionalHeaderCount; if (finalCheckpointHeader.isPresent()) { final BlockHeader targetHeader = finalCheckpointHeader.get(); final long blocksUntilTarget = targetHeader.getNumber() - previousCheckpointNumber; if (blocksUntilTarget <= 0) { return completedFuture(emptyList()); } final long maxHeadersToRequest = blocksUntilTarget / (skip + 1); additionalHeaderCount = (int) Math.min(maxHeadersToRequest, maximumHeaderRequestSize); if (additionalHeaderCount == 0) { return completedFuture(singletonList(targetHeader)); } } else { additionalHeaderCount = maximumHeaderRequestSize; } return requestHeaders(peer, previousCheckpointHeader, additionalHeaderCount, skip); }
206414745_1577
public CompletableFuture<List<BlockHeader>> getNextCheckpointHeaders( final EthPeer peer, final BlockHeader previousCheckpointHeader) { final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final int maximumHeaderRequestSize = syncConfig.getDownloaderHeaderRequestSize(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); final int additionalHeaderCount; if (finalCheckpointHeader.isPresent()) { final BlockHeader targetHeader = finalCheckpointHeader.get(); final long blocksUntilTarget = targetHeader.getNumber() - previousCheckpointNumber; if (blocksUntilTarget <= 0) { return completedFuture(emptyList()); } final long maxHeadersToRequest = blocksUntilTarget / (skip + 1); additionalHeaderCount = (int) Math.min(maxHeadersToRequest, maximumHeaderRequestSize); if (additionalHeaderCount == 0) { return completedFuture(singletonList(targetHeader)); } } else { additionalHeaderCount = maximumHeaderRequestSize; } return requestHeaders(peer, previousCheckpointHeader, additionalHeaderCount, skip); }
206414745_1578
public CompletableFuture<List<BlockHeader>> getNextCheckpointHeaders( final EthPeer peer, final BlockHeader previousCheckpointHeader) { final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final int maximumHeaderRequestSize = syncConfig.getDownloaderHeaderRequestSize(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); final int additionalHeaderCount; if (finalCheckpointHeader.isPresent()) { final BlockHeader targetHeader = finalCheckpointHeader.get(); final long blocksUntilTarget = targetHeader.getNumber() - previousCheckpointNumber; if (blocksUntilTarget <= 0) { return completedFuture(emptyList()); } final long maxHeadersToRequest = blocksUntilTarget / (skip + 1); additionalHeaderCount = (int) Math.min(maxHeadersToRequest, maximumHeaderRequestSize); if (additionalHeaderCount == 0) { return completedFuture(singletonList(targetHeader)); } } else { additionalHeaderCount = maximumHeaderRequestSize; } return requestHeaders(peer, previousCheckpointHeader, additionalHeaderCount, skip); }
206414745_1579
public boolean nextCheckpointEndsAtChainHead( final EthPeer peer, final BlockHeader previousCheckpointHeader) { if (finalCheckpointHeader.isPresent()) { return false; } final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final long peerEstimatedHeight = peer.chainState().getEstimatedHeight(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); return previousCheckpointNumber + skip >= peerEstimatedHeight; }
206414745_1580
public boolean nextCheckpointEndsAtChainHead( final EthPeer peer, final BlockHeader previousCheckpointHeader) { if (finalCheckpointHeader.isPresent()) { return false; } final int skip = syncConfig.getDownloaderChainSegmentSize() - 1; final long peerEstimatedHeight = peer.chainState().getEstimatedHeight(); final long previousCheckpointNumber = previousCheckpointHeader.getNumber(); return previousCheckpointNumber + skip >= peerEstimatedHeight; }
206414745_1581
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1582
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1583
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1584
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1585
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1586
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1587
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1588
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1589
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1590
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1591
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1592
@VisibleForTesting CompletableFuture<Block> importOrSavePendingBlock(final Block block) { // Synchronize to avoid race condition where block import event fires after the // blockchain.contains() check and before the block is registered, causing onBlockAdded() to be // invoked for the parent of this block before we are able to register it. synchronized (pendingBlocks) { if (!protocolContext.getBlockchain().contains(block.getHeader().getParentHash())) { // Block isn't connected to local chain, save it to pending blocks collection if (pendingBlocks.registerPendingBlock(block)) { LOG.info( "Saving announced block {} ({}) for future import", block.getHeader().getNumber(), block.getHash()); } return CompletableFuture.completedFuture(block); } } if (!importingBlocks.add(block.getHash())) { // We're already importing this block. return CompletableFuture.completedFuture(block); } if (protocolContext.getBlockchain().contains(block.getHash())) { // We've already imported this block. importingBlocks.remove(block.getHash()); return CompletableFuture.completedFuture(block); } final BlockHeader parent = protocolContext .getBlockchain() .getBlockHeader(block.getHeader().getParentHash()) .orElseThrow( () -> new IllegalArgumentException( "Incapable of retrieving header from non-existent parent of " + block.getHeader().getNumber() + ".")); final ProtocolSpec protocolSpec = protocolSchedule.getByBlockNumber(block.getHeader().getNumber()); final BlockHeaderValidator blockHeaderValidator = protocolSpec.getBlockHeaderValidator(); final BadBlockManager badBlockManager = protocolSpec.getBadBlocksManager(); return ethContext .getScheduler() .scheduleSyncWorkerTask( () -> validateAndProcessPendingBlock( blockHeaderValidator, block, parent, badBlockManager)); }
206414745_1593
public void start() { if (started.compareAndSet(false, true)) { setupListeners(); } else { throw new IllegalStateException( "Attempt to start an already started " + this.getClass().getSimpleName() + "."); } }
206414745_1594
@VisibleForTesting CompletableFuture<Block> importOrSavePendingBlock(final Block block) { // Synchronize to avoid race condition where block import event fires after the // blockchain.contains() check and before the block is registered, causing onBlockAdded() to be // invoked for the parent of this block before we are able to register it. synchronized (pendingBlocks) { if (!protocolContext.getBlockchain().contains(block.getHeader().getParentHash())) { // Block isn't connected to local chain, save it to pending blocks collection if (pendingBlocks.registerPendingBlock(block)) { LOG.info( "Saving announced block {} ({}) for future import", block.getHeader().getNumber(), block.getHash()); } return CompletableFuture.completedFuture(block); } } if (!importingBlocks.add(block.getHash())) { // We're already importing this block. return CompletableFuture.completedFuture(block); } if (protocolContext.getBlockchain().contains(block.getHash())) { // We've already imported this block. importingBlocks.remove(block.getHash()); return CompletableFuture.completedFuture(block); } final BlockHeader parent = protocolContext .getBlockchain() .getBlockHeader(block.getHeader().getParentHash()) .orElseThrow( () -> new IllegalArgumentException( "Incapable of retrieving header from non-existent parent of " + block.getHeader().getNumber() + ".")); final ProtocolSpec protocolSpec = protocolSchedule.getByBlockNumber(block.getHeader().getNumber()); final BlockHeaderValidator blockHeaderValidator = protocolSpec.getBlockHeaderValidator(); final BadBlockManager badBlockManager = protocolSpec.getBadBlocksManager(); return ethContext .getScheduler() .scheduleSyncWorkerTask( () -> validateAndProcessPendingBlock( blockHeaderValidator, block, parent, badBlockManager)); }
206414745_1595
@Override public boolean hasNext() { return !retrievedRanges.isEmpty() || (requestFailureCount < checkpointTimeoutsPermitted && syncTargetChecker.shouldContinueDownloadingFromSyncTarget(peer, lastRangeEnd) && !reachedEndOfCheckpoints); }
206414745_1596
@Override public Stream<BlockHeader> apply(final CheckpointRangeHeaders checkpointRangeHeaders) { final BlockHeader rangeStart = checkpointRangeHeaders.getCheckpointRange().getStart(); final BlockHeader firstHeaderToImport = checkpointRangeHeaders.getFirstHeaderToImport(); if (isValid(rangeStart, firstHeaderToImport)) { return checkpointRangeHeaders.getHeadersToImport().stream(); } else { final String rangeEndDescription; if (checkpointRangeHeaders.getCheckpointRange().hasEnd()) { final BlockHeader rangeEnd = checkpointRangeHeaders.getCheckpointRange().getEnd(); rangeEndDescription = String.format("#%d (%s)", rangeEnd.getNumber(), rangeEnd.getBlockHash()); } else { rangeEndDescription = "chain head"; } final String errorMessage = String.format( "Invalid checkpoint 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()); } }
206414745_1597
@Override public Stream<BlockHeader> apply(final CheckpointRangeHeaders checkpointRangeHeaders) { final BlockHeader rangeStart = checkpointRangeHeaders.getCheckpointRange().getStart(); final BlockHeader firstHeaderToImport = checkpointRangeHeaders.getFirstHeaderToImport(); if (isValid(rangeStart, firstHeaderToImport)) { return checkpointRangeHeaders.getHeadersToImport().stream(); } else { final String rangeEndDescription; if (checkpointRangeHeaders.getCheckpointRange().hasEnd()) { final BlockHeader rangeEnd = checkpointRangeHeaders.getCheckpointRange().getEnd(); rangeEndDescription = String.format("#%d (%s)", rangeEnd.getNumber(), rangeEnd.getBlockHash()); } else { rangeEndDescription = "chain head"; } final String errorMessage = String.format( "Invalid checkpoint 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()); } }
206414745_1598
public void enforceTrailingPeerLimit() { final TrailingPeerRequirements requirements = trailingPeerRequirementsCalculator.get(); if (requirements.getMaxTrailingPeers() == Long.MAX_VALUE) { return; } final long minimumHeightToBeUpToDate = requirements.getMinimumHeightToBeUpToDate(); final long maxTrailingPeers = requirements.getMaxTrailingPeers(); final List<EthPeer> trailingPeers = ethPeers .streamAvailablePeers() .filter(peer -> peer.chainState().hasEstimatedHeight()) .filter(peer -> peer.chainState().getEstimatedHeight() < minimumHeightToBeUpToDate) .sorted(BY_CHAIN_HEIGHT) .collect(Collectors.toList()); while (!trailingPeers.isEmpty() && trailingPeers.size() > maxTrailingPeers) { final EthPeer peerToDisconnect = trailingPeers.remove(0); LOG.debug("Enforcing trailing peers limit by disconnecting {}", peerToDisconnect); peerToDisconnect.disconnect(DisconnectReason.TOO_MANY_PEERS); } }
206414745_1599
public void enforceTrailingPeerLimit() { final TrailingPeerRequirements requirements = trailingPeerRequirementsCalculator.get(); if (requirements.getMaxTrailingPeers() == Long.MAX_VALUE) { return; } final long minimumHeightToBeUpToDate = requirements.getMinimumHeightToBeUpToDate(); final long maxTrailingPeers = requirements.getMaxTrailingPeers(); final List<EthPeer> trailingPeers = ethPeers .streamAvailablePeers() .filter(peer -> peer.chainState().hasEstimatedHeight()) .filter(peer -> peer.chainState().getEstimatedHeight() < minimumHeightToBeUpToDate) .sorted(BY_CHAIN_HEIGHT) .collect(Collectors.toList()); while (!trailingPeers.isEmpty() && trailingPeers.size() > maxTrailingPeers) { final EthPeer peerToDisconnect = trailingPeers.remove(0); LOG.debug("Enforcing trailing peers limit by disconnecting {}", peerToDisconnect); peerToDisconnect.disconnect(DisconnectReason.TOO_MANY_PEERS); } }
206414745_1600
public void enforceTrailingPeerLimit() { final TrailingPeerRequirements requirements = trailingPeerRequirementsCalculator.get(); if (requirements.getMaxTrailingPeers() == Long.MAX_VALUE) { return; } final long minimumHeightToBeUpToDate = requirements.getMinimumHeightToBeUpToDate(); final long maxTrailingPeers = requirements.getMaxTrailingPeers(); final List<EthPeer> trailingPeers = ethPeers .streamAvailablePeers() .filter(peer -> peer.chainState().hasEstimatedHeight()) .filter(peer -> peer.chainState().getEstimatedHeight() < minimumHeightToBeUpToDate) .sorted(BY_CHAIN_HEIGHT) .collect(Collectors.toList()); while (!trailingPeers.isEmpty() && trailingPeers.size() > maxTrailingPeers) { final EthPeer peerToDisconnect = trailingPeers.remove(0); LOG.debug("Enforcing trailing peers limit by disconnecting {}", peerToDisconnect); peerToDisconnect.disconnect(DisconnectReason.TOO_MANY_PEERS); } }
206414745_1601
public void enforceTrailingPeerLimit() { final TrailingPeerRequirements requirements = trailingPeerRequirementsCalculator.get(); if (requirements.getMaxTrailingPeers() == Long.MAX_VALUE) { return; } final long minimumHeightToBeUpToDate = requirements.getMinimumHeightToBeUpToDate(); final long maxTrailingPeers = requirements.getMaxTrailingPeers(); final List<EthPeer> trailingPeers = ethPeers .streamAvailablePeers() .filter(peer -> peer.chainState().hasEstimatedHeight()) .filter(peer -> peer.chainState().getEstimatedHeight() < minimumHeightToBeUpToDate) .sorted(BY_CHAIN_HEIGHT) .collect(Collectors.toList()); while (!trailingPeers.isEmpty() && trailingPeers.size() > maxTrailingPeers) { final EthPeer peerToDisconnect = trailingPeers.remove(0); LOG.debug("Enforcing trailing peers limit by disconnecting {}", peerToDisconnect); peerToDisconnect.disconnect(DisconnectReason.TOO_MANY_PEERS); } }
206414745_1602
@Override public void onBlockAdded(final BlockAddedEvent event) { if (event.isNewCanonicalHead() && event.getBlock().getHeader().getNumber() % RECHECK_PEERS_WHEN_BLOCK_NUMBER_MULTIPLE_OF == 0) { enforceTrailingPeerLimit(); } }
206414745_1603
@Override public void onBlockAdded(final BlockAddedEvent event) { if (event.isNewCanonicalHead() && event.getBlock().getHeader().getNumber() % RECHECK_PEERS_WHEN_BLOCK_NUMBER_MULTIPLE_OF == 0) { enforceTrailingPeerLimit(); } }
206414745_1604
public Optional<WorldStateProof> getAccountProof( final Hash worldStateRoot, final Address accountAddress, final List<UInt256> accountStorageKeys) { if (!worldStateStorage.isWorldStateAvailable(worldStateRoot)) { return Optional.empty(); } else { final Hash addressHash = Hash.hash(accountAddress); final Proof<Bytes> accountProof = newAccountStateTrie(worldStateRoot).getValueWithProof(addressHash); return accountProof .getValue() .map(RLP::input) .map(StateTrieAccountValue::readFrom) .map( account -> { final SortedMap<UInt256, Proof<Bytes>> storageProofs = getStorageProofs(account, accountStorageKeys); return new WorldStateProof(account, accountProof, storageProofs); }); } }
206414745_1605
public Optional<WorldStateProof> getAccountProof( final Hash worldStateRoot, final Address accountAddress, final List<UInt256> accountStorageKeys) { if (!worldStateStorage.isWorldStateAvailable(worldStateRoot)) { return Optional.empty(); } else { final Hash addressHash = Hash.hash(accountAddress); final Proof<Bytes> accountProof = newAccountStateTrie(worldStateRoot).getValueWithProof(addressHash); return accountProof .getValue() .map(RLP::input) .map(StateTrieAccountValue::readFrom) .map( account -> { final SortedMap<UInt256, Proof<Bytes>> storageProofs = getStorageProofs(account, accountStorageKeys); return new WorldStateProof(account, accountProof, storageProofs); }); } }
206414745_1606
public Optional<WorldStateProof> getAccountProof( final Hash worldStateRoot, final Address accountAddress, final List<UInt256> accountStorageKeys) { if (!worldStateStorage.isWorldStateAvailable(worldStateRoot)) { return Optional.empty(); } else { final Hash addressHash = Hash.hash(accountAddress); final Proof<Bytes> accountProof = newAccountStateTrie(worldStateRoot).getValueWithProof(addressHash); return accountProof .getValue() .map(RLP::input) .map(StateTrieAccountValue::readFrom) .map( account -> { final SortedMap<UInt256, Proof<Bytes>> storageProofs = getStorageProofs(account, accountStorageKeys); return new WorldStateProof(account, accountProof, storageProofs); }); } }
206414745_1607
@Override public synchronized boolean importBlock( final ProtocolContext context, final Block block, final HeaderValidationMode headerValidationMode, final HeaderValidationMode ommerValidationMode) { if (context.getBlockchain().contains(block.getHash())) { return true; } final Optional<BlockValidator.BlockProcessingOutputs> outputs = blockValidator.validateAndProcessBlock( context, block, headerValidationMode, ommerValidationMode); outputs.ifPresent( processingOutputs -> context.getBlockchain().appendBlock(block, processingOutputs.receipts)); return outputs.isPresent(); }
206414745_1608
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1609
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1610
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1611
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1612
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1613
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1614
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1615
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1616
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1617
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1618
public boolean validateHeader( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext, final HeaderValidationMode mode) { switch (mode) { case NONE: return true; case LIGHT_DETACHED_ONLY: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && rule.isDetachedSupported()); case LIGHT_SKIP_DETACHED: return applyRules( header, parent, protocolContext, rule -> rule.includeInLightValidation() && !rule.isDetachedSupported()); case LIGHT: return applyRules(header, parent, protocolContext, Rule::includeInLightValidation); case DETACHED_ONLY: return applyRules(header, parent, protocolContext, Rule::isDetachedSupported); case SKIP_DETACHED: return applyRules(header, parent, protocolContext, rule -> !rule.isDetachedSupported()); case FULL: return applyRules(header, parent, protocolContext, rule -> true); } throw new IllegalArgumentException("Unknown HeaderValidationMode: " + mode); }
206414745_1619
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (header.getGasUsed() > header.getGasLimit()) { LOG.trace( "Invalid block header: gas used {} exceeds gas limit {}", header.getGasUsed(), header.getGasLimit()); return false; } return true; }
206414745_1620
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { return validateExtraData(header.getExtraData()); }
206414745_1621
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { return validateExtraData(header.getExtraData()); }
206414745_1622
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (!header.getParentHash().equals(parent.getHash())) { LOG.trace( "Invalid parent block header. Parent hash {} does not match " + "supplied parent header {}.", header.getParentHash(), parent.getHash()); return false; } if (header.getNumber() != (parent.getNumber() + 1)) { LOG.trace( "Invalid block header: number {} is not one more than parent number {}", header.getNumber(), parent.getNumber()); return false; } return true; }
206414745_1623
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (!header.getParentHash().equals(parent.getHash())) { LOG.trace( "Invalid parent block header. Parent hash {} does not match " + "supplied parent header {}.", header.getParentHash(), parent.getHash()); return false; } if (header.getNumber() != (parent.getNumber() + 1)) { LOG.trace( "Invalid block header: number {} is not one more than parent number {}", header.getNumber(), parent.getNumber()); return false; } return true; }
206414745_1624
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (!header.getParentHash().equals(parent.getHash())) { LOG.trace( "Invalid parent block header. Parent hash {} does not match " + "supplied parent header {}.", header.getParentHash(), parent.getHash()); return false; } if (header.getNumber() != (parent.getNumber() + 1)) { LOG.trace( "Invalid block header: number {} is not one more than parent number {}", header.getNumber(), parent.getNumber()); return false; } return true; }
206414745_1625
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { final long gasLimit = header.getGasLimit(); if ((gasLimit < minGasLimit) || (gasLimit > maxGasLimit)) { LOG.trace( "Header gasLimit = {}, outside range {} --> {}", gasLimit, minGasLimit, maxGasLimit); return false; } final long parentGasLimit = parent.getGasLimit(); final long difference = Math.abs(parentGasLimit - gasLimit); final long bounds = Long.divideUnsigned(parentGasLimit, GASLIMIT_BOUND_DIVISOR); if (Long.compareUnsigned(difference, bounds) >= 0) { LOG.trace( "Invalid block header: gas limit delta {} is out of bounds of {}", gasLimit, bounds); return false; } return true; }
206414745_1626
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { try { if (!eip1559.isEIP1559(header.getNumber())) { return true; } if (eip1559.isForkBlock(header.getNumber())) { return feeMarket.getInitialBasefee() == header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); } final Long parentBaseFee = parent.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final Long currentBaseFee = header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final long targetGasUsed = eip1559.targetGasUsed(parent); final long baseFee = eip1559.computeBaseFee(parentBaseFee, parent.getGasUsed(), targetGasUsed); if (baseFee != header.getBaseFee().orElseThrow()) { LOG.trace( "Invalid block header: basefee {} does not equal expected basefee {}", header.getBaseFee().orElseThrow(), baseFee); return false; } return baseFee == currentBaseFee && eip1559.isValidBaseFee(parentBaseFee, currentBaseFee); } catch (final EIP1559MissingBaseFeeFromBlockHeader e) { LOG.trace(e.getMessage()); return false; } }
206414745_1627
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { try { if (!eip1559.isEIP1559(header.getNumber())) { return true; } if (eip1559.isForkBlock(header.getNumber())) { return feeMarket.getInitialBasefee() == header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); } final Long parentBaseFee = parent.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final Long currentBaseFee = header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final long targetGasUsed = eip1559.targetGasUsed(parent); final long baseFee = eip1559.computeBaseFee(parentBaseFee, parent.getGasUsed(), targetGasUsed); if (baseFee != header.getBaseFee().orElseThrow()) { LOG.trace( "Invalid block header: basefee {} does not equal expected basefee {}", header.getBaseFee().orElseThrow(), baseFee); return false; } return baseFee == currentBaseFee && eip1559.isValidBaseFee(parentBaseFee, currentBaseFee); } catch (final EIP1559MissingBaseFeeFromBlockHeader e) { LOG.trace(e.getMessage()); return false; } }
206414745_1628
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { try { if (!eip1559.isEIP1559(header.getNumber())) { return true; } if (eip1559.isForkBlock(header.getNumber())) { return feeMarket.getInitialBasefee() == header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); } final Long parentBaseFee = parent.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final Long currentBaseFee = header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final long targetGasUsed = eip1559.targetGasUsed(parent); final long baseFee = eip1559.computeBaseFee(parentBaseFee, parent.getGasUsed(), targetGasUsed); if (baseFee != header.getBaseFee().orElseThrow()) { LOG.trace( "Invalid block header: basefee {} does not equal expected basefee {}", header.getBaseFee().orElseThrow(), baseFee); return false; } return baseFee == currentBaseFee && eip1559.isValidBaseFee(parentBaseFee, currentBaseFee); } catch (final EIP1559MissingBaseFeeFromBlockHeader e) { LOG.trace(e.getMessage()); return false; } }
206414745_1629
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { try { if (!eip1559.isEIP1559(header.getNumber())) { return true; } if (eip1559.isForkBlock(header.getNumber())) { return feeMarket.getInitialBasefee() == header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); } final Long parentBaseFee = parent.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final Long currentBaseFee = header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final long targetGasUsed = eip1559.targetGasUsed(parent); final long baseFee = eip1559.computeBaseFee(parentBaseFee, parent.getGasUsed(), targetGasUsed); if (baseFee != header.getBaseFee().orElseThrow()) { LOG.trace( "Invalid block header: basefee {} does not equal expected basefee {}", header.getBaseFee().orElseThrow(), baseFee); return false; } return baseFee == currentBaseFee && eip1559.isValidBaseFee(parentBaseFee, currentBaseFee); } catch (final EIP1559MissingBaseFeeFromBlockHeader e) { LOG.trace(e.getMessage()); return false; } }
206414745_1630
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { try { if (!eip1559.isEIP1559(header.getNumber())) { return true; } if (eip1559.isForkBlock(header.getNumber())) { return feeMarket.getInitialBasefee() == header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); } final Long parentBaseFee = parent.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final Long currentBaseFee = header.getBaseFee().orElseThrow(EIP1559MissingBaseFeeFromBlockHeader::new); final long targetGasUsed = eip1559.targetGasUsed(parent); final long baseFee = eip1559.computeBaseFee(parentBaseFee, parent.getGasUsed(), targetGasUsed); if (baseFee != header.getBaseFee().orElseThrow()) { LOG.trace( "Invalid block header: basefee {} does not equal expected basefee {}", header.getBaseFee().orElseThrow(), baseFee); return false; } return baseFee == currentBaseFee && eip1559.isValidBaseFee(parentBaseFee, currentBaseFee); } catch (final EIP1559MissingBaseFeeFromBlockHeader e) { LOG.trace(e.getMessage()); return false; } }
206414745_1631
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (includeBaseFee) { if (!ExperimentalEIPs.eip1559Enabled) { LOG.warn("Invalid block header: EIP-1559 feature flag must be enabled --Xeip1559-enabled"); return false; } else if (header.getBaseFee().isEmpty()) { LOG.warn("Invalid block header: missing mandatory base fee."); return false; } } final byte[] hashBuffer = new byte[64]; final Hash headerHash = hashHeader(header); HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.toArray()); if (header.getDifficulty().isZero()) { LOG.trace("Rejecting header because difficulty is 0"); return false; } final BigInteger difficulty = header.getDifficulty().toBytes().toUnsignedBigInteger(); final UInt256 target = difficulty.equals(BigInteger.ONE) ? UInt256.MAX_VALUE : UInt256.valueOf(ETHASH_TARGET_UPPER_BOUND.divide(difficulty)); final UInt256 result = UInt256.fromBytes(Bytes32.wrap(hashBuffer, 32)); if (result.compareTo(target) > 0) { LOG.warn( "Invalid block header: the EthHash result {} was greater than the target {}.\n" + "Failing header:\n{}", result, target, header); return false; } final Hash mixedHash = Hash.wrap(Bytes32.leftPad(Bytes.wrap(hashBuffer).slice(0, Bytes32.SIZE))); if (!header.getMixHash().equals(mixedHash)) { LOG.warn( "Invalid block header: header mixed hash {} does not equal calculated mixed hash {}.\n" + "Failing header:\n{}", header.getMixHash(), mixedHash, header); return false; } return true; }
206414745_1632
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (includeBaseFee) { if (!ExperimentalEIPs.eip1559Enabled) { LOG.warn("Invalid block header: EIP-1559 feature flag must be enabled --Xeip1559-enabled"); return false; } else if (header.getBaseFee().isEmpty()) { LOG.warn("Invalid block header: missing mandatory base fee."); return false; } } final byte[] hashBuffer = new byte[64]; final Hash headerHash = hashHeader(header); HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.toArray()); if (header.getDifficulty().isZero()) { LOG.trace("Rejecting header because difficulty is 0"); return false; } final BigInteger difficulty = header.getDifficulty().toBytes().toUnsignedBigInteger(); final UInt256 target = difficulty.equals(BigInteger.ONE) ? UInt256.MAX_VALUE : UInt256.valueOf(ETHASH_TARGET_UPPER_BOUND.divide(difficulty)); final UInt256 result = UInt256.fromBytes(Bytes32.wrap(hashBuffer, 32)); if (result.compareTo(target) > 0) { LOG.warn( "Invalid block header: the EthHash result {} was greater than the target {}.\n" + "Failing header:\n{}", result, target, header); return false; } final Hash mixedHash = Hash.wrap(Bytes32.leftPad(Bytes.wrap(hashBuffer).slice(0, Bytes32.SIZE))); if (!header.getMixHash().equals(mixedHash)) { LOG.warn( "Invalid block header: header mixed hash {} does not equal calculated mixed hash {}.\n" + "Failing header:\n{}", header.getMixHash(), mixedHash, header); return false; } return true; }
206414745_1633
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (includeBaseFee) { if (!ExperimentalEIPs.eip1559Enabled) { LOG.warn("Invalid block header: EIP-1559 feature flag must be enabled --Xeip1559-enabled"); return false; } else if (header.getBaseFee().isEmpty()) { LOG.warn("Invalid block header: missing mandatory base fee."); return false; } } final byte[] hashBuffer = new byte[64]; final Hash headerHash = hashHeader(header); HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.toArray()); if (header.getDifficulty().isZero()) { LOG.trace("Rejecting header because difficulty is 0"); return false; } final BigInteger difficulty = header.getDifficulty().toBytes().toUnsignedBigInteger(); final UInt256 target = difficulty.equals(BigInteger.ONE) ? UInt256.MAX_VALUE : UInt256.valueOf(ETHASH_TARGET_UPPER_BOUND.divide(difficulty)); final UInt256 result = UInt256.fromBytes(Bytes32.wrap(hashBuffer, 32)); if (result.compareTo(target) > 0) { LOG.warn( "Invalid block header: the EthHash result {} was greater than the target {}.\n" + "Failing header:\n{}", result, target, header); return false; } final Hash mixedHash = Hash.wrap(Bytes32.leftPad(Bytes.wrap(hashBuffer).slice(0, Bytes32.SIZE))); if (!header.getMixHash().equals(mixedHash)) { LOG.warn( "Invalid block header: header mixed hash {} does not equal calculated mixed hash {}.\n" + "Failing header:\n{}", header.getMixHash(), mixedHash, header); return false; } return true; }
206414745_1634
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (includeBaseFee) { if (!ExperimentalEIPs.eip1559Enabled) { LOG.warn("Invalid block header: EIP-1559 feature flag must be enabled --Xeip1559-enabled"); return false; } else if (header.getBaseFee().isEmpty()) { LOG.warn("Invalid block header: missing mandatory base fee."); return false; } } final byte[] hashBuffer = new byte[64]; final Hash headerHash = hashHeader(header); HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.toArray()); if (header.getDifficulty().isZero()) { LOG.trace("Rejecting header because difficulty is 0"); return false; } final BigInteger difficulty = header.getDifficulty().toBytes().toUnsignedBigInteger(); final UInt256 target = difficulty.equals(BigInteger.ONE) ? UInt256.MAX_VALUE : UInt256.valueOf(ETHASH_TARGET_UPPER_BOUND.divide(difficulty)); final UInt256 result = UInt256.fromBytes(Bytes32.wrap(hashBuffer, 32)); if (result.compareTo(target) > 0) { LOG.warn( "Invalid block header: the EthHash result {} was greater than the target {}.\n" + "Failing header:\n{}", result, target, header); return false; } final Hash mixedHash = Hash.wrap(Bytes32.leftPad(Bytes.wrap(hashBuffer).slice(0, Bytes32.SIZE))); if (!header.getMixHash().equals(mixedHash)) { LOG.warn( "Invalid block header: header mixed hash {} does not equal calculated mixed hash {}.\n" + "Failing header:\n{}", header.getMixHash(), mixedHash, header); return false; } return true; }
206414745_1635
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { if (includeBaseFee) { if (!ExperimentalEIPs.eip1559Enabled) { LOG.warn("Invalid block header: EIP-1559 feature flag must be enabled --Xeip1559-enabled"); return false; } else if (header.getBaseFee().isEmpty()) { LOG.warn("Invalid block header: missing mandatory base fee."); return false; } } final byte[] hashBuffer = new byte[64]; final Hash headerHash = hashHeader(header); HASHER.hash(hashBuffer, header.getNonce(), header.getNumber(), headerHash.toArray()); if (header.getDifficulty().isZero()) { LOG.trace("Rejecting header because difficulty is 0"); return false; } final BigInteger difficulty = header.getDifficulty().toBytes().toUnsignedBigInteger(); final UInt256 target = difficulty.equals(BigInteger.ONE) ? UInt256.MAX_VALUE : UInt256.valueOf(ETHASH_TARGET_UPPER_BOUND.divide(difficulty)); final UInt256 result = UInt256.fromBytes(Bytes32.wrap(hashBuffer, 32)); if (result.compareTo(target) > 0) { LOG.warn( "Invalid block header: the EthHash result {} was greater than the target {}.\n" + "Failing header:\n{}", result, target, header); return false; } final Hash mixedHash = Hash.wrap(Bytes32.leftPad(Bytes.wrap(hashBuffer).slice(0, Bytes32.SIZE))); if (!header.getMixHash().equals(mixedHash)) { LOG.warn( "Invalid block header: header mixed hash {} does not equal calculated mixed hash {}.\n" + "Failing header:\n{}", header.getMixHash(), mixedHash, header); return false; } return true; }
206414745_1636
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { final T actualValue = accessor.apply(header); if (!actualValue.equals(expectedValue)) { LOG.trace( "{} failed validation. Actual != Expected ({} != {}).", fieldName, actualValue, expectedValue); return false; } return true; }
206414745_1637
@Override public boolean validate(final BlockHeader header, final BlockHeader parent) { final T actualValue = accessor.apply(header); if (!actualValue.equals(expectedValue)) { LOG.trace( "{} failed validation. Actual != Expected ({} != {}).", fieldName, actualValue, expectedValue); return false; } return true; }
206414745_1638
public boolean isAllowFutureNonce() { return allowFutureNonce; }
206414745_1639
public boolean checkOnchainPermissions() { return checkOnchainPermissions; }
206414745_1640
public boolean checkLocalPermissions() { return checkLocalPermissions; }
206414745_1641
public static TransactionValidationParams transactionSimulator() { return transactionSimulatorParams; }