Search in sources :

Example 1 with EthContext

use of org.hyperledger.besu.ethereum.eth.manager.EthContext in project besu by hyperledger.

the class PendingTransactionsSenderTest method testSendEth65PeersOnly.

@Test
public void testSendEth65PeersOnly() {
    PeerPendingTransactionTracker peerPendingTransactionTracker = mock(PeerPendingTransactionTracker.class);
    PendingTransactionsMessageSender pendingTransactionsMessageSender = mock(PendingTransactionsMessageSender.class);
    EthContext ethContext = mock(EthContext.class);
    EthScheduler ethScheduler = mock(EthScheduler.class);
    when(ethContext.getScheduler()).thenReturn(ethScheduler);
    PendingTransactionSender sender = new PendingTransactionSender(peerPendingTransactionTracker, pendingTransactionsMessageSender, ethContext);
    EthPeer peer1 = mock(EthPeer.class);
    EthPeer peer2 = mock(EthPeer.class);
    Transaction tx = mock(Transaction.class);
    Hash hash = Hash.wrap(Bytes32.random());
    when(tx.getHash()).thenReturn(hash);
    EthPeers ethPeers = mock(EthPeers.class);
    when(ethContext.getEthPeers()).thenReturn(ethPeers);
    when(ethPeers.streamAvailablePeers()).thenReturn(Arrays.asList(peer1, peer2).stream());
    when(peerPendingTransactionTracker.isPeerSupported(peer1, EthProtocol.ETH65)).thenReturn(true);
    when(peerPendingTransactionTracker.isPeerSupported(peer2, EthProtocol.ETH65)).thenReturn(false);
    sender.onTransactionsAdded(Collections.singleton(tx));
    verify(peerPendingTransactionTracker, times(1)).addToPeerSendQueue(peer1, hash);
    verify(peerPendingTransactionTracker, never()).addToPeerSendQueue(peer2, hash);
}
Also used : EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) EthScheduler(org.hyperledger.besu.ethereum.eth.manager.EthScheduler) EthPeer(org.hyperledger.besu.ethereum.eth.manager.EthPeer) Transaction(org.hyperledger.besu.ethereum.core.Transaction) EthPeers(org.hyperledger.besu.ethereum.eth.manager.EthPeers) Hash(org.hyperledger.besu.datatypes.Hash) Test(org.junit.Test)

Example 2 with EthContext

use of org.hyperledger.besu.ethereum.eth.manager.EthContext in project besu by hyperledger.

the class Istanbul99ProtocolManagerTest method respondToEth65GetHeadersUsingIstanbul99.

@Test
public void respondToEth65GetHeadersUsingIstanbul99() throws ExecutionException, InterruptedException, TimeoutException {
    final CompletableFuture<Void> done = new CompletableFuture<>();
    final EthScheduler ethScheduler = new DeterministicEthScheduler(() -> false);
    EthPeers peers = new EthPeers(Istanbul99Protocol.NAME, TestClock.fixed(), new NoOpMetricsSystem(), 25);
    EthMessages messages = new EthMessages();
    final BigInteger networkId = BigInteger.ONE;
    try (final EthProtocolManager ethManager = new Istanbul99ProtocolManager(blockchain, networkId, protocolContext.getWorldStateArchive(), transactionPool, EthProtocolConfiguration.defaultConfig(), peers, messages, new EthContext(peers, messages, ethScheduler), Collections.emptyList(), false, ethScheduler)) {
        final long startBlock = blockchain.getChainHeadBlockNumber() + 1;
        final int blockCount = 5;
        final MessageData messageData = GetBlockHeadersMessage.create(startBlock, blockCount, 0, false);
        final PeerSendHandler onSend = (cap, message, conn) -> {
            if (message.getCode() == EthPV62.STATUS) {
                // Ignore status message
                return;
            }
            assertThat(message.getCode()).isEqualTo(EthPV62.BLOCK_HEADERS);
            final BlockHeadersMessage headersMsg = BlockHeadersMessage.readFrom(message);
            final List<BlockHeader> headers = Lists.newArrayList(headersMsg.getHeaders(protocolSchedule));
            assertThat(headers.size()).isEqualTo(0);
            done.complete(null);
        };
        final PeerConnection peer = setupPeer(ethManager, onSend);
        ethManager.processMessage(Istanbul99Protocol.ISTANBUL99, new DefaultMessage(peer, messageData));
        done.get(10, TimeUnit.SECONDS);
    }
}
Also used : MockPeerConnection(org.hyperledger.besu.ethereum.eth.manager.MockPeerConnection) StatusMessage(org.hyperledger.besu.ethereum.eth.messages.StatusMessage) EthPV62(org.hyperledger.besu.ethereum.eth.messages.EthPV62) PeerSendHandler(org.hyperledger.besu.ethereum.eth.manager.MockPeerConnection.PeerSendHandler) BeforeClass(org.junit.BeforeClass) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) NoOpMetricsSystem(org.hyperledger.besu.metrics.noop.NoOpMetricsSystem) DefaultMessage(org.hyperledger.besu.ethereum.p2p.rlpx.wire.DefaultMessage) EthProtocol(org.hyperledger.besu.ethereum.eth.EthProtocol) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) HashSet(java.util.HashSet) GetBlockHeadersMessage(org.hyperledger.besu.ethereum.eth.messages.GetBlockHeadersMessage) BlockchainSetupUtil(org.hyperledger.besu.ethereum.core.BlockchainSetupUtil) DataStorageFormat(org.hyperledger.besu.ethereum.worldstate.DataStorageFormat) Lists(com.google.common.collect.Lists) EthScheduler(org.hyperledger.besu.ethereum.eth.manager.EthScheduler) PeerConnection(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection) BigInteger(java.math.BigInteger) TransactionPool(org.hyperledger.besu.ethereum.eth.transactions.TransactionPool) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) EthProtocolConfiguration(org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) Set(java.util.Set) Test(org.junit.Test) BlockHeadersMessage(org.hyperledger.besu.ethereum.eth.messages.BlockHeadersMessage) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) EthProtocolManager(org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager) List(java.util.List) MessageData(org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData) EthPeers(org.hyperledger.besu.ethereum.eth.manager.EthPeers) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) DeterministicEthScheduler(org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler) EthMessages(org.hyperledger.besu.ethereum.eth.manager.EthMessages) Capability(org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability) Collections(java.util.Collections) TestClock(org.hyperledger.besu.testutil.TestClock) DefaultMessage(org.hyperledger.besu.ethereum.p2p.rlpx.wire.DefaultMessage) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) EthMessages(org.hyperledger.besu.ethereum.eth.manager.EthMessages) MockPeerConnection(org.hyperledger.besu.ethereum.eth.manager.MockPeerConnection) PeerConnection(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection) MessageData(org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData) DeterministicEthScheduler(org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler) EthPeers(org.hyperledger.besu.ethereum.eth.manager.EthPeers) EthProtocolManager(org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager) CompletableFuture(java.util.concurrent.CompletableFuture) EthScheduler(org.hyperledger.besu.ethereum.eth.manager.EthScheduler) DeterministicEthScheduler(org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler) NoOpMetricsSystem(org.hyperledger.besu.metrics.noop.NoOpMetricsSystem) BigInteger(java.math.BigInteger) List(java.util.List) GetBlockHeadersMessage(org.hyperledger.besu.ethereum.eth.messages.GetBlockHeadersMessage) BlockHeadersMessage(org.hyperledger.besu.ethereum.eth.messages.BlockHeadersMessage) PeerSendHandler(org.hyperledger.besu.ethereum.eth.manager.MockPeerConnection.PeerSendHandler) Test(org.junit.Test)

Example 3 with EthContext

use of org.hyperledger.besu.ethereum.eth.manager.EthContext in project besu by hyperledger.

the class FastSyncTargetManager method confirmPivotBlockHeader.

private CompletableFuture<Optional<EthPeer>> confirmPivotBlockHeader(final EthPeer bestPeer) {
    final BlockHeader pivotBlockHeader = fastSyncState.getPivotBlockHeader().get();
    final RetryingGetHeaderFromPeerByNumberTask task = RetryingGetHeaderFromPeerByNumberTask.forSingleNumber(protocolSchedule, ethContext, metricsSystem, pivotBlockHeader.getNumber(), MAX_QUERY_RETRIES_PER_PEER);
    task.assignPeer(bestPeer);
    return ethContext.getScheduler().timeout(task).thenCompose(result -> {
        if (peerHasDifferentPivotBlock(result)) {
            if (!hasPivotChanged(pivotBlockHeader)) {
                // if the pivot block has not changed, then warn and disconnect this peer
                LOG.warn("Best peer has wrong pivot block (#{}) expecting {} but received {}.  Disconnect: {}", pivotBlockHeader.getNumber(), pivotBlockHeader.getHash(), result.size() == 1 ? result.get(0).getHash() : "invalid response", bestPeer);
                bestPeer.disconnect(DisconnectReason.USELESS_PEER);
                return CompletableFuture.completedFuture(Optional.<EthPeer>empty());
            }
            LOG.debug("Retrying best peer {} with new pivot block {}", bestPeer.getShortNodeId(), pivotBlockHeader.toLogString());
            return confirmPivotBlockHeader(bestPeer);
        } else {
            return CompletableFuture.completedFuture(Optional.of(bestPeer));
        }
    }).exceptionally(error -> {
        LOG.debug("Could not confirm best peer had pivot block", error);
        return Optional.empty();
    });
}
Also used : Logger(org.slf4j.Logger) EthPeer(org.hyperledger.besu.ethereum.eth.manager.EthPeer) SyncTargetManager(org.hyperledger.besu.ethereum.eth.sync.SyncTargetManager) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) LoggerFactory(org.slf4j.LoggerFactory) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) CompletableFuture(java.util.concurrent.CompletableFuture) SynchronizerConfiguration(org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) List(java.util.List) RetryingGetHeaderFromPeerByNumberTask(org.hyperledger.besu.ethereum.eth.sync.tasks.RetryingGetHeaderFromPeerByNumberTask) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) Optional(java.util.Optional) WorldStateStorage(org.hyperledger.besu.ethereum.worldstate.WorldStateStorage) MetricsSystem(org.hyperledger.besu.plugin.services.MetricsSystem) MAX_QUERY_RETRIES_PER_PEER(org.hyperledger.besu.ethereum.eth.sync.fastsync.PivotBlockRetriever.MAX_QUERY_RETRIES_PER_PEER) DisconnectReason(org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason) EthPeer(org.hyperledger.besu.ethereum.eth.manager.EthPeer) RetryingGetHeaderFromPeerByNumberTask(org.hyperledger.besu.ethereum.eth.sync.tasks.RetryingGetHeaderFromPeerByNumberTask) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 4 with EthContext

use of org.hyperledger.besu.ethereum.eth.manager.EthContext in project besu by hyperledger.

the class PivotBlockConfirmer method executePivotQuery.

private CompletableFuture<BlockHeader> executePivotQuery(final long blockNumber) {
    if (isCancelled.get() || result.isDone()) {
        // Stop loop if this task is done
        return CompletableFuture.failedFuture(new CancellationException());
    }
    final Optional<RetryingGetHeaderFromPeerByNumberTask> query = createPivotQuery(blockNumber);
    final CompletableFuture<BlockHeader> pivotHeaderFuture;
    if (query.isPresent()) {
        final CompletableFuture<BlockHeader> headerQuery = query.get().getHeader();
        pivotHeaderFuture = FutureUtils.exceptionallyCompose(headerQuery, (error) -> executePivotQuery(blockNumber));
    } else {
        // We were unable to find a peer to query, wait and try again
        LOG.debug("No peer currently available to query for block {}.", blockNumber);
        pivotHeaderFuture = ethContext.getScheduler().timeout(WaitForPeerTask.create(ethContext, metricsSystem), Duration.ofSeconds(5)).handle(// Ignore result
        (err, res) -> null).thenCompose(res -> executePivotQuery(blockNumber));
    }
    return pivotHeaderFuture;
}
Also used : EthTask(org.hyperledger.besu.ethereum.eth.manager.task.EthTask) Logger(org.slf4j.Logger) EthPeer(org.hyperledger.besu.ethereum.eth.manager.EthPeer) CancellationException(java.util.concurrent.CancellationException) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Bytes(org.apache.tuweni.bytes.Bytes) Collectors(java.util.stream.Collectors) WaitForPeerTask(org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeerTask) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) FutureUtils(org.hyperledger.besu.util.FutureUtils) RetryingGetHeaderFromPeerByNumberTask(org.hyperledger.besu.ethereum.eth.sync.tasks.RetryingGetHeaderFromPeerByNumberTask) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) Optional(java.util.Optional) MetricsSystem(org.hyperledger.besu.plugin.services.MetricsSystem) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CancellationException(java.util.concurrent.CancellationException) RetryingGetHeaderFromPeerByNumberTask(org.hyperledger.besu.ethereum.eth.sync.tasks.RetryingGetHeaderFromPeerByNumberTask) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 5 with EthContext

use of org.hyperledger.besu.ethereum.eth.manager.EthContext 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)

Aggregations

EthContext (org.hyperledger.besu.ethereum.eth.manager.EthContext)34 EthProtocolManager (org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager)16 Test (org.junit.Test)15 ProtocolContext (org.hyperledger.besu.ethereum.ProtocolContext)13 EthPeers (org.hyperledger.besu.ethereum.eth.manager.EthPeers)13 EthScheduler (org.hyperledger.besu.ethereum.eth.manager.EthScheduler)12 Block (org.hyperledger.besu.ethereum.core.Block)11 ProtocolSchedule (org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule)11 Optional (java.util.Optional)10 MiningParameters (org.hyperledger.besu.ethereum.core.MiningParameters)9 Transaction (org.hyperledger.besu.ethereum.core.Transaction)8 Before (org.junit.Before)8 EthMessages (org.hyperledger.besu.ethereum.eth.manager.EthMessages)7 EthPeer (org.hyperledger.besu.ethereum.eth.manager.EthPeer)7 SyncState (org.hyperledger.besu.ethereum.eth.sync.state.SyncState)7 BlockDataGenerator (org.hyperledger.besu.ethereum.core.BlockDataGenerator)6 TransactionReceipt (org.hyperledger.besu.ethereum.core.TransactionReceipt)6 TransactionPool (org.hyperledger.besu.ethereum.eth.transactions.TransactionPool)6 NoOpMetricsSystem (org.hyperledger.besu.metrics.noop.NoOpMetricsSystem)6 CompletableFuture (java.util.concurrent.CompletableFuture)5