Search in sources :

Example 1 with WorldStateArchive

use of org.hyperledger.besu.ethereum.worldstate.WorldStateArchive in project besu by hyperledger.

the class SStoreOperationTest method createMessageFrame.

private MessageFrame createMessageFrame(final Address address, final Gas initialGas, final Gas remainingGas) {
    final Blockchain blockchain = mock(Blockchain.class);
    final WorldStateArchive worldStateArchive = createInMemoryWorldStateArchive();
    final WorldUpdater worldStateUpdater = worldStateArchive.getMutable().updater();
    final BlockHeader blockHeader = new BlockHeaderTestFixture().buildHeader();
    final MessageFrame frame = new MessageFrameTestFixture().address(address).worldUpdater(worldStateUpdater).blockHeader(blockHeader).blockchain(blockchain).initialGas(initialGas).build();
    worldStateUpdater.getOrCreate(address).getMutable().setBalance(Wei.of(1));
    worldStateUpdater.commit();
    frame.setGasRemaining(remainingGas);
    return frame;
}
Also used : BlockHeaderTestFixture(org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture) InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive(org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive) WorldStateArchive(org.hyperledger.besu.ethereum.worldstate.WorldStateArchive) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) WorldUpdater(org.hyperledger.besu.evm.worldstate.WorldUpdater) MessageFrame(org.hyperledger.besu.evm.frame.MessageFrame) MessageFrameTestFixture(org.hyperledger.besu.ethereum.core.MessageFrameTestFixture) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 2 with WorldStateArchive

use of org.hyperledger.besu.ethereum.worldstate.WorldStateArchive in project besu by hyperledger.

the class JsonRpcHttpServiceTest method getBlockByNumberForPending.

@Test
public void getBlockByNumberForPending() throws Exception {
    final String id = "123";
    final RequestBody body = RequestBody.create(JSON, "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"eth_getBlockByNumber\", \"params\": [\"pending\",true]}");
    // Setup mocks to return a block
    final BlockDataGenerator gen = new BlockDataGenerator();
    final Block block = gen.genesisBlock();
    final BlockWithMetadata<TransactionWithMetadata, Hash> blockWithMetadata = blockWithMetadata(block);
    when(blockchainQueries.headBlockNumber()).thenReturn(0L);
    when(blockchainQueries.blockByNumber(eq(0L))).thenReturn(Optional.of(blockWithMetadata));
    when(blockchainQueries.getBlockchain()).thenReturn(blockchain);
    when(blockchain.getBlockHeader(blockchainQueries.headBlockNumber())).thenReturn(Optional.of(block.getHeader()));
    WorldStateArchive state = mock(WorldStateArchive.class);
    when(state.isWorldStateAvailable(any(Hash.class), any(Hash.class))).thenReturn(true);
    when(blockchainQueries.getWorldStateArchive()).thenReturn(state);
    try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
        assertThat(resp.code()).isEqualTo(200);
        // Check general format of result
        final String respBody = resp.body().string();
        final JsonObject json = new JsonObject(respBody);
        testHelper.assertValidJsonRpcResult(json, id);
        // Check result
        final JsonObject result = json.getJsonObject("result");
        verifyBlockResult(block, blockWithMetadata.getTotalDifficulty(), result, false);
    }
}
Also used : Response(okhttp3.Response) WorldStateArchive(org.hyperledger.besu.ethereum.worldstate.WorldStateArchive) TransactionWithMetadata(org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata) Block(org.hyperledger.besu.ethereum.core.Block) JsonObject(io.vertx.core.json.JsonObject) Hash(org.hyperledger.besu.datatypes.Hash) BlockDataGenerator(org.hyperledger.besu.ethereum.core.BlockDataGenerator) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 3 with WorldStateArchive

use of org.hyperledger.besu.ethereum.worldstate.WorldStateArchive in project besu by hyperledger.

the class JsonRpcHttpServiceTest method getBlockByNumberForLatest.

@Test
public void getBlockByNumberForLatest() throws Exception {
    final String id = "123";
    final RequestBody body = RequestBody.create(JSON, "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"eth_getBlockByNumber\", \"params\": [\"latest\",true]}");
    // Setup mocks to return a block
    final BlockDataGenerator gen = new BlockDataGenerator();
    final Block block = gen.genesisBlock();
    final BlockWithMetadata<TransactionWithMetadata, Hash> blockWithMetadata = blockWithMetadata(block);
    when(blockchainQueries.headBlockNumber()).thenReturn(0L);
    when(blockchainQueries.blockByNumber(eq(0L))).thenReturn(Optional.of(blockWithMetadata));
    when(blockchainQueries.getBlockchain()).thenReturn(blockchain);
    when(blockchain.getBlockHeader(blockchainQueries.headBlockNumber())).thenReturn(Optional.of(block.getHeader()));
    WorldStateArchive state = mock(WorldStateArchive.class);
    when(state.isWorldStateAvailable(any(Hash.class), any(Hash.class))).thenReturn(true);
    when(blockchainQueries.getWorldStateArchive()).thenReturn(state);
    try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
        assertThat(resp.code()).isEqualTo(200);
        // Check general format of result
        final String respBody = resp.body().string();
        final JsonObject json = new JsonObject(respBody);
        testHelper.assertValidJsonRpcResult(json, id);
        // Check result
        final JsonObject result = json.getJsonObject("result");
        verifyBlockResult(block, blockWithMetadata.getTotalDifficulty(), result, false);
    }
}
Also used : Response(okhttp3.Response) WorldStateArchive(org.hyperledger.besu.ethereum.worldstate.WorldStateArchive) TransactionWithMetadata(org.hyperledger.besu.ethereum.api.query.TransactionWithMetadata) Block(org.hyperledger.besu.ethereum.core.Block) JsonObject(io.vertx.core.json.JsonObject) Hash(org.hyperledger.besu.datatypes.Hash) BlockDataGenerator(org.hyperledger.besu.ethereum.core.BlockDataGenerator) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 4 with WorldStateArchive

use of org.hyperledger.besu.ethereum.worldstate.WorldStateArchive in project besu by hyperledger.

the class TransactionSmartContractPermissioningControllerTest method setupController.

private TransactionSmartContractPermissioningController setupController(final String resourceName, final String contractAddressString) throws IOException {
    final ProtocolSchedule protocolSchedule = ProtocolScheduleFixture.MAINNET;
    final String emptyContractFile = Resources.toString(this.getClass().getResource(resourceName), UTF_8);
    final GenesisState genesisState = GenesisState.fromConfig(GenesisConfigFile.fromConfig(emptyContractFile), protocolSchedule);
    final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock());
    final WorldStateArchive worldArchive = createInMemoryWorldStateArchive();
    genesisState.writeStateTo(worldArchive.getMutable());
    final TransactionSimulator ts = new TransactionSimulator(blockchain, worldArchive, protocolSchedule);
    final Address contractAddress = Address.fromHexString(contractAddressString);
    when(metricsSystem.createCounter(BesuMetricCategory.PERMISSIONING, "transaction_smart_contract_check_count", "Number of times the transaction smart contract permissioning provider has been checked")).thenReturn(checkCounter);
    when(metricsSystem.createCounter(BesuMetricCategory.PERMISSIONING, "transaction_smart_contract_check_count_permitted", "Number of times the transaction smart contract permissioning provider has been checked and returned permitted")).thenReturn(checkPermittedCounter);
    when(metricsSystem.createCounter(BesuMetricCategory.PERMISSIONING, "transaction_smart_contract_check_count_unpermitted", "Number of times the transaction smart contract permissioning provider has been checked and returned unpermitted")).thenReturn(checkUnpermittedCounter);
    return new TransactionSmartContractPermissioningController(contractAddress, ts, metricsSystem);
}
Also used : GenesisState(org.hyperledger.besu.ethereum.chain.GenesisState) Address(org.hyperledger.besu.datatypes.Address) InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive(org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive) WorldStateArchive(org.hyperledger.besu.ethereum.worldstate.WorldStateArchive) MutableBlockchain(org.hyperledger.besu.ethereum.chain.MutableBlockchain) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) TransactionSimulator(org.hyperledger.besu.ethereum.transaction.TransactionSimulator)

Example 5 with WorldStateArchive

use of org.hyperledger.besu.ethereum.worldstate.WorldStateArchive in project besu by hyperledger.

the class FastWorldStateDownloaderTest method testCancellation.

@SuppressWarnings("unchecked")
private void testCancellation(final boolean shouldCancelFuture) {
    final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create();
    // Prevent the persistence service from running
    final MockExecutorService serviceExecutor = ((DeterministicEthScheduler) ethProtocolManager.ethContext().getScheduler()).mockServiceExecutor();
    serviceExecutor.setAutoRun(false);
    // Setup "remote" state
    final WorldStateArchive remoteWorldStateArchive = createInMemoryWorldStateArchive();
    final MutableWorldState remoteWorldState = remoteWorldStateArchive.getMutable();
    // Generate accounts and save corresponding state root
    dataGen.createRandomContractAccountsWithNonEmptyStorage(remoteWorldState, 20);
    final Hash stateRoot = remoteWorldState.rootHash();
    final BlockHeader header = dataGen.block(BlockOptions.create().setStateRoot(stateRoot).setBlockNumber(10)).getHeader();
    // Create some peers
    final List<RespondingEthPeer> peers = Stream.generate(() -> EthProtocolManagerTestUtil.createPeer(ethProtocolManager, header.getNumber())).limit(5).collect(Collectors.toList());
    final InMemoryTasksPriorityQueues<NodeDataRequest> taskCollection = new InMemoryTasksPriorityQueues<>();
    final WorldStateStorage localStorage = new WorldStateKeyValueStorage(new InMemoryKeyValueStorage());
    final WorldStateDownloader downloader = createDownloader(ethProtocolManager.ethContext(), localStorage, taskCollection);
    final FastSyncState fastSyncState = new FastSyncState(header);
    final CompletableFuture<Void> result = downloader.run(null, fastSyncState);
    // Send a few responses
    final RespondingEthPeer.Responder responder = RespondingEthPeer.blockchainResponder(mock(Blockchain.class), remoteWorldStateArchive);
    for (int i = 0; i < 3; i++) {
        for (final RespondingEthPeer peer : peers) {
            peer.respond(responder);
        }
        giveOtherThreadsAGo();
    }
    // Sanity check
    assertThat(result.isDone()).isFalse();
    // Reset taskCollection so we can track interactions after the cancellation
    reset(taskCollection);
    if (shouldCancelFuture) {
        result.cancel(true);
    } else {
        downloader.cancel();
        assertThat(result).isCancelled();
    }
    // Send some more responses after cancelling
    for (int i = 0; i < 3; i++) {
        for (final RespondingEthPeer peer : peers) {
            peer.respond(responder);
        }
        giveOtherThreadsAGo();
    }
    // Now allow the persistence service to run which should exit immediately
    serviceExecutor.runPendingFutures();
    verify(taskCollection, times(1)).clear();
    verify(taskCollection, never()).remove();
    verify(taskCollection, never()).add(any(NodeDataRequest.class));
    // Target world state should not be available
    assertThat(localStorage.isWorldStateAvailable(header.getStateRoot(), header.getHash())).isFalse();
}
Also used : WorldStateStorage(org.hyperledger.besu.ethereum.worldstate.WorldStateStorage) MutableWorldState(org.hyperledger.besu.ethereum.core.MutableWorldState) InMemoryKeyValueStorage(org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage) RespondingEthPeer(org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) DeterministicEthScheduler(org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler) InMemoryTasksPriorityQueues(org.hyperledger.besu.services.tasks.InMemoryTasksPriorityQueues) Hash(org.hyperledger.besu.datatypes.Hash) WorldStateDownloader(org.hyperledger.besu.ethereum.eth.sync.worldstate.WorldStateDownloader) FastSyncState(org.hyperledger.besu.ethereum.eth.sync.fastsync.FastSyncState) EthProtocolManager(org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager) WorldStateKeyValueStorage(org.hyperledger.besu.ethereum.storage.keyvalue.WorldStateKeyValueStorage) InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive(org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive) DefaultWorldStateArchive(org.hyperledger.besu.ethereum.worldstate.DefaultWorldStateArchive) WorldStateArchive(org.hyperledger.besu.ethereum.worldstate.WorldStateArchive) MockExecutorService(org.hyperledger.besu.testutil.MockExecutorService) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Aggregations

WorldStateArchive (org.hyperledger.besu.ethereum.worldstate.WorldStateArchive)36 InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive (org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive)23 Hash (org.hyperledger.besu.datatypes.Hash)17 MutableWorldState (org.hyperledger.besu.ethereum.core.MutableWorldState)15 BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)14 Blockchain (org.hyperledger.besu.ethereum.chain.Blockchain)13 MutableBlockchain (org.hyperledger.besu.ethereum.chain.MutableBlockchain)11 DefaultWorldStateArchive (org.hyperledger.besu.ethereum.worldstate.DefaultWorldStateArchive)11 ArrayList (java.util.ArrayList)10 ProtocolContext (org.hyperledger.besu.ethereum.ProtocolContext)10 Block (org.hyperledger.besu.ethereum.core.Block)10 BlockDataGenerator (org.hyperledger.besu.ethereum.core.BlockDataGenerator)10 ProtocolSchedule (org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule)10 EthProtocolManager (org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager)9 TransactionPool (org.hyperledger.besu.ethereum.eth.transactions.TransactionPool)9 WorldStateStorage (org.hyperledger.besu.ethereum.worldstate.WorldStateStorage)9 NoOpMetricsSystem (org.hyperledger.besu.metrics.noop.NoOpMetricsSystem)9 Collections (java.util.Collections)8 List (java.util.List)8 Optional (java.util.Optional)8