Skip to content

Commit

Permalink
Add new configuration RPC endpoints (#17)
Browse files Browse the repository at this point in the history
feat: Add new configuration RPC endpoints (config_getShowCalls, config_setShowCalls, and config_setResolveHashes). Add example http REST file for quickly testing the node locally. Add recommended plugins for VSCode. Add SUPPORTED_APIS.md. Update version to 1.0.3
  • Loading branch information
MexicanAce authored Jul 31, 2023
1 parent f5db37f commit 0c9d64c
Show file tree
Hide file tree
Showing 10 changed files with 261 additions and 5 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ etc/system-contracts/.yarnrc.yml
etc/system-contracts/bootloader/build

etc/**/*.zbin
.vscode/
.vscode/*
!.vscode/extensions.json
6 changes: 6 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"rust-lang.rust-analyzer",
"humao.rest-client",
],
}
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "era_test_node"
version = "1.0.2"
version = "1.0.3"
edition = "2018"
authors = ["The Matter Labs Team <hello@matterlabs.dev>"]
homepage = "https://zksync.io/"
Expand Down Expand Up @@ -29,6 +29,8 @@ once_cell = "1.7"

jsonrpc-http-server = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" }
jsonrpc-core = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" }
jsonrpc-core-client = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" }
jsonrpc-derive = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" }

clap = { version = "4.2.4", features = ["derive"] }
reqwest = { version = "0.11", features = ["blocking"] }
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ Here's a list of the available rich wallets:
Feel free to use these wallets in your tests, but remember, they are for development purposes only and should not be used in production or with real assets.
## 🔧 Supported APIs
See our list of [Supported APIs here](SUPPORTED_APIS.md).
## 🤝 Contributing
We welcome contributions from the community! If you're interested in contributing to the zkSync Era In-Memory Node, please take a look at our [CONTRIBUTING.md](./.github/CONTRIBUTING.md) for guidelines and details on the process.
Expand Down
82 changes: 82 additions & 0 deletions SUPPORTED_APIS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# 🔧 Supported APIs for In-Memory Node 🔧

> ⚠️ **WORK IN PROGRESS**: This list is non-comprehensive and being updated
# Key

The `status` options are:

+ `SUPPORTED` - Basic support is complete
+ `PARTIALLY` - Partial support and a description including more specific details
+ `NOT IMPLEMENTED` - Currently not supported/implemented

# `CONFIG NAMESPACE`

## `config_getShowCalls`

[source](src/configuration_api.rs)

Gets the current value of `show_calls` that's originally set with `--show-calls` option

### Arguments

+ _NONE_

### Status

`SUPPORTED`

### Example

```bash
curl --request POST \
--url http://localhost:8011/ \
--header 'content-type: application/json' \
--data '{"jsonrpc": "2.0","id": "1","method": "config_getShowCalls","params": []}'
```

## `config_setShowCalls`

[source](src/configuration_api.rs)

Updates `show_calls` to print more detailed call traces

### Arguments

+ `value: String ('None', 'User', 'System', 'All')`

### Status

`SUPPORTED`

### Example

```bash
curl --request POST \
--url http://localhost:8011/ \
--header 'content-type: application/json' \
--data '{"jsonrpc": "2.0","id": "1","method": "config_setShowCalls","params": ["all"]}'
```

## `config_setResolveHashes`

[source](src/configuration_api.rs)

Updates `resolve-hashes` to call OpenChain for human-readable ABI names in call traces

### Arguments

+ `value: boolean`

### Status

`SUPPORTED`

### Example

```bash
curl --request POST \
--url http://localhost:8011/ \
--header 'content-type: application/json' \
--data '{"jsonrpc": "2.0","id": "1","method": "config_setResolveHashes","params": [true]}'
```
78 changes: 78 additions & 0 deletions src/configuration_api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Built-in uses
use std::sync::{Arc, RwLock};

// External uses
use jsonrpc_core::Result;
use jsonrpc_derive::rpc;

// Workspace uses

// Local uses
use crate::{node::InMemoryNodeInner, ShowCalls};

pub struct ConfigurationApiNamespace {
node: Arc<RwLock<InMemoryNodeInner>>,
}

impl ConfigurationApiNamespace {
pub fn new(node: Arc<RwLock<InMemoryNodeInner>>) -> Self {
Self { node }
}
}

#[rpc]
pub trait ConfigurationApiNamespaceT {
/// Get the InMemoryNodeInner's show_calls property as a string
///
/// # Returns
/// The current `show_calls` value for the InMemoryNodeInner.
#[rpc(name = "config_getShowCalls", returns = "String")]
fn config_get_show_calls(&self) -> Result<String>;

/// Set show_calls for the InMemoryNodeInner
///
/// # Parameters
/// - `value`: A ShowCalls enum to update show_calls to
///
/// # Returns
/// The updated/current `show_calls` value for the InMemoryNodeInner.
#[rpc(name = "config_setShowCalls", returns = "String")]
fn config_set_show_calls(&self, value: String) -> Result<String>;

/// Set resolve_hashes for the InMemoryNodeInner
///
/// # Parameters
/// - `value`: A bool to update resolve_hashes to
///
/// # Returns
/// The updated `resolve_hashes` value for the InMemoryNodeInner.
#[rpc(name = "config_setResolveHashes", returns = "bool")]
fn config_set_resolve_hashes(&self, value: bool) -> Result<bool>;
}

impl ConfigurationApiNamespaceT for ConfigurationApiNamespace {
fn config_get_show_calls(&self) -> Result<String> {
let reader = self.node.read().unwrap();
Ok(reader.show_calls.to_string())
}

fn config_set_show_calls(&self, value: String) -> Result<String> {
let show_calls = match value.parse::<ShowCalls>() {
Ok(value) => value,
Err(_) => {
let reader = self.node.read().unwrap();
return Ok(reader.show_calls.to_string());
}
};

let mut inner = self.node.write().unwrap();
inner.show_calls = show_calls;
Ok(inner.show_calls.to_string())
}

fn config_set_resolve_hashes(&self, value: bool) -> Result<bool> {
let mut inner = self.node.write().unwrap();
inner.resolve_hashes = value;
Ok(inner.resolve_hashes)
}
}
23 changes: 22 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use clap::{Parser, Subcommand};
use configuration_api::ConfigurationApiNamespaceT;
use fork::ForkDetails;
use zks::ZkMockNamespaceImpl;

mod configuration_api;
mod console_log;
mod deps;
mod fork;
Expand Down Expand Up @@ -32,7 +34,7 @@ use futures::{
use jsonrpc_core::IoHandler;
use zksync_basic_types::{L2ChainId, H160, H256};

use crate::node::TEST_NODE_NETWORK_ID;
use crate::{configuration_api::ConfigurationApiNamespace, node::TEST_NODE_NETWORK_ID};
use zksync_core::api_server::web3::backend_jsonrpc::namespaces::{
eth::EthNamespaceT, net::NetNamespaceT, zks::ZksNamespaceT,
};
Expand Down Expand Up @@ -61,13 +63,15 @@ async fn build_json_http(
addr: SocketAddr,
node: InMemoryNode,
net: NetNamespace,
config_api: ConfigurationApiNamespace,
) -> tokio::task::JoinHandle<()> {
let (sender, recv) = oneshot::channel::<()>();

let io_handler = {
let mut io = IoHandler::new();
io.extend_with(node.to_delegate());
io.extend_with(net.to_delegate());
io.extend_with(config_api.to_delegate());
io.extend_with(ZkMockNamespaceImpl.to_delegate());

io
Expand Down Expand Up @@ -123,6 +127,20 @@ pub enum ShowCalls {
All,
}

impl FromStr for ShowCalls {
type Err = ();

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_ref() {
"none" => Ok(ShowCalls::None),
"user" => Ok(ShowCalls::User),
"system" => Ok(ShowCalls::System),
"all" => Ok(ShowCalls::All),
_ => Err(()),
}
}
}

impl Display for ShowCalls {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)
Expand Down Expand Up @@ -231,10 +249,13 @@ async fn main() -> anyhow::Result<()> {

let net = NetNamespace::new(L2ChainId(TEST_NODE_NETWORK_ID));

let config_api = ConfigurationApiNamespace::new(node.get_inner());

let threads = build_json_http(
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), opt.port),
node,
net,
config_api,
)
.await;

Expand Down
6 changes: 5 additions & 1 deletion src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ impl InMemoryNode {
}
}

pub fn get_inner(&self) -> Arc<RwLock<InMemoryNodeInner>> {
self.inner.clone()
}

/// Applies multiple transactions - but still one per L1 batch.
pub fn apply_txs(&self, txs: Vec<L2Tx>) {
println!("Running {:?} transactions (one per batch)", txs.len());
Expand Down Expand Up @@ -386,7 +390,7 @@ impl InMemoryNode {
}

println!(
"\n==== {} Use --show-calls flag to display more info.",
"\n==== {} Use --show-calls flag or call config_setResolveHashes to display more info.",
format!("{:?} call traces. ", tx_result.call_traces.len()).bold()
);

Expand Down
56 changes: 56 additions & 0 deletions test_endpoints.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
POST http://localhost:8011
content-type: application/json

{
"jsonrpc": "2.0",
"id": "1",
"method": "eth_blockNumber",
"params": []
}

###
POST http://localhost:8011
content-type: application/json

{
"jsonrpc": "2.0",
"id": "1",
"method": "net_version",
"params": []
}

###
POST http://localhost:8011
content-type: application/json

{
"jsonrpc": "2.0",
"id": "1",
"method": "config_getShowCalls",
"params": []
}

###
POST http://localhost:8011
content-type: application/json

{
"jsonrpc": "2.0",
"id": "1",
"method": "config_setShowCalls",
"params": ["All"]
}

###
POST http://localhost:8011
content-type: application/json

{
"jsonrpc": "2.0",
"id": "1",
"method": "config_setResolveHashes",
"params": [true]
}

###

0 comments on commit 0c9d64c

Please sign in to comment.