Upgrade Mockito (#6397)

Signed-off-by: Fabio Di Fabio <fabio.difabio@consensys.net>
pull/6411/head
Fabio Di Fabio 10 months ago committed by GitHub
parent 39d7042ca3
commit 724e3d040e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      CHANGELOG.md
  2. 4
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/handlers/HandlerFactory.java
  3. 23
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlock.java
  4. 64
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceHostAllowlistTest.java
  5. 62
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceLoginTest.java
  6. 129
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceRpcApisTest.java
  7. 86
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java
  8. 88
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTestBase.java
  9. 64
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsClientAuthTest.java
  10. 64
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsMisconfigurationTest.java
  11. 64
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsTest.java
  12. 28
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBlockToFileTest.java
  13. 45
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockTest.java
  14. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/backwardsync/BackwardSyncAlgSpec.java
  15. 13
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/netty/DeFramerTest.java
  16. 3
      evm/src/test/java/org/hyperledger/besu/evm/operations/ChainIdOperationTest.java
  17. 46
      gradle/verification-metadata.xml
  18. 2
      gradle/versions.gradle

@ -15,6 +15,7 @@
- Upgrade dependencies [#6377](https://github.com/hyperledger/besu/pull/6377) - Upgrade dependencies [#6377](https://github.com/hyperledger/besu/pull/6377)
- Upgrade `com.fasterxml.jackson` dependencies [#6378](https://github.com/hyperledger/besu/pull/6378) - Upgrade `com.fasterxml.jackson` dependencies [#6378](https://github.com/hyperledger/besu/pull/6378)
- Upgrade Guava dependency [#6396](https://github.com/hyperledger/besu/pull/6396) - Upgrade Guava dependency [#6396](https://github.com/hyperledger/besu/pull/6396)
- Upgrade Mockito [#6397](https://github.com/hyperledger/besu/pull/6397)
### Bug fixes ### Bug fixes
- INTERNAL_ERROR from `eth_estimateGas` JSON/RPC calls [#6344](https://github.com/hyperledger/besu/issues/6344) - INTERNAL_ERROR from `eth_estimateGas` JSON/RPC calls [#6344](https://github.com/hyperledger/besu/issues/6344)

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.Tracer;
@ -35,7 +36,8 @@ public class HandlerFactory {
assert methods != null && globalOptions != null; assert methods != null && globalOptions != null;
return TimeoutHandler.handler( return TimeoutHandler.handler(
Optional.of(globalOptions), Optional.of(globalOptions),
methods.keySet().stream().collect(Collectors.toMap(String::new, ignored -> globalOptions))); methods.keySet().stream()
.collect(Collectors.toMap(Function.identity(), ignored -> globalOptions)));
} }
public static Handler<RoutingContext> authentication( public static Handler<RoutingContext> authentication(

@ -46,15 +46,15 @@ public class DebugTraceBlock implements JsonRpcMethod {
private static final Logger LOG = LoggerFactory.getLogger(DebugTraceBlock.class); private static final Logger LOG = LoggerFactory.getLogger(DebugTraceBlock.class);
private final Supplier<BlockTracer> blockTracerSupplier; private final Supplier<BlockTracer> blockTracerSupplier;
private final BlockHeaderFunctions blockHeaderFunctions; private final BlockHeaderFunctions blockHeaderFunctions;
private final BlockchainQueries blockchain; private final BlockchainQueries blockchainQueries;
public DebugTraceBlock( public DebugTraceBlock(
final Supplier<BlockTracer> blockTracerSupplier, final Supplier<BlockTracer> blockTracerSupplier,
final BlockHeaderFunctions blockHeaderFunctions, final BlockHeaderFunctions blockHeaderFunctions,
final BlockchainQueries blockchain) { final BlockchainQueries blockchainQueries) {
this.blockTracerSupplier = blockTracerSupplier; this.blockTracerSupplier = blockTracerSupplier;
this.blockHeaderFunctions = blockHeaderFunctions; this.blockHeaderFunctions = blockHeaderFunctions;
this.blockchain = blockchain; this.blockchainQueries = blockchainQueries;
} }
@Override @Override
@ -79,18 +79,17 @@ public class DebugTraceBlock implements JsonRpcMethod {
.map(TransactionTraceParams::traceOptions) .map(TransactionTraceParams::traceOptions)
.orElse(TraceOptions.DEFAULT); .orElse(TraceOptions.DEFAULT);
if (this.blockchain.blockByHash(block.getHeader().getParentHash()).isPresent()) { if (this.blockchainQueries.blockByHash(block.getHeader().getParentHash()).isPresent()) {
final Collection<DebugTraceTransactionResult> results = final Collection<DebugTraceTransactionResult> results =
Tracer.processTracing( Tracer.processTracing(
blockchain, blockchainQueries,
Optional.of(block.getHeader()), Optional.of(block.getHeader()),
mutableWorldState -> { mutableWorldState ->
return blockTracerSupplier blockTracerSupplier
.get() .get()
.trace(mutableWorldState, block, new DebugOperationTracer(traceOptions)) .trace(mutableWorldState, block, new DebugOperationTracer(traceOptions))
.map(BlockTrace::getTransactionTraces) .map(BlockTrace::getTransactionTraces)
.map(DebugTraceTransactionResult::of); .map(DebugTraceTransactionResult::of))
})
.orElse(null); .orElse(null);
return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), results); return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), results);
} else { } else {

@ -17,7 +17,6 @@ package org.hyperledger.besu.ethereum.api.jsonrpc;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.DEFAULT_RPC_APIS; import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.DEFAULT_RPC_APIS;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
@ -98,38 +97,37 @@ public class JsonRpcHttpServiceHostAllowlistTest {
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
rpcMethods = rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, CHAIN_ID,
CHAIN_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), peerDiscoveryMock,
peerDiscoveryMock, blockchainQueries,
blockchainQueries, synchronizer,
synchronizer, MainnetProtocolSchedule.fromConfig(
MainnetProtocolSchedule.fromConfig( new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)),
new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)), mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), DEFAULT_RPC_APIS,
DEFAULT_RPC_APIS, mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, new HashMap<>(),
new HashMap<>(), folder,
folder, mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
service = createJsonRpcHttpService(); service = createJsonRpcHttpService();
service.start().join(); service.start().join();

@ -19,7 +19,6 @@ import static java.util.concurrent.TimeUnit.MINUTES;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.list; import static org.assertj.core.util.Lists.list;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
@ -129,37 +128,36 @@ public class JsonRpcHttpServiceLoginTest {
new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID); new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID);
rpcMethods = rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, CHAIN_ID,
CHAIN_ID, genesisConfigOptions,
genesisConfigOptions, peerDiscoveryMock,
peerDiscoveryMock, blockchainQueries,
blockchainQueries, synchronizer,
synchronizer, MainnetProtocolSchedule.fromConfig(genesisConfigOptions),
MainnetProtocolSchedule.fromConfig(genesisConfigOptions), mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.empty(),
Optional.empty(), Optional.empty(),
Optional.empty(), JSON_RPC_APIS,
JSON_RPC_APIS, mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, new HashMap<>(),
new HashMap<>(), folder,
folder, mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
service = createJsonRpcHttpService(); service = createJsonRpcHttpService();
jwtAuth = service.authenticationService.get().getJwtAuthProvider(); jwtAuth = service.authenticationService.get().getJwtAuthProvider();
service.start().join(); service.start().join();

@ -17,7 +17,6 @@ package org.hyperledger.besu.ethereum.api.jsonrpc;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
@ -201,37 +200,36 @@ public class JsonRpcHttpServiceRpcApisTest {
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
final Map<String, JsonRpcMethod> rpcMethods = final Map<String, JsonRpcMethod> rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, NETWORK_ID,
NETWORK_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), mock(P2PNetwork.class),
mock(P2PNetwork.class), blockchainQueries,
blockchainQueries, mock(Synchronizer.class),
mock(Synchronizer.class), ProtocolScheduleFixture.MAINNET,
ProtocolScheduleFixture.MAINNET, mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), config.getRpcApis(),
config.getRpcApis(), mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, new HashMap<>(),
new HashMap<>(), folder,
folder, mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
final JsonRpcHttpService jsonRpcHttpService = final JsonRpcHttpService jsonRpcHttpService =
new JsonRpcHttpService( new JsonRpcHttpService(
vertx, vertx,
@ -302,8 +300,7 @@ public class JsonRpcHttpServiceRpcApisTest {
final WebSocketConfiguration webSocketConfiguration, final WebSocketConfiguration webSocketConfiguration,
final P2PNetwork p2pNetwork, final P2PNetwork p2pNetwork,
final MetricsConfiguration metricsConfiguration, final MetricsConfiguration metricsConfiguration,
final NatService natService) final NatService natService) {
throws Exception {
final Set<Capability> supportedCapabilities = new HashSet<>(); final Set<Capability> supportedCapabilities = new HashSet<>();
supportedCapabilities.add(EthProtocol.ETH62); supportedCapabilities.add(EthProtocol.ETH62);
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
@ -311,37 +308,36 @@ public class JsonRpcHttpServiceRpcApisTest {
webSocketConfiguration.setPort(0); webSocketConfiguration.setPort(0);
final Map<String, JsonRpcMethod> rpcMethods = final Map<String, JsonRpcMethod> rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, NETWORK_ID,
NETWORK_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), p2pNetwork,
p2pNetwork, blockchainQueries,
blockchainQueries, mock(Synchronizer.class),
mock(Synchronizer.class), ProtocolScheduleFixture.MAINNET,
ProtocolScheduleFixture.MAINNET, mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), jsonRpcConfiguration.getRpcApis(),
jsonRpcConfiguration.getRpcApis(), mock(PrivacyParameters.class),
mock(PrivacyParameters.class), jsonRpcConfiguration,
jsonRpcConfiguration, webSocketConfiguration,
webSocketConfiguration, metricsConfiguration,
metricsConfiguration, natService,
natService, new HashMap<>(),
new HashMap<>(), folder,
folder, mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
final JsonRpcHttpService jsonRpcHttpService = final JsonRpcHttpService jsonRpcHttpService =
new JsonRpcHttpService( new JsonRpcHttpService(
vertx, vertx,
@ -425,8 +421,7 @@ public class JsonRpcHttpServiceRpcApisTest {
"{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"net_services\"}", JSON); "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"net_services\"}", JSON);
} }
public JsonRpcHttpService getJsonRpcHttpService(final boolean[] enabledNetServices) public JsonRpcHttpService getJsonRpcHttpService(final boolean[] enabledNetServices) {
throws Exception {
JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault(); JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault();
WebSocketConfiguration webSocketConfiguration = WebSocketConfiguration.createDefault(); WebSocketConfiguration webSocketConfiguration = WebSocketConfiguration.createDefault();

@ -17,10 +17,7 @@ package org.hyperledger.besu.ethereum.api.jsonrpc;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
@ -1389,65 +1386,68 @@ public class JsonRpcHttpServiceTest extends JsonRpcHttpServiceTestBase {
+ "\"}", + "\"}",
JSON); JSON);
when(rpcMethods.get(any(String.class))).thenReturn(null); try (var unused = disableRpcMethod(methodName)) {
when(rpcMethods.containsKey(any(String.class))).thenReturn(false);
try (final Response resp = client.newCall(buildPostRequest(body)).execute()) { try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
assertThat(resp.code()).isEqualTo(200); assertThat(resp.code()).isEqualTo(200);
final JsonObject json = new JsonObject(resp.body().string()); final JsonObject json = new JsonObject(resp.body().string());
final RpcErrorType expectedError = RpcErrorType.METHOD_NOT_ENABLED; final RpcErrorType expectedError = RpcErrorType.METHOD_NOT_ENABLED;
testHelper.assertValidJsonRpcError( testHelper.assertValidJsonRpcError(
json, id, expectedError.getCode(), expectedError.getMessage()); json, id, expectedError.getCode(), expectedError.getMessage());
}
} }
verify(rpcMethods).containsKey(methodName);
verify(rpcMethods).get(methodName);
reset(rpcMethods);
} }
@Test @Test
public void exceptionallyHandleJsonSingleRequest() throws Exception { public void exceptionallyHandleJsonSingleRequest() throws Exception {
final String methodName = "foo";
final JsonRpcMethod jsonRpcMethod = mock(JsonRpcMethod.class); final JsonRpcMethod jsonRpcMethod = mock(JsonRpcMethod.class);
when(jsonRpcMethod.getName()).thenReturn("foo"); when(jsonRpcMethod.getName()).thenReturn(methodName);
when(jsonRpcMethod.response(any())).thenThrow(new RuntimeException("test exception")); when(jsonRpcMethod.response(any())).thenThrow(new RuntimeException("test exception"));
doReturn(jsonRpcMethod).when(rpcMethods).get("foo"); try (var unused = addRpcMethod(methodName, jsonRpcMethod)) {
final RequestBody body = final RequestBody body =
RequestBody.create("{\"jsonrpc\":\"2.0\",\"id\":\"666\",\"method\":\"foo\"}", JSON); RequestBody.create(
"{\"jsonrpc\":\"2.0\",\"id\":\"666\",\"method\":\"" + methodName + "\"}", JSON);
try (final Response resp = client.newCall(buildPostRequest(body)).execute()) { try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
assertThat(resp.code()).isEqualTo(200); assertThat(resp.code()).isEqualTo(200);
final JsonObject json = new JsonObject(resp.body().string()); final JsonObject json = new JsonObject(resp.body().string());
final RpcErrorType expectedError = RpcErrorType.INTERNAL_ERROR; final RpcErrorType expectedError = RpcErrorType.INTERNAL_ERROR;
testHelper.assertValidJsonRpcError( testHelper.assertValidJsonRpcError(
json, "666", expectedError.getCode(), expectedError.getMessage()); json, "666", expectedError.getCode(), expectedError.getMessage());
}
} }
} }
@Test @Test
public void exceptionallyHandleJsonBatchRequest() throws Exception { public void exceptionallyHandleJsonBatchRequest() throws Exception {
final String methodName = "foo";
final JsonRpcMethod jsonRpcMethod = mock(JsonRpcMethod.class); final JsonRpcMethod jsonRpcMethod = mock(JsonRpcMethod.class);
when(jsonRpcMethod.getName()).thenReturn("foo"); when(jsonRpcMethod.getName()).thenReturn(methodName);
when(jsonRpcMethod.response(any())).thenThrow(new RuntimeException("test exception")); when(jsonRpcMethod.response(any())).thenThrow(new RuntimeException("test exception"));
doReturn(jsonRpcMethod).when(rpcMethods).get("foo");
final RequestBody body = try (var unused = addRpcMethod(methodName, jsonRpcMethod)) {
RequestBody.create(
"[{\"jsonrpc\":\"2.0\",\"id\":\"000\",\"method\":\"web3_clientVersion\"}," final RequestBody body =
+ "{\"jsonrpc\":\"2.0\",\"id\":\"111\",\"method\":\"foo\"}," RequestBody.create(
+ "{\"jsonrpc\":\"2.0\",\"id\":\"222\",\"method\":\"net_version\"}]", "[{\"jsonrpc\":\"2.0\",\"id\":\"000\",\"method\":\"web3_clientVersion\"},"
JSON); + "{\"jsonrpc\":\"2.0\",\"id\":\"111\",\"method\":\""
+ methodName
try (final Response resp = client.newCall(buildPostRequest(body)).execute()) { + "\"},"
assertThat(resp.code()).isEqualTo(200); + "{\"jsonrpc\":\"2.0\",\"id\":\"222\",\"method\":\"net_version\"}]",
final JsonArray array = new JsonArray(resp.body().string()); JSON);
testHelper.assertValidJsonRpcResult(array.getJsonObject(0), "000");
final RpcErrorType expectedError = RpcErrorType.INTERNAL_ERROR; try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
testHelper.assertValidJsonRpcError( assertThat(resp.code()).isEqualTo(200);
array.getJsonObject(1), "111", expectedError.getCode(), expectedError.getMessage()); final JsonArray array = new JsonArray(resp.body().string());
testHelper.assertValidJsonRpcResult(array.getJsonObject(2), "222"); testHelper.assertValidJsonRpcResult(array.getJsonObject(0), "000");
final RpcErrorType expectedError = RpcErrorType.INTERNAL_ERROR;
testHelper.assertValidJsonRpcError(
array.getJsonObject(1), "111", expectedError.getCode(), expectedError.getMessage());
testHelper.assertValidJsonRpcResult(array.getJsonObject(2), "222");
}
} }
} }

@ -16,7 +16,6 @@
package org.hyperledger.besu.ethereum.api.jsonrpc; package org.hyperledger.besu.ethereum.api.jsonrpc;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
@ -72,8 +71,9 @@ public class JsonRpcHttpServiceTestBase {
protected final JsonRpcTestHelper testHelper = new JsonRpcTestHelper(); protected final JsonRpcTestHelper testHelper = new JsonRpcTestHelper();
private static final Vertx vertx = Vertx.vertx(); private static final Vertx vertx = Vertx.vertx();
protected static Map<String, JsonRpcMethod> rpcMethods; protected static Map<String, JsonRpcMethod> rpcMethods;
private static Map<String, JsonRpcMethod> disabledRpcMethods;
private static Set<String> addedRpcMethods;
protected static JsonRpcHttpService service; protected static JsonRpcHttpService service;
protected static OkHttpClient client; protected static OkHttpClient client;
protected static String baseUrl; protected static String baseUrl;
@ -106,39 +106,41 @@ public class JsonRpcHttpServiceTestBase {
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
rpcMethods = rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, CHAIN_ID,
CHAIN_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), peerDiscoveryMock,
peerDiscoveryMock, blockchainQueries,
blockchainQueries, synchronizer,
synchronizer, MainnetProtocolSchedule.fromConfig(
MainnetProtocolSchedule.fromConfig( new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID),
new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID), EvmConfiguration.DEFAULT),
EvmConfiguration.DEFAULT), mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), JSON_RPC_APIS,
JSON_RPC_APIS, mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, new HashMap<>(),
new HashMap<>(), folder,
folder, ethPeersMock,
ethPeersMock, vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty())); disabledRpcMethods = new HashMap<>();
addedRpcMethods = new HashSet<>();
service = createJsonRpcHttpService(createLimitedJsonRpcConfig()); service = createJsonRpcHttpService(createLimitedJsonRpcConfig());
service.start().join(); service.start().join();
@ -189,6 +191,22 @@ public class JsonRpcHttpServiceTestBase {
return new Request.Builder().get().url(baseUrl + path).build(); return new Request.Builder().get().url(baseUrl + path).build();
} }
protected AutoCloseable disableRpcMethod(final String methodName) {
disabledRpcMethods.put(methodName, rpcMethods.remove(methodName));
return () -> resetRpcMethods();
}
protected AutoCloseable addRpcMethod(final String methodName, final JsonRpcMethod method) {
rpcMethods.put(methodName, method);
addedRpcMethods.add(methodName);
return () -> resetRpcMethods();
}
protected void resetRpcMethods() {
disabledRpcMethods.forEach(rpcMethods::put);
addedRpcMethods.forEach(rpcMethods::remove);
}
/** Tears down the HTTP server. */ /** Tears down the HTTP server. */
@AfterAll @AfterAll
public static void shutdownServer() { public static void shutdownServer() {

@ -21,7 +21,6 @@ import static org.hyperledger.besu.ethereum.api.tls.KnownClientFileUtil.writeToK
import static org.hyperledger.besu.ethereum.api.tls.TlsClientAuthConfiguration.Builder.aTlsClientAuthConfiguration; import static org.hyperledger.besu.ethereum.api.tls.TlsClientAuthConfiguration.Builder.aTlsClientAuthConfiguration;
import static org.hyperledger.besu.ethereum.api.tls.TlsConfiguration.Builder.aTlsConfiguration; import static org.hyperledger.besu.ethereum.api.tls.TlsConfiguration.Builder.aTlsConfiguration;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
@ -112,38 +111,37 @@ public class JsonRpcHttpServiceTlsClientAuthTest {
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
rpcMethods = rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, CHAIN_ID,
CHAIN_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), peerDiscoveryMock,
peerDiscoveryMock, blockchainQueries,
blockchainQueries, synchronizer,
synchronizer, MainnetProtocolSchedule.fromConfig(
MainnetProtocolSchedule.fromConfig( new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)),
new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)), mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), DEFAULT_RPC_APIS,
DEFAULT_RPC_APIS, mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, Collections.emptyMap(),
Collections.emptyMap(), folder,
folder, mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
System.setProperty("javax.net.ssl.trustStore", CLIENT_AS_CA_CERT.getKeyStoreFile().toString()); System.setProperty("javax.net.ssl.trustStore", CLIENT_AS_CA_CERT.getKeyStoreFile().toString());
System.setProperty( System.setProperty(

@ -20,7 +20,6 @@ import static org.hyperledger.besu.ethereum.api.tls.KnownClientFileUtil.writeToK
import static org.hyperledger.besu.ethereum.api.tls.TlsClientAuthConfiguration.Builder.aTlsClientAuthConfiguration; import static org.hyperledger.besu.ethereum.api.tls.TlsClientAuthConfiguration.Builder.aTlsClientAuthConfiguration;
import static org.hyperledger.besu.ethereum.api.tls.TlsConfiguration.Builder.aTlsConfiguration; import static org.hyperledger.besu.ethereum.api.tls.TlsConfiguration.Builder.aTlsConfiguration;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
@ -100,38 +99,37 @@ class JsonRpcHttpServiceTlsMisconfigurationTest {
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
rpcMethods = rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, CHAIN_ID,
CHAIN_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), peerDiscoveryMock,
peerDiscoveryMock, blockchainQueries,
blockchainQueries, synchronizer,
synchronizer, MainnetProtocolSchedule.fromConfig(
MainnetProtocolSchedule.fromConfig( new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)),
new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)), mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), DEFAULT_RPC_APIS,
DEFAULT_RPC_APIS, mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, Collections.emptyMap(),
Collections.emptyMap(), tempDir.getRoot(),
tempDir.getRoot(), mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
} }
@AfterEach @AfterEach

@ -20,7 +20,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.DEFAULT_RPC_APIS; import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.DEFAULT_RPC_APIS;
import static org.hyperledger.besu.ethereum.api.tls.TlsConfiguration.Builder.aTlsConfiguration; import static org.hyperledger.besu.ethereum.api.tls.TlsConfiguration.Builder.aTlsConfiguration;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.config.StubGenesisConfigOptions;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
@ -101,38 +100,37 @@ public class JsonRpcHttpServiceTlsTest {
supportedCapabilities.add(EthProtocol.ETH63); supportedCapabilities.add(EthProtocol.ETH63);
rpcMethods = rpcMethods =
spy( new JsonRpcMethodsFactory()
new JsonRpcMethodsFactory() .methods(
.methods( CLIENT_VERSION,
CLIENT_VERSION, CHAIN_ID,
CHAIN_ID, new StubGenesisConfigOptions(),
new StubGenesisConfigOptions(), peerDiscoveryMock,
peerDiscoveryMock, blockchainQueries,
blockchainQueries, synchronizer,
synchronizer, MainnetProtocolSchedule.fromConfig(
MainnetProtocolSchedule.fromConfig( new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)),
new StubGenesisConfigOptions().constantinopleBlock(0).chainId(CHAIN_ID)), mock(ProtocolContext.class),
mock(ProtocolContext.class), mock(FilterManager.class),
mock(FilterManager.class), mock(TransactionPool.class),
mock(TransactionPool.class), mock(MiningParameters.class),
mock(MiningParameters.class), mock(PoWMiningCoordinator.class),
mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(),
new NoOpMetricsSystem(), supportedCapabilities,
supportedCapabilities, Optional.of(mock(AccountLocalConfigPermissioningController.class)),
Optional.of(mock(AccountLocalConfigPermissioningController.class)), Optional.of(mock(NodeLocalConfigPermissioningController.class)),
Optional.of(mock(NodeLocalConfigPermissioningController.class)), DEFAULT_RPC_APIS,
DEFAULT_RPC_APIS, mock(PrivacyParameters.class),
mock(PrivacyParameters.class), mock(JsonRpcConfiguration.class),
mock(JsonRpcConfiguration.class), mock(WebSocketConfiguration.class),
mock(WebSocketConfiguration.class), mock(MetricsConfiguration.class),
mock(MetricsConfiguration.class), natService,
natService, Collections.emptyMap(),
Collections.emptyMap(), folder,
folder, mock(EthPeers.class),
mock(EthPeers.class), vertx,
vertx, mock(ApiConfiguration.class),
mock(ApiConfiguration.class), Optional.empty());
Optional.empty()));
service = createJsonRpcHttpService(createJsonRpcConfig()); service = createJsonRpcHttpService(createJsonRpcConfig());
service.start().join(); service.start().join();
baseUrl = service.url(); baseUrl = service.url();

@ -18,11 +18,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTracer;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
@ -30,28 +31,23 @@ import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
public class DebugStandardTraceBlockToFileTest { public class DebugStandardTraceBlockToFileTest {
// this tempDir is deliberately static // this tempDir is deliberately static
@TempDir private static Path folder; @TempDir private static Path folder;
private final WorldStateArchive archive =
mock(WorldStateArchive.class, Answers.RETURNS_DEEP_STUBS);
private final Blockchain blockchain = mock(Blockchain.class); private final Blockchain blockchain = mock(Blockchain.class);
private final BlockchainQueries blockchainQueries = private final BlockchainQueries blockchainQueries = mock(BlockchainQueries.class);
spy(new BlockchainQueries(blockchain, archive));
private final TransactionTracer transactionTracer = mock(TransactionTracer.class); private final TransactionTracer transactionTracer = mock(TransactionTracer.class);
private final DebugStandardTraceBlockToFile debugStandardTraceBlockToFile = private final DebugStandardTraceBlockToFile debugStandardTraceBlockToFile =
new DebugStandardTraceBlockToFile(() -> transactionTracer, blockchainQueries, folder); new DebugStandardTraceBlockToFile(() -> transactionTracer, blockchainQueries, folder);
@ -76,20 +72,26 @@ public class DebugStandardTraceBlockToFileTest {
new JsonRpcRequestContext( new JsonRpcRequestContext(
new JsonRpcRequest("2.0", "debug_standardTraceBlockToFile", params)); new JsonRpcRequest("2.0", "debug_standardTraceBlockToFile", params));
final List<String> paths = new ArrayList<>(); final List<String> paths = List.of("path-1");
paths.add("path-1");
when(blockchainQueries.getBlockchain()).thenReturn(blockchain);
when(blockchain.getBlockByHash(block.getHash())).thenReturn(Optional.of(block)); when(blockchain.getBlockByHash(block.getHash())).thenReturn(Optional.of(block));
when(blockchain.getBlockHeader(genesis.getHash())).thenReturn(Optional.of(genesis.getHeader())); when(blockchain.getBlockHeader(genesis.getHash())).thenReturn(Optional.of(genesis.getHeader()));
when(blockchainQueries.getBlockchain()).thenReturn(blockchain);
when(blockchainQueries.getAndMapWorldState(any(), any()))
.thenAnswer(
invocationOnMock -> {
Function<Tracer.TraceableState, ? extends Optional<BlockTracer>> mapper =
invocationOnMock.getArgument(1);
return mapper.apply(mock(Tracer.TraceableState.class));
});
when(transactionTracer.traceTransactionToFile( when(transactionTracer.traceTransactionToFile(
any(MutableWorldState.class), eq(block.getHash()), any(), any())) any(MutableWorldState.class), eq(block.getHash()), any(), any()))
.thenReturn(paths); .thenReturn(paths);
final JsonRpcSuccessResponse response = final JsonRpcSuccessResponse response =
(JsonRpcSuccessResponse) debugStandardTraceBlockToFile.response(request); (JsonRpcSuccessResponse) debugStandardTraceBlockToFile.response(request);
final List result = (ArrayList) response.getResult(); final List result = (List) response.getResult();
assertThat(result.size()).isEqualTo(1); assertThat(result.size()).isEqualTo(1);
} }

@ -18,9 +18,8 @@ import static java.util.Arrays.asList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
@ -35,32 +34,25 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSucces
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType;
import org.hyperledger.besu.ethereum.api.query.BlockWithMetadata; import org.hyperledger.besu.ethereum.api.query.BlockWithMetadata;
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.debug.TraceFrame; import org.hyperledger.besu.ethereum.debug.TraceFrame;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions;
import org.hyperledger.besu.ethereum.processing.TransactionProcessingResult; import org.hyperledger.besu.ethereum.processing.TransactionProcessingResult;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalLong; import java.util.OptionalLong;
import java.util.function.Function;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.Mockito;
public class DebugTraceBlockTest { public class DebugTraceBlockTest {
private final BlockTracer blockTracer = mock(BlockTracer.class); private final BlockTracer blockTracer = mock(BlockTracer.class);
private final WorldStateArchive archive = private final BlockchainQueries blockchainQueries = mock(BlockchainQueries.class);
mock(WorldStateArchive.class, Answers.RETURNS_DEEP_STUBS);
private final Blockchain blockchain = mock(Blockchain.class);
private final BlockchainQueries blockchainQueries =
spy(new BlockchainQueries(blockchain, archive));
private final DebugTraceBlock debugTraceBlock = private final DebugTraceBlock debugTraceBlock =
new DebugTraceBlock(() -> blockTracer, new MainnetBlockHeaderFunctions(), blockchainQueries); new DebugTraceBlock(() -> blockTracer, new MainnetBlockHeaderFunctions(), blockchainQueries);
@ -127,22 +119,25 @@ public class DebugTraceBlockTest {
when(transaction2Trace.getResult()).thenReturn(transaction2Result); when(transaction2Trace.getResult()).thenReturn(transaction2Result);
when(transaction1Result.getOutput()).thenReturn(Bytes.fromHexString("1234")); when(transaction1Result.getOutput()).thenReturn(Bytes.fromHexString("1234"));
when(transaction2Result.getOutput()).thenReturn(Bytes.fromHexString("1234")); when(transaction2Result.getOutput()).thenReturn(Bytes.fromHexString("1234"));
when(blockTracer.trace(any(Tracer.TraceableState.class), Mockito.eq(block), any())) when(blockTracer.trace(any(Tracer.TraceableState.class), eq(block), any()))
.thenReturn(Optional.of(blockTrace)); .thenReturn(Optional.of(blockTrace));
when(blockchain.getBlockHeader(parentBlock.getHash())) when(blockchainQueries.blockByHash(parentBlock.getHash()))
.thenReturn(Optional.of(parentBlock.getHeader())); .thenReturn(
doAnswer( Optional.of(
invocation -> new BlockWithMetadata<>(
Optional.of( parentBlock.getHeader(),
new BlockWithMetadata<>( Collections.emptyList(),
parentBlock.getHeader(), Collections.emptyList(),
Collections.emptyList(), parentBlock.getHeader().getDifficulty(),
Collections.emptyList(), parentBlock.calculateSize())));
parentBlock.getHeader().getDifficulty(), when(blockchainQueries.getAndMapWorldState(eq(parentBlock.getHash()), any()))
parentBlock.calculateSize()))) .thenAnswer(
.when(blockchainQueries) invocationOnMock -> {
.blockByHash(parentBlock.getHash()); Function<Tracer.TraceableState, ? extends Optional<BlockTracer>> mapper =
invocationOnMock.getArgument(1);
return mapper.apply(mock(Tracer.TraceableState.class));
});
final JsonRpcSuccessResponse response = final JsonRpcSuccessResponse response =
(JsonRpcSuccessResponse) debugTraceBlock.response(request); (JsonRpcSuccessResponse) debugTraceBlock.response(request);

@ -165,7 +165,7 @@ public class BackwardSyncAlgSpec {
ttdCaptor.getValue().onTTDReached(true); ttdCaptor.getValue().onTTDReached(true);
voidCompletableFuture.get(100, TimeUnit.MILLISECONDS); voidCompletableFuture.get(200, TimeUnit.MILLISECONDS);
assertThat(voidCompletableFuture).isCompleted(); assertThat(voidCompletableFuture).isCompleted();
verify(context.getSyncState()).unsubscribeTTDReached(88L); verify(context.getSyncState()).unsubscribeTTDReached(88L);
@ -192,7 +192,7 @@ public class BackwardSyncAlgSpec {
completionCaptor.getValue().onInitialSyncCompleted(); completionCaptor.getValue().onInitialSyncCompleted();
voidCompletableFuture.get(100, TimeUnit.MILLISECONDS); voidCompletableFuture.get(200, TimeUnit.MILLISECONDS);
assertThat(voidCompletableFuture).isCompleted(); assertThat(voidCompletableFuture).isCompleted();
verify(context.getSyncState()).unsubscribeTTDReached(88L); verify(context.getSyncState()).unsubscribeTTDReached(88L);

@ -65,6 +65,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId; import io.netty.channel.ChannelId;
import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPipeline;
@ -196,7 +197,7 @@ public class DeFramerTest {
assertThat(out).isEmpty(); assertThat(out).isEmpty();
// Next phase of pipeline should be setup // Next phase of pipeline should be setup
verify(pipeline, times(1)).addLast(any()); verify(pipeline, times(1)).addLast(any(ChannelHandler[].class));
// Next message should be pushed out // Next message should be pushed out
final PingMessage nextMessage = PingMessage.get(); final PingMessage nextMessage = PingMessage.get();
@ -204,7 +205,7 @@ public class DeFramerTest {
when(framer.deframe(eq(nextData))) when(framer.deframe(eq(nextData)))
.thenReturn(new RawMessage(nextMessage.getCode(), nextMessage.getData())) .thenReturn(new RawMessage(nextMessage.getCode(), nextMessage.getData()))
.thenReturn(null); .thenReturn(null);
verify(pipeline, times(1)).addLast(any()); verify(pipeline, times(1)).addLast(any(ChannelHandler[].class));
deFramer.decode(ctx, nextData, out); deFramer.decode(ctx, nextData, out);
assertThat(out.size()).isEqualTo(1); assertThat(out.size()).isEqualTo(1);
} }
@ -246,7 +247,7 @@ public class DeFramerTest {
assertThat(peerConnection.getPeer().getEnodeURL()).isEqualTo(expectedEnode); assertThat(peerConnection.getPeer().getEnodeURL()).isEqualTo(expectedEnode);
// Next phase of pipeline should be setup // Next phase of pipeline should be setup
verify(pipeline, times(1)).addLast(any()); verify(pipeline, times(1)).addLast(any(ChannelHandler[].class));
// Next message should be pushed out // Next message should be pushed out
final PingMessage nextMessage = PingMessage.get(); final PingMessage nextMessage = PingMessage.get();
@ -254,7 +255,7 @@ public class DeFramerTest {
when(framer.deframe(eq(nextData))) when(framer.deframe(eq(nextData)))
.thenReturn(new RawMessage(nextMessage.getCode(), nextMessage.getData())) .thenReturn(new RawMessage(nextMessage.getCode(), nextMessage.getData()))
.thenReturn(null); .thenReturn(null);
verify(pipeline, times(1)).addLast(any()); verify(pipeline, times(1)).addLast(any(ChannelHandler[].class));
deFramer.decode(ctx, nextData, out); deFramer.decode(ctx, nextData, out);
assertThat(out.size()).isEqualTo(1); assertThat(out.size()).isEqualTo(1);
} }
@ -292,7 +293,7 @@ public class DeFramerTest {
assertThat(out).isEmpty(); assertThat(out).isEmpty();
// Next phase of pipeline should be setup // Next phase of pipeline should be setup
verify(pipeline, times(1)).addLast(any()); verify(pipeline, times(1)).addLast(any(ChannelHandler[].class));
} }
@Test @Test
@ -321,7 +322,7 @@ public class DeFramerTest {
assertThat(out).isEmpty(); assertThat(out).isEmpty();
// Next phase of pipeline should be setup // Next phase of pipeline should be setup
verify(pipeline, times(1)).addLast(any()); verify(pipeline, times(1)).addLast(any(ChannelHandler[].class));
} }
@Test @Test

@ -27,7 +27,6 @@ import java.util.List;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.MethodSource;
@ -51,7 +50,7 @@ class ChainIdOperationTest {
void shouldReturnChainId(final String chainIdString, final int expectedGas) { void shouldReturnChainId(final String chainIdString, final int expectedGas) {
Bytes32 chainId = Bytes32.fromHexString(chainIdString); Bytes32 chainId = Bytes32.fromHexString(chainIdString);
ChainIdOperation operation = new ChainIdOperation(new ConstantinopleGasCalculator(), chainId); ChainIdOperation operation = new ChainIdOperation(new ConstantinopleGasCalculator(), chainId);
final ArgumentCaptor<Bytes> arg = ArgumentCaptor.forClass(UInt256.class); final ArgumentCaptor<Bytes> arg = ArgumentCaptor.forClass(Bytes.class);
when(messageFrame.getRemainingGas()).thenReturn(100L); when(messageFrame.getRemainingGas()).thenReturn(100L);
operation.execute(messageFrame, null); operation.execute(messageFrame, null);
Mockito.verify(messageFrame).getRemainingGas(); Mockito.verify(messageFrame).getRemainingGas();

@ -2858,12 +2858,12 @@
<sha256 value="57e0c23ac60945aefb5a0c4a9339bea68a295364ca47c7a9079a032f79013abb" origin="Generated by Gradle"/> <sha256 value="57e0c23ac60945aefb5a0c4a9339bea68a295364ca47c7a9079a032f79013abb" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="net.bytebuddy" name="byte-buddy" version="1.12.19"> <component group="net.bytebuddy" name="byte-buddy" version="1.14.10">
<artifact name="byte-buddy-1.12.19.jar"> <artifact name="byte-buddy-1.14.10.jar">
<sha256 value="030704139e46f32c38d27060edee9e0676b0a0fff8a8be53461515154ba8a7be" origin="Generated by Gradle"/> <sha256 value="30e6e0446437a67db37e2b7f7d33f50787ddfd970359319dfd05469daa2dcbce" origin="Generated by Gradle"/>
</artifact> </artifact>
<artifact name="byte-buddy-1.12.19.pom"> <artifact name="byte-buddy-1.14.10.pom">
<sha256 value="435fb8664aa9b7e120c8dd6c707d4eafa642fa262dff6d5e3f71dc25c69e89eb" origin="Generated by Gradle"/> <sha256 value="cd58782845ff8eedf2ed83a0c3edf45eeeb99e14c05af8a2e901860ea080ceaf" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="net.bytebuddy" name="byte-buddy" version="1.14.11"> <component group="net.bytebuddy" name="byte-buddy" version="1.14.11">
@ -2874,17 +2874,17 @@
<sha256 value="358449d6c73538584508dd8ae6cfde56baf4a34b767b71d9cc4644f0f1f4211a" origin="Generated by Gradle"/> <sha256 value="358449d6c73538584508dd8ae6cfde56baf4a34b767b71d9cc4644f0f1f4211a" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="net.bytebuddy" name="byte-buddy-agent" version="1.12.19"> <component group="net.bytebuddy" name="byte-buddy-agent" version="1.14.10">
<artifact name="byte-buddy-agent-1.12.19.jar"> <artifact name="byte-buddy-agent-1.14.10.jar">
<sha256 value="3a70240de7cdcde04e7c504c2327d7035b9c25ae0206881e3bf4e6798a273ed8" origin="Generated by Gradle"/> <sha256 value="67993a89d47ca58ff868802a4448ddd150e5fe4e5a5645ded990d7b4d557a6b9" origin="Generated by Gradle"/>
</artifact> </artifact>
<artifact name="byte-buddy-agent-1.12.19.pom"> <artifact name="byte-buddy-agent-1.14.10.pom">
<sha256 value="b5a2cff643681de1687fc40acd251feefdfca23e673e049fb3c3692b53526d4b" origin="Generated by Gradle"/> <sha256 value="53bc97e9c6bf7c2d0e5f9cbac7d5de6b2924d916cf4b817e6a3a35929c796b4a" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="net.bytebuddy" name="byte-buddy-parent" version="1.12.19"> <component group="net.bytebuddy" name="byte-buddy-parent" version="1.14.10">
<artifact name="byte-buddy-parent-1.12.19.pom"> <artifact name="byte-buddy-parent-1.14.10.pom">
<sha256 value="72ab6fef409e812921f4728b3c4b6ef4fa53bc25fabb0488fc2cae367368b54d" origin="Generated by Gradle"/> <sha256 value="c698219060fb0e565a0f2c96094e92b20efe146fd61636b2c9e4c03bd9ba4a7b" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="net.bytebuddy" name="byte-buddy-parent" version="1.14.11"> <component group="net.bytebuddy" name="byte-buddy-parent" version="1.14.11">
@ -5316,20 +5316,20 @@
<sha256 value="d8531a746c988f7f68ed5f188cdea945006aea993ec5df9e524e0d27d61491da" origin="Generated by Gradle"/> <sha256 value="d8531a746c988f7f68ed5f188cdea945006aea993ec5df9e524e0d27d61491da" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="org.mockito" name="mockito-core" version="4.11.0"> <component group="org.mockito" name="mockito-core" version="5.8.0">
<artifact name="mockito-core-4.11.0.jar"> <artifact name="mockito-core-5.8.0.jar">
<sha256 value="4b909690cab288c761eb94c0bf0e814496cf3921d8affac84cd87774530351e5" origin="Generated by Gradle"/> <sha256 value="c320f662a03c2951edcc51a44b64d79a8e994373ff548453b5fdaf69debe4682" origin="Generated by Gradle"/>
</artifact> </artifact>
<artifact name="mockito-core-4.11.0.pom"> <artifact name="mockito-core-5.8.0.pom">
<sha256 value="2bc2e3c8c8b313fdac231f23822225b07831dc899d067072f49d5f8ae37e739a" origin="Generated by Gradle"/> <sha256 value="74958acdde148f30bfa31ffc0858b62f71f63ccc2ceb4d8a8c67d7f428d43a2d" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="org.mockito" name="mockito-junit-jupiter" version="4.11.0"> <component group="org.mockito" name="mockito-junit-jupiter" version="5.8.0">
<artifact name="mockito-junit-jupiter-4.11.0.jar"> <artifact name="mockito-junit-jupiter-5.8.0.jar">
<sha256 value="f4b3694f60fccc7b520d8aea9b6c827d8e9949b652cad09fce10b546bf3ac537" origin="Generated by Gradle"/> <sha256 value="9f6ccc29654335b92ac20e800eb44949772031711185bed6a44a5f8bd56e476b" origin="Generated by Gradle"/>
</artifact> </artifact>
<artifact name="mockito-junit-jupiter-4.11.0.pom"> <artifact name="mockito-junit-jupiter-5.8.0.pom">
<sha256 value="b724ad13e3e450cb022672fe5ca6f1d38d5d7485246a3ff3d278edf9321e3417" origin="Generated by Gradle"/> <sha256 value="036ac84dd98ef3d56e7d8118e819060a58f611d30bd3a2c350c42702921177be" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="org.objenesis" name="objenesis" version="3.3"> <component group="org.objenesis" name="objenesis" version="3.3">

@ -192,7 +192,7 @@ dependencyManagement {
entry 'org.jupnp' entry 'org.jupnp'
} }
dependencySet(group: 'org.mockito', version:'4.11.0') { dependencySet(group: 'org.mockito', version:'5.8.0') {
entry 'mockito-core' entry 'mockito-core'
entry 'mockito-junit-jupiter' entry 'mockito-junit-jupiter'
} }

Loading…
Cancel
Save