Search in sources :

Example 1 with LogWithMetadata

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

the class DefaultBlockchainTest method appendBlockWithReorgToLongerChain.

@Test
public void appendBlockWithReorgToLongerChain() {
    final BlockDataGenerator gen = new BlockDataGenerator(2);
    // Setup an initial blockchain
    final int originalChainLength = 4;
    final List<Block> chain = gen.blockSequence(originalChainLength);
    final List<List<TransactionReceipt>> blockReceipts = chain.stream().map(gen::receipts).collect(Collectors.toList());
    final KeyValueStorage kvStore = new InMemoryKeyValueStorage();
    final DefaultBlockchain blockchain = createMutableBlockchain(kvStore, chain.get(0));
    // Listen to block events and add the Logs here
    List<LogWithMetadata> logsWithMetadata = new ArrayList<>();
    blockchain.observeBlockAdded(event -> logsWithMetadata.addAll(event.getLogsWithMetadata()));
    List<LogWithMetadata> expectedLogsWithMetadata = new ArrayList<>();
    for (int i = 1; i < chain.size(); i++) {
        blockchain.appendBlock(chain.get(i), blockReceipts.get(i));
        expectedLogsWithMetadata.addAll(LogWithMetadata.generate(chain.get(i), blockReceipts.get(i), false));
    }
    final Block originalHead = chain.get(originalChainLength - 1);
    // Create parallel fork of length 2 from 3 blocks back
    final List<Block> forkBlocks = new ArrayList<>();
    final int forkStart = 3;
    final int commonAncestor = 2;
    // Generate first block
    BlockDataGenerator.BlockOptions options = new BlockDataGenerator.BlockOptions().setParentHash(chain.get(commonAncestor).getHash()).setBlockNumber(forkStart).setDifficulty(chain.get(forkStart).getHeader().getDifficulty().subtract(5L));
    forkBlocks.add(gen.block(options));
    // Generate second block
    options = new BlockDataGenerator.BlockOptions().setParentHash(forkBlocks.get(0).getHash()).setBlockNumber(forkStart + 1).setDifficulty(Difficulty.of(10L));
    forkBlocks.add(gen.block(options));
    // Generate corresponding receipts
    final List<List<TransactionReceipt>> forkReceipts = forkBlocks.stream().map(gen::receipts).collect(Collectors.toList());
    // Collect fork data
    final List<Block> reorgedChain = new ArrayList<>(chain.subList(0, forkStart));
    reorgedChain.addAll(forkBlocks);
    final List<List<TransactionReceipt>> reorgedReceipts = new ArrayList<>(blockReceipts.subList(0, forkStart));
    reorgedReceipts.addAll(forkReceipts);
    // Add first block in fork, which should not cause a reorg
    blockchain.appendBlock(forkBlocks.get(0), forkReceipts.get(0));
    // Check chain has not reorganized
    for (int i = 0; i < chain.size(); i++) {
        assertBlockDataIsStored(blockchain, chain.get(i), blockReceipts.get(i));
    }
    assertBlockIsHead(blockchain, originalHead);
    assertTotalDifficultiesAreConsistent(blockchain, originalHead);
    // Check transactions were not indexed
    for (final Transaction tx : forkBlocks.get(0).getBody().getTransactions()) {
        assertThat(blockchain.getTransactionByHash(tx.getHash())).isNotPresent();
    }
    // Appended block should be tracked as a fork
    assertThat(blockchain.blockIsOnCanonicalChain(forkBlocks.get(0).getHash())).isFalse();
    Set<Hash> forks = blockchain.getForks();
    assertThat(forks.size()).isEqualTo(1);
    assertThat(forks.stream().anyMatch(f -> f.equals(forkBlocks.get(0).getHash()))).isTrue();
    // Add second block in fork, which should cause a reorg
    blockchain.appendBlock(forkBlocks.get(1), forkReceipts.get(1));
    // Check chain has reorganized
    for (int i = 0; i < reorgedChain.size(); i++) {
        assertBlockDataIsStored(blockchain, reorgedChain.get(i), reorgedReceipts.get(i));
    }
    assertBlockIsHead(blockchain, forkBlocks.get(1));
    assertTotalDifficultiesAreConsistent(blockchain, forkBlocks.get(1));
    // Check old transactions have been removed
    final List<Transaction> removedTransactions = new ArrayList<>();
    for (int i = forkStart; i < originalChainLength; i++) {
        removedTransactions.addAll(chain.get(i).getBody().getTransactions());
    }
    for (final Transaction tx : removedTransactions) {
        assertThat(blockchain.getTransactionByHash(tx.getHash())).isNotPresent();
    }
    // LogWithMetadata reflecting removal of logs
    for (int i = originalChainLength - 1; i >= forkStart; i--) {
        final Block currentBlock = chain.get(i);
        expectedLogsWithMetadata.addAll(Lists.reverse(LogWithMetadata.generate(currentBlock, blockchain.getTxReceipts(currentBlock.getHash()).get(), true)));
    }
    // LogWithMetadata reflecting addition of logs
    for (int i = 0; i < forkBlocks.size(); i++) {
        expectedLogsWithMetadata.addAll(LogWithMetadata.generate(forkBlocks.get(i), forkReceipts.get(i), false));
    }
    // Old chain head should now be tracked as a fork.
    forks = blockchain.getForks();
    assertThat(forks.size()).isEqualTo(1);
    assertThat(forks.stream().anyMatch(f -> f.equals(originalHead.getHash()))).isTrue();
    // Old chain should not be on canonical chain.
    for (int i = commonAncestor + 1; i < originalChainLength; i++) {
        assertThat(blockchain.blockIsOnCanonicalChain(chain.get(i).getHash())).isFalse();
    }
    assertThat(logsWithMetadata).containsExactly(expectedLogsWithMetadata.toArray(new LogWithMetadata[] {}));
}
Also used : BlockOptions(org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions) BlockOptions(org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions) InMemoryKeyValueStorage(org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage) KeyValueStorage(org.hyperledger.besu.plugin.services.storage.KeyValueStorage) InMemoryKeyValueStorage(org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage) ArrayList(java.util.ArrayList) Hash(org.hyperledger.besu.datatypes.Hash) BlockDataGenerator(org.hyperledger.besu.ethereum.core.BlockDataGenerator) Transaction(org.hyperledger.besu.ethereum.core.Transaction) LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) Block(org.hyperledger.besu.ethereum.core.Block) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 2 with LogWithMetadata

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

the class DefaultBlockchainTest method appendBlock.

@Test
public void appendBlock() {
    final BlockDataGenerator gen = new BlockDataGenerator();
    final KeyValueStorage kvStore = new InMemoryKeyValueStorage();
    final Block genesisBlock = gen.genesisBlock();
    final DefaultBlockchain blockchain = createMutableBlockchain(kvStore, genesisBlock);
    final BlockDataGenerator.BlockOptions options = new BlockDataGenerator.BlockOptions().setBlockNumber(1L).addTransaction(gen.transactions(5)).setParentHash(genesisBlock.getHash());
    final Block newBlock = gen.block(options);
    final List<TransactionReceipt> receipts = gen.receipts(newBlock);
    blockchain.observeBlockAdded((event -> assertThat(event.getLogsWithMetadata()).containsExactly(LogWithMetadata.generate(newBlock, receipts, false).toArray(new LogWithMetadata[] {}))));
    blockchain.appendBlock(newBlock, receipts);
    assertBlockIsHead(blockchain, newBlock);
    assertTotalDifficultiesAreConsistent(blockchain, newBlock);
    assertThat(blockchain.getForks()).isEmpty();
}
Also used : BlockOptions(org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions) BlockOptions(org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NoOpMetricsSystem(org.hyperledger.besu.metrics.noop.NoOpMetricsSystem) ArrayList(java.util.ArrayList) BlockDataGenerator(org.hyperledger.besu.ethereum.core.BlockDataGenerator) Lists(com.google.common.collect.Lists) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) TransactionReceipt(org.hyperledger.besu.ethereum.core.TransactionReceipt) Block(org.hyperledger.besu.ethereum.core.Block) MainnetBlockHeaderFunctions(org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions) Difficulty(org.hyperledger.besu.ethereum.core.Difficulty) MetricsSystemFactory(org.hyperledger.besu.metrics.MetricsSystemFactory) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) KeyValueStoragePrefixedKeyBlockchainStorage(org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStoragePrefixedKeyBlockchainStorage) Set(java.util.Set) Test(org.junit.Test) LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) MetricsConfiguration(org.hyperledger.besu.metrics.prometheus.MetricsConfiguration) Collectors(java.util.stream.Collectors) List(java.util.List) KeyValueStorage(org.hyperledger.besu.plugin.services.storage.KeyValueStorage) InMemoryKeyValueStorage(org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage) Optional(java.util.Optional) Transaction(org.hyperledger.besu.ethereum.core.Transaction) Collections(java.util.Collections) Hash(org.hyperledger.besu.datatypes.Hash) InMemoryKeyValueStorage(org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage) KeyValueStorage(org.hyperledger.besu.plugin.services.storage.KeyValueStorage) InMemoryKeyValueStorage(org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage) LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) TransactionReceipt(org.hyperledger.besu.ethereum.core.TransactionReceipt) Block(org.hyperledger.besu.ethereum.core.Block) BlockDataGenerator(org.hyperledger.besu.ethereum.core.BlockDataGenerator) Test(org.junit.Test)

Example 3 with LogWithMetadata

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

the class EthGetFilterLogs method response.

@Override
public JsonRpcResponse response(final JsonRpcRequestContext requestContext) {
    final String filterId = requestContext.getRequiredParameter(0, String.class);
    final List<LogWithMetadata> logs = filterManager.logs(filterId);
    if (logs != null) {
        return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), new LogsResult(logs));
    }
    return new JsonRpcErrorResponse(requestContext.getRequest().getId(), JsonRpcError.LOGS_FILTER_NOT_FOUND);
}
Also used : LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) LogsResult(org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.LogsResult) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Example 4 with LogWithMetadata

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

the class EthGetLogs method response.

@Override
public JsonRpcResponse response(final JsonRpcRequestContext requestContext) {
    final FilterParameter filter = requestContext.getRequiredParameter(0, FilterParameter.class);
    if (!filter.isValid()) {
        return new JsonRpcErrorResponse(requestContext.getRequest().getId(), JsonRpcError.INVALID_PARAMS);
    }
    final List<LogWithMetadata> matchingLogs = filter.getBlockHash().map(blockHash -> blockchain.matchingLogs(blockHash, filter.getLogsQuery(), requestContext::isAlive)).orElseGet(() -> {
        final long fromBlockNumber = filter.getFromBlock().getNumber().orElse(0L);
        final long toBlockNumber = filter.getToBlock().getNumber().orElse(blockchain.headBlockNumber());
        return blockchain.matchingLogs(fromBlockNumber, toBlockNumber, filter.getLogsQuery(), requestContext::isAlive);
    });
    return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), new LogsResult(matchingLogs));
}
Also used : LogsResult(org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.LogsResult) List(java.util.List) RpcMethod(org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) FilterParameter(org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) BlockchainQueries(org.hyperledger.besu.ethereum.api.query.BlockchainQueries) JsonRpcRequestContext(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) FilterParameter(org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter) LogsResult(org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.LogsResult) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Example 5 with LogWithMetadata

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

the class FilterManagerLogFilterTest method privateLogFilterShouldQueryPrivacyQueriesObject.

@Test
public void privateLogFilterShouldQueryPrivacyQueriesObject() {
    final LogWithMetadata logWithMetadata = logWithMetadata();
    final LogsQuery logsQuery = logsQuery();
    when(privacyQueries.matchingLogs(eq(PRIVACY_GROUP_ID), any(), eq(logsQuery))).thenReturn(singletonList(logWithMetadata));
    final String filterId = filterManager.installPrivateLogFilter(PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY, latest(), latest(), logsQuery);
    final Hash blockAddedHash = recordBlockEvents(1).get(0).getBlock().getHash();
    verify(privacyQueries).matchingLogs(eq(PRIVACY_GROUP_ID), eq(blockAddedHash), eq(logsQuery));
    assertThat(filterManager.logsChanges(filterId).get(0)).isEqualTo(logWithMetadata);
}
Also used : LogWithMetadata(org.hyperledger.besu.ethereum.core.LogWithMetadata) LogsQuery(org.hyperledger.besu.ethereum.api.query.LogsQuery) Hash(org.hyperledger.besu.datatypes.Hash) Test(org.junit.Test)

Aggregations

LogWithMetadata (org.hyperledger.besu.ethereum.core.LogWithMetadata)34 Test (org.junit.Test)22 Hash (org.hyperledger.besu.datatypes.Hash)18 List (java.util.List)12 ArrayList (java.util.ArrayList)11 JsonRpcSuccessResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse)10 LogsResult (org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.LogsResult)10 BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)9 Block (org.hyperledger.besu.ethereum.core.Block)8 Transaction (org.hyperledger.besu.ethereum.core.Transaction)8 TransactionReceipt (org.hyperledger.besu.ethereum.core.TransactionReceipt)8 BlockOptions (org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions)7 JsonRpcRequestContext (org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext)6 JsonRpcErrorResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)6 LogsQuery (org.hyperledger.besu.ethereum.api.query.LogsQuery)6 BlockDataGenerator (org.hyperledger.besu.ethereum.core.BlockDataGenerator)6 KeyValueStorage (org.hyperledger.besu.plugin.services.storage.KeyValueStorage)6 InMemoryKeyValueStorage (org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage)6 Optional (java.util.Optional)5 BlockchainQueries (org.hyperledger.besu.ethereum.api.query.BlockchainQueries)5