Skip to content

Commit

Permalink
feat(chain): Exposed genesis config + runtime config and genesis reco…
Browse files Browse the repository at this point in the history
…rds via RPC

We needed to make Near config query-able through node RPC. Specifically,
one of our clients wanted to have know how many blocks remain until an
account is going to be evicted due to rent. This information can be
derived from the account balance and the config.

In this commit, two new RPC endpoints are exposed:
EXPERIMENTAL_genesis_config and EXPERIMENTAL_genesis_records. Learn more
in PR #2109.

 # Test plan

Added tests to query the endpoints with happy path and also invalid
parameters.
  • Loading branch information
frol committed Feb 27, 2020
1 parent edd3fce commit 51bb270
Show file tree
Hide file tree
Showing 41 changed files with 433 additions and 179 deletions.
46 changes: 43 additions & 3 deletions Cargo.lock

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

8 changes: 6 additions & 2 deletions chain/chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,12 @@ impl ChainGenesis {
}
}

impl From<GenesisConfig> for ChainGenesis {
fn from(genesis_config: GenesisConfig) -> Self {
impl<T> From<T> for ChainGenesis
where
T: AsRef<GenesisConfig>,
{
fn from(genesis_config: T) -> Self {
let genesis_config = genesis_config.as_ref();
ChainGenesis::new(
genesis_config.genesis_time,
genesis_config.gas_limit,
Expand Down
8 changes: 5 additions & 3 deletions chain/client/tests/challenges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ fn test_verify_chunk_invalid_state_challenge() {
let runtimes: Vec<Arc<dyn RuntimeAdapter>> = vec![Arc::new(near::NightshadeRuntime::new(
Path::new("."),
store1,
genesis_config,
Arc::new(genesis_config),
vec![],
vec![],
))];
Expand Down Expand Up @@ -685,11 +685,12 @@ fn test_fishermen_challenge() {
init_test_logger();
let mut genesis_config = GenesisConfig::test(vec!["test0", "test1", "test2"], 1);
genesis_config.epoch_length = 5;
let genesis_config = Arc::new(genesis_config);
let create_runtime = || -> Arc<NightshadeRuntime> {
Arc::new(near::NightshadeRuntime::new(
Path::new("."),
create_test_store(),
genesis_config.clone(),
Arc::clone(&genesis_config),
vec![],
vec![],
))
Expand Down Expand Up @@ -744,12 +745,13 @@ fn test_challenge_in_different_epoch() {
init_test_logger();
let mut genesis_config = GenesisConfig::test(vec!["test0", "test1"], 2);
genesis_config.epoch_length = 2;
let genesis_config = Arc::new(genesis_config);
// genesis_config.validator_kickout_threshold = 10;
let network_adapter = Arc::new(MockNetworkAdapter::default());
let runtime1 = Arc::new(near::NightshadeRuntime::new(
Path::new("."),
create_test_store(),
genesis_config.clone(),
Arc::clone(&genesis_config),
vec![],
vec![],
));
Expand Down
5 changes: 3 additions & 2 deletions chain/jsonrpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ chrono = { version = "0.4.4", features = ["serde"] }
lazy_static = "1.4"
log = "0.4"
prometheus = "^0.7"
serde_derive = "1.0"
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
validator = "0.10"
uuid = { version = "~0.8", features = ["v4"] }
borsh = "0.2.10"

near-chain-configs = { path = "../../core/chain-configs" }
near-crypto = { path = "../../core/crypto" }
near-primitives = { path = "../../core/primitives" }
near-store = { path = "../../core/store" }
Expand Down
4 changes: 2 additions & 2 deletions chain/jsonrpc/client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ edition = "2018"
[dependencies]
actix-web = "2.0.0"
futures = "0.3"
serde_derive = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde = "1.0"
uuid = { version = "~0.8", features = ["v4"] }

near-chain-configs = { path = "../../../core/chain-configs" }
near-primitives = { path = "../../../core/primitives" }
14 changes: 12 additions & 2 deletions chain/jsonrpc/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ use serde::Deserialize;
use serde::Serialize;

use near_primitives::hash::CryptoHash;
use near_primitives::rpc::{BlockQueryInfo, RpcQueryRequest};
use near_primitives::rpc::{BlockQueryInfo, RpcGenesisRecordsRequest, RpcQueryRequest};
use near_primitives::types::{BlockId, MaybeBlockId, ShardId};
use near_primitives::views::{
BlockView, ChunkView, EpochValidatorInfo, FinalExecutionOutcomeView, GasPriceView,
QueryResponse, StateChangesView, StatusResponse,
GenesisRecordsView, QueryResponse, StateChangesView, StatusResponse,
};

use crate::message::{from_slice, Message, RpcError};
Expand Down Expand Up @@ -180,6 +180,8 @@ jsonrpc_client!(pub struct JsonRpcClient {
pub fn broadcast_tx_async(&mut self, tx: String) -> RpcRequest<String>;
pub fn broadcast_tx_commit(&mut self, tx: String) -> RpcRequest<FinalExecutionOutcomeView>;
pub fn status(&mut self) -> RpcRequest<StatusResponse>;
#[allow(non_snake_case)]
pub fn EXPERIMENTAL_genesis_config(&mut self) -> RpcRequest<serde_json::Value>;
pub fn health(&mut self) -> RpcRequest<()>;
pub fn tx(&mut self, hash: String, account_id: String) -> RpcRequest<FinalExecutionOutcomeView>;
pub fn chunk(&mut self, id: ChunkId) -> RpcRequest<ChunkView>;
Expand All @@ -189,6 +191,14 @@ jsonrpc_client!(pub struct JsonRpcClient {
});

impl JsonRpcClient {
#[allow(non_snake_case)]
pub fn EXPERIMENTAL_genesis_records(
&mut self,
request: RpcGenesisRecordsRequest,
) -> RpcRequest<GenesisRecordsView> {
call_method(&self.client, &self.server_addr, "EXPERIMENTAL_genesis_records", request)
}

/// This is a soft-deprecated method to do query RPC request with a path and data positional
/// parameters.
pub fn query_by_path(&mut self, path: String, data: String) -> RpcRequest<QueryResponse> {
Expand Down
22 changes: 14 additions & 8 deletions chain/jsonrpc/client/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@
//! The main entrypoint here is the [Message](enum.Message.html). The others are just building
//! blocks and you should generally work with `Message` instead.
#![allow(unused)]

use std::fmt::{Formatter, Result as FmtResult};

use serde::de::{Deserialize, Deserializer, Error, Unexpected, Visitor};
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde_derive::{Deserialize, Serialize};
use serde::de::{Deserializer, Error, Unexpected, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use serde_json::{to_value, Result as JsonResult, Value};
use uuid::Uuid;

Expand Down Expand Up @@ -92,8 +90,17 @@ impl RpcError {
RpcError { code, message, data }
}
/// Create an Invalid Param error.
pub fn invalid_params(msg: Option<String>) -> Self {
RpcError::new(-32_602, "Invalid params".to_owned(), msg.map(Value::String))
pub fn invalid_params(data: impl Serialize) -> Self {
let value = match to_value(data) {
Ok(value) => value,
Err(err) => {
return Self::server_error(Some(format!(
"Failed to serialize invalid parameters error: {:?}",
err.to_string()
)))
}
};
RpcError::new(-32_602, "Invalid params".to_owned(), Some(value))
}
/// Create a server error.
pub fn server_error<E: Serialize>(e: Option<E>) -> Self {
Expand Down Expand Up @@ -172,7 +179,6 @@ struct WireResponse {
// structure that directly corresponds to whatever is on the wire and then convert it to our more
// convenient representation.
impl<'de> Deserialize<'de> for Response {
#[allow(unreachable_code)] // For that unreachable below
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let wr: WireResponse = Deserialize::deserialize(deserializer)?;
let result = match (wr.result, wr.error) {
Expand Down
Loading

0 comments on commit 51bb270

Please sign in to comment.