Search in sources :

Example 96 with Block

use of org.hyperledger.besu.ethereum.core.Block in project besu by hyperledger.

the class BlockBroadcaster method propagate.

public void propagate(final Block block, final Difficulty totalDifficulty) {
    blockPropagatedSubscribers.forEach(listener -> listener.accept(block, totalDifficulty));
    final NewBlockMessage newBlockMessage = NewBlockMessage.create(block, totalDifficulty);
    ethContext.getEthPeers().streamAvailablePeers().filter(ethPeer -> !ethPeer.hasSeenBlock(block.getHash())).forEach(ethPeer -> {
        ethPeer.registerKnownBlock(block.getHash());
        try {
            ethPeer.send(newBlockMessage);
        } catch (final PeerConnection.PeerNotConnected e) {
            LOG.trace("Failed to broadcast new block to peer", e);
        }
    });
}
Also used : Difficulty(org.hyperledger.besu.ethereum.core.Difficulty) Logger(org.slf4j.Logger) PeerConnection(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection) NewBlockMessage(org.hyperledger.besu.ethereum.eth.messages.NewBlockMessage) LoggerFactory(org.slf4j.LoggerFactory) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) Block(org.hyperledger.besu.ethereum.core.Block) Subscribers(org.hyperledger.besu.util.Subscribers) NewBlockMessage(org.hyperledger.besu.ethereum.eth.messages.NewBlockMessage) PeerConnection(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection)

Example 97 with Block

use of org.hyperledger.besu.ethereum.core.Block in project besu by hyperledger.

the class BlockPropagationManager method onBlockAdded.

private void onBlockAdded(final BlockAddedEvent blockAddedEvent) {
    // Check to see if any of our pending blocks are now ready for import
    final Block newBlock = blockAddedEvent.getBlock();
    final List<Block> readyForImport;
    synchronized (pendingBlocksManager) {
        // Remove block from pendingBlocks list
        pendingBlocksManager.deregisterPendingBlock(newBlock);
        // Import any pending blocks that are children of the newly added block
        readyForImport = pendingBlocksManager.childrenOf(newBlock.getHash());
    }
    traceLambda(LOG, "Block added event type {} for block {}. Current status {}", blockAddedEvent::getEventType, newBlock::toLogString, () -> this);
    if (!readyForImport.isEmpty()) {
        traceLambda(LOG, "Ready to import pending blocks found [{}] for block {}", () -> readyForImport.stream().map(Block::toLogString).collect(Collectors.joining(", ")), newBlock::toLogString);
        final Supplier<CompletableFuture<List<Block>>> importBlocksTask = PersistBlockTask.forUnorderedBlocks(protocolSchedule, protocolContext, ethContext, readyForImport, HeaderValidationMode.FULL, metricsSystem);
        ethContext.getScheduler().scheduleSyncWorkerTask(importBlocksTask).whenComplete((r, t) -> {
            if (r != null) {
                LOG.info("Imported {} pending blocks", r.size());
            }
            if (t != null) {
                LOG.error("Error importing pending blocks", t);
            }
        });
    } else {
        traceLambda(LOG, "There are no pending blocks ready to import for block {}", newBlock::toLogString);
        maybeProcessNonAnnouncedBlocks(newBlock);
    }
    if (blockAddedEvent.getEventType().equals(EventType.HEAD_ADVANCED)) {
        final long head = protocolContext.getBlockchain().getChainHeadBlockNumber();
        final long cutoff = head + config.getBlockPropagationRange().lowerEndpoint();
        pendingBlocksManager.purgeBlocksOlderThan(cutoff);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Block(org.hyperledger.besu.ethereum.core.Block)

Example 98 with Block

use of org.hyperledger.besu.ethereum.core.Block in project besu by hyperledger.

the class BlockPropagationManager method getBlockFromPeers.

private CompletableFuture<Block> getBlockFromPeers(final Optional<EthPeer> preferredPeer, final long blockNumber, final Optional<Hash> blockHash) {
    final RetryingGetBlockFromPeersTask getBlockTask = RetryingGetBlockFromPeersTask.create(protocolContext, protocolSchedule, ethContext, metricsSystem, ethContext.getEthPeers().getMaxPeers(), blockHash, blockNumber);
    preferredPeer.ifPresent(getBlockTask::assignPeer);
    return ethContext.getScheduler().scheduleSyncWorkerTask(getBlockTask::run).thenCompose(r -> importOrSavePendingBlock(r.getResult(), r.getPeer().nodeId())).whenComplete((r, t) -> {
        requestedNonAnnouncedBlocks.remove(blockNumber);
        blockHash.ifPresentOrElse(requestedBlocks::remove, () -> {
            if (r != null) {
                // in case we successfully retrieved only by block number, when can remove
                // the request by hash too
                requestedBlocks.remove(r.getHash());
            }
        });
    });
}
Also used : RLPException(org.hyperledger.besu.ethereum.rlp.RLPException) EthPV62(org.hyperledger.besu.ethereum.eth.messages.EthPV62) SyncState(org.hyperledger.besu.ethereum.eth.sync.state.SyncState) EthPeer(org.hyperledger.besu.ethereum.eth.manager.EthPeer) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RetryingGetBlockFromPeersTask(org.hyperledger.besu.ethereum.eth.manager.task.RetryingGetBlockFromPeersTask) CompletableFuture(java.util.concurrent.CompletableFuture) Bytes(org.apache.tuweni.bytes.Bytes) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PendingBlocksManager(org.hyperledger.besu.ethereum.eth.sync.state.PendingBlocksManager) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) Lists(com.google.common.collect.Lists) BlockHeaderValidator(org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator) BlockAddedEvent(org.hyperledger.besu.ethereum.chain.BlockAddedEvent) Block(org.hyperledger.besu.ethereum.core.Block) EventType(org.hyperledger.besu.ethereum.chain.BlockAddedEvent.EventType) EthMessage(org.hyperledger.besu.ethereum.eth.manager.EthMessage) Slf4jLambdaHelper.traceLambda(org.hyperledger.besu.util.Slf4jLambdaHelper.traceLambda) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) DisconnectReason(org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason) PersistBlockTask(org.hyperledger.besu.ethereum.eth.sync.tasks.PersistBlockTask) NewBlockHash(org.hyperledger.besu.ethereum.eth.messages.NewBlockHashesMessage.NewBlockHash) Difficulty(org.hyperledger.besu.ethereum.core.Difficulty) Logger(org.slf4j.Logger) BadBlockManager(org.hyperledger.besu.ethereum.chain.BadBlockManager) NewBlockHashesMessage(org.hyperledger.besu.ethereum.eth.messages.NewBlockHashesMessage) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) Collection(java.util.Collection) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) NewBlockMessage(org.hyperledger.besu.ethereum.eth.messages.NewBlockMessage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Range(com.google.common.collect.Range) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) Optional(java.util.Optional) HeaderValidationMode(org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode) MetricsSystem(org.hyperledger.besu.plugin.services.MetricsSystem) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ProtocolSpec(org.hyperledger.besu.ethereum.mainnet.ProtocolSpec) Collections(java.util.Collections) Hash(org.hyperledger.besu.datatypes.Hash) RetryingGetBlockFromPeersTask(org.hyperledger.besu.ethereum.eth.manager.task.RetryingGetBlockFromPeersTask)

Example 99 with Block

use of org.hyperledger.besu.ethereum.core.Block in project besu by hyperledger.

the class ForwardSyncStep method saveBlocks.

@VisibleForTesting
protected Void saveBlocks(final List<Block> blocks) {
    if (blocks.isEmpty()) {
        LOG.info("No blocks to save...");
        context.halveBatchSize();
        return null;
    }
    for (Block block : blocks) {
        final Optional<Block> parent = context.getProtocolContext().getBlockchain().getBlockByHash(block.getHeader().getParentHash());
        if (parent.isEmpty()) {
            context.halveBatchSize();
            return null;
        } else {
            saveBlock(block);
        }
    }
    infoLambda(LOG, "Saved blocks {} -> {} (target: {})", () -> blocks.get(0).getHeader().getNumber(), () -> blocks.get(blocks.size() - 1).getHeader().getNumber(), () -> backwardChain.getPivot().orElse(blocks.get(blocks.size() - 1)).getHeader().getNumber());
    context.resetBatchSize();
    return null;
}
Also used : Block(org.hyperledger.besu.ethereum.core.Block) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 100 with Block

use of org.hyperledger.besu.ethereum.core.Block in project besu by hyperledger.

the class TransactionPoolTest method shouldReadTransactionsFromThePreviousCanonicalHeadWhenAReorgOccurs.

@Test
public void shouldReadTransactionsFromThePreviousCanonicalHeadWhenAReorgOccurs() {
    givenTransactionIsValid(transaction1);
    givenTransactionIsValid(transaction2);
    transactions.addRemoteTransaction(transaction1);
    transactions.addRemoteTransaction(transaction2);
    final BlockHeader commonParent = getHeaderForCurrentChainHead();
    final Block originalFork1 = appendBlock(Difficulty.of(1000), commonParent, transaction1);
    final Block originalFork2 = appendBlock(Difficulty.ONE, originalFork1.getHeader(), transaction2);
    assertTransactionNotPending(transaction1);
    assertTransactionNotPending(transaction2);
    final Block reorgFork1 = appendBlock(Difficulty.ONE, commonParent);
    verifyChainHeadIs(originalFork2);
    transactions.subscribePendingTransactions(listener);
    final Block reorgFork2 = appendBlock(Difficulty.of(2000), reorgFork1.getHeader());
    verifyChainHeadIs(reorgFork2);
    assertTransactionPending(transaction1);
    assertTransactionPending(transaction2);
    verify(listener).onTransactionAdded(transaction1);
    verify(listener).onTransactionAdded(transaction2);
    verifyNoMoreInteractions(listener);
}
Also used : Block(org.hyperledger.besu.ethereum.core.Block) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) Test(org.junit.Test)

Aggregations

Block (org.hyperledger.besu.ethereum.core.Block)425 Test (org.junit.Test)236 BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)118 BlockDataGenerator (org.hyperledger.besu.ethereum.core.BlockDataGenerator)91 List (java.util.List)57 Hash (org.hyperledger.besu.datatypes.Hash)54 TransactionReceipt (org.hyperledger.besu.ethereum.core.TransactionReceipt)52 BlockBody (org.hyperledger.besu.ethereum.core.BlockBody)47 ProtocolContext (org.hyperledger.besu.ethereum.ProtocolContext)40 ArrayList (java.util.ArrayList)37 Test (org.junit.jupiter.api.Test)37 ConsensusRoundIdentifier (org.hyperledger.besu.consensus.common.bft.ConsensusRoundIdentifier)36 Transaction (org.hyperledger.besu.ethereum.core.Transaction)34 RespondingEthPeer (org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer)34 Optional (java.util.Optional)33 Bytes (org.apache.tuweni.bytes.Bytes)33 MutableBlockchain (org.hyperledger.besu.ethereum.chain.MutableBlockchain)31 ProtocolSchedule (org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule)31 Address (org.hyperledger.besu.datatypes.Address)28 Difficulty (org.hyperledger.besu.ethereum.core.Difficulty)28