Search in sources :

Example 1 with SafeFuture

use of tech.pegasys.teku.infrastructure.async.SafeFuture in project teku by ConsenSys.

the class TekuDepositSender method sendValidatorDeposits.

public void sendValidatorDeposits(final BesuNode eth1Node, final List<ValidatorKeys> validatorKeys, UInt64 amount) throws InterruptedException, ExecutionException, TimeoutException {
    final Eth1Address eth1Address = Eth1Address.fromHexString(eth1Node.getDepositContractAddress());
    final Credentials eth1Credentials = Credentials.create(eth1Node.getRichBenefactorKey());
    final DepositSenderService depositSenderService = new DepositSenderService(spec, eth1Node.getExternalJsonRpcUrl(), eth1Credentials, eth1Address, amount);
    final List<SafeFuture<TransactionReceipt>> transactionReceipts = validatorKeys.stream().map(depositSenderService::sendDeposit).collect(Collectors.toList());
    final SafeFuture<Void> future = SafeFuture.allOf(transactionReceipts.toArray(SafeFuture[]::new));
    Waiter.waitFor(future, Duration.ofMinutes(2));
}
Also used : SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) Eth1Address(tech.pegasys.teku.spec.datastructures.eth1.Eth1Address) Credentials(org.web3j.crypto.Credentials) DepositSenderService(tech.pegasys.teku.test.acceptance.dsl.tools.deposits.DepositSenderService)

Example 2 with SafeFuture

use of tech.pegasys.teku.infrastructure.async.SafeFuture in project teku by ConsenSys.

the class SyncController method startSync.

private InProgressSync startSync(final SyncTarget syncTarget) {
    eventThread.checkOnEventThread();
    final TargetChain chain = syncTarget.getTargetChain();
    if (currentSync.map(current -> !current.isFailed() && current.hasSameTarget(chain)).orElse(false)) {
        LOG.trace("Not starting new sync because it has the same target as current sync");
        return currentSync.get();
    }
    LOG.debug("Starting new sync to {} with {} peers finalized: {}, speculative: {}", chain.getChainHead(), chain.getPeerCount(), syncTarget.isFinalizedSync(), syncTarget.isSpeculativeSync());
    final UInt64 startSlot = recentChainData.getHeadSlot();
    final SafeFuture<SyncResult> syncResult = sync.syncToChain(chain);
    syncResult.finishAsync(this::onSyncComplete, error -> {
        LOG.error("Error encountered during sync", error);
        onSyncComplete(SyncResult.FAILED);
    }, eventThread);
    return new InProgressSync(startSlot, syncTarget, syncResult);
}
Also used : Executor(java.util.concurrent.Executor) TargetChain(tech.pegasys.teku.beacon.sync.forward.multipeer.chains.TargetChain) EventThread(tech.pegasys.teku.infrastructure.async.eventthread.EventThread) MoreObjects(com.google.common.base.MoreObjects) SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) Subscribers(tech.pegasys.teku.infrastructure.subscribers.Subscribers) SyncingStatus(tech.pegasys.teku.beacon.sync.events.SyncingStatus) Objects(java.util.Objects) SyncSubscriber(tech.pegasys.teku.beacon.sync.forward.ForwardSync.SyncSubscriber) Logger(org.apache.logging.log4j.Logger) RecentChainData(tech.pegasys.teku.storage.client.RecentChainData) Optional(java.util.Optional) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) LogManager(org.apache.logging.log4j.LogManager) TargetChain(tech.pegasys.teku.beacon.sync.forward.multipeer.chains.TargetChain) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64)

Example 3 with SafeFuture

use of tech.pegasys.teku.infrastructure.async.SafeFuture in project teku by ConsenSys.

the class BatchImporter method importBatch.

/**
 * Import the blocks in the specified batch.
 *
 * <p>Guaranteed to return immediately and perform the import on worker threads.
 *
 * @param batch the batch to import
 * @return a future reporting the result of the import
 */
public SafeFuture<BatchImportResult> importBatch(final Batch batch) {
    // Copy the data from batch as we're going to use them from off the event thread.
    final List<SignedBeaconBlock> blocks = new ArrayList<>(batch.getBlocks());
    final Optional<SyncSource> source = batch.getSource();
    checkState(!blocks.isEmpty(), "Batch has no blocks to import");
    return asyncRunner.runAsync(() -> {
        SafeFuture<BlockImportResult> importResult = importBlock(blocks.get(0), source.orElseThrow());
        for (int i = 1; i < blocks.size(); i++) {
            final SignedBeaconBlock block = blocks.get(i);
            importResult = importResult.thenCompose(previousResult -> {
                if (previousResult.isSuccessful()) {
                    return importBlock(block, source.orElseThrow());
                } else {
                    return SafeFuture.completedFuture(previousResult);
                }
            });
        }
        return importResult.thenApply(lastBlockImportResult -> {
            if (lastBlockImportResult.isSuccessful()) {
                return BatchImportResult.IMPORTED_ALL_BLOCKS;
            } else if (lastBlockImportResult.getFailureReason() == BlockImportResult.FailureReason.FAILED_EXECUTION_PAYLOAD_EXECUTION) {
                return BatchImportResult.SERVICE_OFFLINE;
            }
            LOG.debug("Failed to import batch {}: {}", batch, lastBlockImportResult.getFailureReason(), lastBlockImportResult.getFailureCause().orElse(null));
            return BatchImportResult.IMPORT_FAILED;
        });
    });
}
Also used : AsyncRunner(tech.pegasys.teku.infrastructure.async.AsyncRunner) Batch(tech.pegasys.teku.beacon.sync.forward.multipeer.batches.Batch) SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) SyncSource(tech.pegasys.teku.networking.eth2.peers.SyncSource) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ArrayList(java.util.ArrayList) DisconnectReason(tech.pegasys.teku.networking.p2p.peer.DisconnectReason) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Optional(java.util.Optional) BlockImporter(tech.pegasys.teku.statetransition.block.BlockImporter) SignedBeaconBlock(tech.pegasys.teku.spec.datastructures.blocks.SignedBeaconBlock) LogManager(org.apache.logging.log4j.LogManager) BlockImportResult(tech.pegasys.teku.spec.logic.common.statetransition.results.BlockImportResult) SyncSource(tech.pegasys.teku.networking.eth2.peers.SyncSource) ArrayList(java.util.ArrayList) SignedBeaconBlock(tech.pegasys.teku.spec.datastructures.blocks.SignedBeaconBlock) BlockImportResult(tech.pegasys.teku.spec.logic.common.statetransition.results.BlockImportResult)

Example 4 with SafeFuture

use of tech.pegasys.teku.infrastructure.async.SafeFuture in project teku by ConsenSys.

the class SyncControllerTest method shouldNotNotifySubscribersWhenRunningSpeculativeTarget.

@Test
void shouldNotNotifySubscribersWhenRunningSpeculativeTarget() {
    final SyncSubscriber subscriber = mock(SyncSubscriber.class);
    syncController.subscribeToSyncChanges(subscriber);
    final SafeFuture<SyncResult> syncResult = new SafeFuture<>();
    when(syncTargetSelector.selectSyncTarget(any())).thenReturn(Optional.of(SyncTarget.speculativeTarget(targetChain)));
    when(sync.syncToChain(targetChain)).thenReturn(syncResult);
    onTargetChainsUpdated();
    syncResult.complete(SyncResult.COMPLETE);
    verify(subscriberExecutor, never()).execute(any());
}
Also used : SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) SyncSubscriber(tech.pegasys.teku.beacon.sync.forward.ForwardSync.SyncSubscriber) Test(org.junit.jupiter.api.Test)

Example 5 with SafeFuture

use of tech.pegasys.teku.infrastructure.async.SafeFuture in project teku by ConsenSys.

the class PeerSyncTest method sync_stopSyncIfPeerSendsBlocksInWrongOrder.

@Test
void sync_stopSyncIfPeerSendsBlocksInWrongOrder() {
    final UInt64 startSlot = UInt64.ONE;
    UInt64 peerHeadSlot = UInt64.valueOf(1000000);
    withPeerHeadSlot(peerHeadSlot);
    final SafeFuture<Void> requestFuture = new SafeFuture<>();
    when(peer.requestBlocksByRange(any(), any(), any(), any())).thenReturn(requestFuture);
    final SafeFuture<PeerSyncResult> syncFuture = peerSync.sync(peer);
    assertThat(syncFuture).isNotDone();
    verify(peer).requestBlocksByRange(eq(startSlot), eq(MAX_BLOCK_BY_RANGE_REQUEST_SIZE), eq(UInt64.ONE), responseListenerArgumentCaptor.capture());
    requestFuture.completeExceptionally(new BlocksByRangeResponseInvalidResponseException(peer, BlocksByRangeResponseInvalidResponseException.InvalidResponseType.BLOCK_SLOT_NOT_GREATER_THAN_PREVIOUS_BLOCK_SLOT));
    // Peer returns some blocks but they are not ordered
    assertThat(syncFuture).isCompletedWithValue(PeerSyncResult.INVALID_RESPONSE);
    verify(peer).disconnectCleanly(any());
}
Also used : SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) BlocksByRangeResponseInvalidResponseException(tech.pegasys.teku.networking.eth2.rpc.beaconchain.methods.BlocksByRangeResponseInvalidResponseException) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) Test(org.junit.jupiter.api.Test)

Aggregations

SafeFuture (tech.pegasys.teku.infrastructure.async.SafeFuture)104 Test (org.junit.jupiter.api.Test)66 UInt64 (tech.pegasys.teku.infrastructure.unsigned.UInt64)55 Optional (java.util.Optional)43 Bytes32 (org.apache.tuweni.bytes.Bytes32)30 Spec (tech.pegasys.teku.spec.Spec)28 List (java.util.List)25 LogManager (org.apache.logging.log4j.LogManager)25 SignedBeaconBlock (tech.pegasys.teku.spec.datastructures.blocks.SignedBeaconBlock)25 Logger (org.apache.logging.log4j.Logger)23 BeaconState (tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState)18 Collection (java.util.Collection)16 BLSSignature (tech.pegasys.teku.bls.BLSSignature)15 Attestation (tech.pegasys.teku.spec.datastructures.operations.Attestation)15 RecentChainData (tech.pegasys.teku.storage.client.RecentChainData)15 Set (java.util.Set)11 SafeFutureAssert.assertThatSafeFuture (tech.pegasys.teku.infrastructure.async.SafeFutureAssert.assertThatSafeFuture)11 ArrayList (java.util.ArrayList)10 ConnectionManager (tech.pegasys.teku.networking.p2p.connection.ConnectionManager)10 CombinedChainDataClient (tech.pegasys.teku.storage.client.CombinedChainDataClient)10