Skip to content
This repository has been archived by the owner on Sep 26, 2019. It is now read-only.

Initial PoC for RPC end points via the plugin mechanism. #1909

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ public Optional<Integer> getJsonRpcWebSocketPort() {
}

public Optional<Integer> getJsonRpcSocketPort() {
if (isWebSocketsRpcEnabled()) {
if (isJsonRpcEnabled()) {
return Optional.of(Integer.valueOf(portsProperties.getProperty("json-rpc")));
} else {
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.plugin.services.PantheonEvents;
import tech.pegasys.pantheon.plugin.services.PicoCLIOptions;
import tech.pegasys.pantheon.plugin.services.RpcEndpointService;
import tech.pegasys.pantheon.services.PantheonEventsImpl;
import tech.pegasys.pantheon.services.PantheonPluginContextImpl;
import tech.pegasys.pantheon.services.PicoCLIOptionsImpl;
import tech.pegasys.pantheon.services.RPCEndpointServiceImpl;
import tech.pegasys.pantheon.services.kvstore.RocksDbConfiguration;

import java.io.File;
Expand Down Expand Up @@ -72,6 +74,9 @@ private PantheonPluginContextImpl buildPluginContext(final PantheonNode node) {
pluginsDirFile.deleteOnExit();
}
System.setProperty("pantheon.plugins.dir", pluginsPath.toString());
final RPCEndpointServiceImpl rpcEndpointService = new RPCEndpointServiceImpl();
node.jsonRpcConfiguration().setPluginEndpoints(rpcEndpointService.getRpcMethods());
pantheonPluginContext.addService(RpcEndpointService.class, rpcEndpointService);
pantheonPluginContext.registerPlugins(pluginsPath);
return pantheonPluginContext;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,23 @@ public PantheonNode createArchiveNodeWithRpcDisabled(final String name) throws I
}

public PantheonNode createPluginsNode(
final String name, final List<String> plugins, final List<String> extraCLIOptions)
final String name,
final List<String> plugins,
final List<String> extraCLIOptions,
final RpcApi... enabledRpcApis)
throws IOException {
return create(
final PantheonNodeConfigurationBuilder pantheonNodeConfigurationBuilder =
new PantheonNodeConfigurationBuilder()
.name(name)
.plugins(plugins)
.extraCLIOptions(extraCLIOptions)
.build());
.extraCLIOptions(extraCLIOptions);
if (enabledRpcApis.length > 0) {
final JsonRpcConfiguration jsonRpcConfig = node.createJsonRpcEnabledConfig();
jsonRpcConfig.setRpcApis(asList(enabledRpcApis));
pantheonNodeConfigurationBuilder.jsonRpcConfiguration(jsonRpcConfig);
}

return create(pantheonNodeConfigurationBuilder.build());
}

public PantheonNode createArchiveNodeWithRpcApis(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Copyright 2019 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.pantheon.tests.acceptance.plugins;

import static org.assertj.core.api.Assertions.assertThat;

import tech.pegasys.pantheon.config.JsonUtil;
import tech.pegasys.pantheon.ethereum.jsonrpc.RpcApis;
import tech.pegasys.pantheon.tests.acceptance.dsl.AcceptanceTestBase;
import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode;

import java.io.IOException;
import java.util.Collections;

import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.junit.Before;
import org.junit.Test;

public class RpcEndpointPluginTest extends AcceptanceTestBase {

private PantheonNode node;
private OkHttpClient client;
protected static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

@Before
public void setUp() throws Exception {
node =
pantheon.createPluginsNode(
"node1",
Collections.singletonList("testPlugins"),
Collections.emptyList(),
RpcApis.NET);
cluster.start(node);
client = new OkHttpClient();
}

@Test
public void rpcWorking() throws IOException {
final String firstCall = "FirstCall";
final String secondCall = "SecondCall";
final String thirdCall = "ThirdCall";
final String fourthCall = "FourthCall";

ObjectNode resultJson = callTestMethod("unitTests_replaceValue", firstCall);
assertThat(resultJson.get("result").asText()).isEqualTo("InitialValue");

resultJson = callTestMethod("unitTests_replaceValueArray", secondCall);
assertThat(resultJson.get("result").get(0).asText()).isEqualTo(firstCall);

resultJson = callTestMethod("unitTests_replaceValueBean", thirdCall);
assertThat(resultJson.get("result").get("value").asText()).isEqualTo(secondCall);

resultJson = callTestMethod("unitTests_replaceValueLength", fourthCall);
assertThat(resultJson.get("result").asInt()).isEqualTo(thirdCall.length());
}

@Test
public void throwsError() throws IOException {
ObjectNode resultJson = callTestMethod("unitTests_replaceValue", null);
assertThat(resultJson.get("result").asText()).isEqualTo("InitialValue");

resultJson = callTestMethod("unitTests_replaceValueLength", "InitialValue");
assertThat(resultJson.get("error").get("message").asText()).isEqualTo("Internal error");
}

private ObjectNode callTestMethod(final String method, final String value) throws IOException {
final String resultString =
client
.newCall(
new Request.Builder()
.post(
RequestBody.create(
JSON,
"{\"jsonrpc\":\"2.0\",\"method\":\""
+ method
+ "\",\"params\":["
+ (value == null ? value : "\"" + value + "\"")
+ "],\"id\":33}"))
.url(
"http://"
+ node.getHostName()
+ ":"
+ node.getJsonRpcSocketPort().get()
+ "/")
.build())
.execute()
.body()
.string();
System.out.println(resultString);
return JsonUtil.objectNodeFromString(resultString);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import com.google.common.base.MoreObjects;

Expand All @@ -33,6 +35,7 @@ public class JsonRpcConfiguration {
private List<String> hostsWhitelist = Arrays.asList("localhost", "127.0.0.1");
private boolean authenticationEnabled = false;
private String authenticationCredentialsFile;
private Map<String, Function<List<String>, ?>> pluginEndpoints = Collections.emptyMap();

public static JsonRpcConfiguration createDefault() {
final JsonRpcConfiguration config = new JsonRpcConfiguration();
Expand Down Expand Up @@ -100,6 +103,14 @@ public void setHostsWhitelist(final List<String> hostsWhitelist) {
this.hostsWhitelist = hostsWhitelist;
}

public Map<String, Function<List<String>, ?>> getPluginEndpoints() {
return pluginEndpoints;
}

public void setPluginEndpoints(final Map<String, Function<List<String>, ?>> pluginEndpoints) {
this.pluginEndpoints = pluginEndpoints;
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2019 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.pantheon.ethereum.jsonrpc.internal.methods;

import tech.pegasys.pantheon.ethereum.jsonrpc.internal.JsonRpcRequest;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.response.JsonRpcError;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.response.JsonRpcErrorResponse;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.response.JsonRpcResponse;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.response.JsonRpcSuccessResponse;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PluginJsonRpcMethod implements JsonRpcMethod {

private final String name;
private final Function<List<String>, ?> function;

public PluginJsonRpcMethod(final String name, final Function<List<String>, ?> function) {
this.name = name;
this.function = function;
}

@Override
public String getName() {
return name;
}

@Override
public JsonRpcResponse response(final JsonRpcRequest request) {
try {
return new JsonRpcSuccessResponse(
request.getId(),
function.apply(
Arrays.stream(request.getParams())
.map(o -> o == null ? null : o.toString())
.collect(Collectors.toList())));
} catch (final RuntimeException re) {
return new JsonRpcErrorResponse(request.getId(), JsonRpcError.INTERNAL_ERROR);
}
}
}
21 changes: 14 additions & 7 deletions pantheon/src/main/java/tech/pegasys/pantheon/RunnerBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.filter.FilterManager;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.filter.FilterRepository;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.methods.JsonRpcMethod;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.methods.PluginJsonRpcMethod;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.queries.BlockchainQueries;
import tech.pegasys.pantheon.ethereum.jsonrpc.websocket.WebSocketConfiguration;
import tech.pegasys.pantheon.ethereum.jsonrpc.websocket.WebSocketRequestHandler;
Expand Down Expand Up @@ -92,6 +93,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.google.common.annotations.VisibleForTesting;
Expand All @@ -105,7 +107,7 @@ public class RunnerBuilder {
private PantheonController<?> pantheonController;

private NetworkingConfiguration networkingConfiguration = NetworkingConfiguration.create();
private Collection<BytesValue> bannedNodeIds = new ArrayList<>();
private final Collection<BytesValue> bannedNodeIds = new ArrayList<>();
private boolean p2pEnabled = true;
private boolean discovery;
private String p2pAdvertisedHost;
Expand Down Expand Up @@ -304,8 +306,8 @@ public Runner build() {

final Optional<UpnpNatManager> natManager = buildNatManager(natMethod);

NetworkBuilder inactiveNetwork = (caps) -> new NoopP2PNetwork();
NetworkBuilder activeNetwork =
final NetworkBuilder inactiveNetwork = (caps) -> new NoopP2PNetwork();
final NetworkBuilder activeNetwork =
(caps) ->
DefaultP2PNetwork.builder()
.vertx(vertx)
Expand Down Expand Up @@ -375,7 +377,8 @@ public Runner build() {
privacyParameters,
jsonRpcConfiguration,
webSocketConfiguration,
metricsConfiguration);
metricsConfiguration,
jsonRpcConfiguration.getPluginEndpoints());
jsonRpcHttpService =
Optional.of(
new JsonRpcHttpService(
Expand Down Expand Up @@ -433,7 +436,8 @@ public Runner build() {
privacyParameters,
jsonRpcConfiguration,
webSocketConfiguration,
metricsConfiguration);
metricsConfiguration,
Collections.emptyMap());

final SubscriptionManager subscriptionManager =
createSubscriptionManager(vertx, transactionPool);
Expand Down Expand Up @@ -510,7 +514,7 @@ private Optional<AccountPermissioningController> buildAccountPermissioningContro
final TransactionSimulator transactionSimulator) {

if (permissioningConfiguration.isPresent()) {
Optional<AccountPermissioningController> accountPermissioningController =
final Optional<AccountPermissioningController> accountPermissioningController =
AccountPermissioningControllerFactory.create(
permissioningConfiguration.get(), transactionSimulator, metricsSystem);

Expand Down Expand Up @@ -563,7 +567,8 @@ private Map<String, JsonRpcMethod> jsonRpcMethods(
final PrivacyParameters privacyParameters,
final JsonRpcConfiguration jsonRpcConfiguration,
final WebSocketConfiguration webSocketConfiguration,
final MetricsConfiguration metricsConfiguration) {
final MetricsConfiguration metricsConfiguration,
final Map<String, Function<List<String>, ?>> pluginMethods) {
final Map<String, JsonRpcMethod> methods =
new JsonRpcMethodsFactory()
.methods(
Expand All @@ -588,6 +593,8 @@ private Map<String, JsonRpcMethod> jsonRpcMethods(
webSocketConfiguration,
metricsConfiguration);
methods.putAll(pantheonController.getAdditionalJsonRpcMethods(jsonRpcApis));
pluginMethods.forEach(
(name, function) -> methods.put(name, new PluginJsonRpcMethod(name, function)));
return methods;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,12 @@
import tech.pegasys.pantheon.plugin.services.MetricsSystem;
import tech.pegasys.pantheon.plugin.services.PantheonEvents;
import tech.pegasys.pantheon.plugin.services.PicoCLIOptions;
import tech.pegasys.pantheon.plugin.services.RpcEndpointService;
import tech.pegasys.pantheon.plugin.services.metrics.MetricCategory;
import tech.pegasys.pantheon.services.PantheonEventsImpl;
import tech.pegasys.pantheon.services.PantheonPluginContextImpl;
import tech.pegasys.pantheon.services.PicoCLIOptionsImpl;
import tech.pegasys.pantheon.services.RPCEndpointServiceImpl;
import tech.pegasys.pantheon.services.kvstore.RocksDbConfiguration;
import tech.pegasys.pantheon.util.PermissioningConfigurationValidator;
import tech.pegasys.pantheon.util.bytes.BytesValue;
Expand Down Expand Up @@ -171,6 +173,7 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
private final RunnerBuilder runnerBuilder;
private final PantheonController.Builder controllerBuilderFactory;
private final PantheonPluginContextImpl pantheonPluginContext;
private final RPCEndpointServiceImpl rpcEndpointService;
private final Map<String, String> environment;

protected KeyLoader getKeyLoader() {
Expand Down Expand Up @@ -679,6 +682,7 @@ public PantheonCommand(
this.controllerBuilderFactory = controllerBuilderFactory;
this.pantheonPluginContext = pantheonPluginContext;
this.environment = environment;
this.rpcEndpointService = new RPCEndpointServiceImpl();
}

private StandaloneCommand standaloneCommands;
Expand Down Expand Up @@ -774,6 +778,7 @@ private PantheonCommand handleUnstableOptions() {
private PantheonCommand preparePlugins() {
pantheonPluginContext.addService(PicoCLIOptions.class, new PicoCLIOptionsImpl(commandLine));
pantheonPluginContext.addService(MetricsSystem.class, getMetricsSystem());
pantheonPluginContext.addService(RpcEndpointService.class, rpcEndpointService);
pantheonPluginContext.registerPlugins(pluginsDir());
return this;
}
Expand Down Expand Up @@ -1002,6 +1007,7 @@ private JsonRpcConfiguration jsonRpcConfiguration() {
jsonRpcConfiguration.setHostsWhitelist(hostsWhitelist);
jsonRpcConfiguration.setAuthenticationEnabled(isRpcHttpAuthenticationEnabled);
jsonRpcConfiguration.setAuthenticationCredentialsFile(rpcHttpAuthenticationCredentialsFile());
jsonRpcConfiguration.setPluginEndpoints(rpcEndpointService.getRpcMethods());
return jsonRpcConfiguration;
}

Expand Down
Loading