Exposing types from RPC

This commit is contained in:
Tomasz Drwięga
2016-05-27 15:46:07 +02:00
parent d0ae713b29
commit 6f93ecf1d2
26 changed files with 156 additions and 18 deletions

View File

@@ -27,7 +27,6 @@ extern crate serde_json;
extern crate jsonrpc_core;
extern crate jsonrpc_http_server;
extern crate ethcore_util as util;
extern crate ethcore_signer as signer;
extern crate ethcore;
extern crate ethsync;
extern crate ethminer;

View File

@@ -18,12 +18,12 @@
//!
//! Compliant with ethereum rpc.
pub mod traits;
mod impls;
mod types;
mod helpers;
pub mod traits;
pub mod tests;
pub mod types;
pub use self::traits::{Web3, Eth, EthFilter, Personal, Net, Ethcore, Traces, Rpc};
pub use self::impls::*;

View File

@@ -18,9 +18,12 @@ use serde::{Serialize, Serializer};
use util::numbers::*;
use v1::types::{Bytes, Transaction, OptionalValue};
/// Block Transactions
#[derive(Debug)]
pub enum BlockTransactions {
/// Only hashes
Hashes(Vec<H256>),
/// Full transactions
Full(Vec<Transaction>)
}
@@ -34,38 +37,58 @@ impl Serialize for BlockTransactions {
}
}
/// Block representation
#[derive(Debug, Serialize)]
pub struct Block {
/// Hash of the block
pub hash: OptionalValue<H256>,
/// Hash of the parent
#[serde(rename="parentHash")]
pub parent_hash: H256,
/// Hash of the uncles
#[serde(rename="sha3Uncles")]
pub uncles_hash: H256,
/// Authors address
pub author: Address,
// TODO: get rid of this one
/// ?
pub miner: Address,
/// State root hash
#[serde(rename="stateRoot")]
pub state_root: H256,
/// Transactions root hash
#[serde(rename="transactionsRoot")]
pub transactions_root: H256,
/// Transactions receipts root hash
#[serde(rename="receiptsRoot")]
pub receipts_root: H256,
/// Block number
pub number: OptionalValue<U256>,
/// Gas Used
#[serde(rename="gasUsed")]
pub gas_used: U256,
/// Gas Limit
#[serde(rename="gasLimit")]
pub gas_limit: U256,
/// Extra data
#[serde(rename="extraData")]
pub extra_data: Bytes,
/// Logs bloom
#[serde(rename="logsBloom")]
pub logs_bloom: H2048,
/// Timestamp
pub timestamp: U256,
/// Difficulty
pub difficulty: U256,
/// Total difficulty
#[serde(rename="totalDifficulty")]
pub total_difficulty: U256,
/// Seal fields
#[serde(rename="sealFields")]
pub seal_fields: Vec<Bytes>,
/// Uncles' hashes
pub uncles: Vec<H256>,
/// Transactions
pub transactions: BlockTransactions
}

View File

@@ -21,9 +21,13 @@ use ethcore::client::BlockID;
/// Represents rpc api block number param.
#[derive(Debug, PartialEq, Clone)]
pub enum BlockNumber {
/// Number
Num(u64),
/// Latest block
Latest,
/// Earliest block (genesis)
Earliest,
/// Pending block (being mined)
Pending
}

87
rpc/src/v1/types/bytes.rs Normal file
View File

@@ -0,0 +1,87 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Serializable wrapper around vector of bytes
use rustc_serialize::hex::ToHex;
use serde::{Serialize, Serializer, Deserialize, Deserializer, Error};
use serde::de::Visitor;
use util::common::FromHex;
/// Wrapper structure around vector of bytes.
#[derive(Debug, PartialEq, Eq, Default, Hash, Clone)]
pub struct Bytes(pub Vec<u8>);
impl Bytes {
/// Simple constructor.
pub fn new(bytes: Vec<u8>) -> Bytes {
Bytes(bytes)
}
/// Convert back to vector
pub fn to_vec(self) -> Vec<u8> {
self.0
}
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer {
let mut serialized = "0x".to_owned();
serialized.push_str(self.0.to_hex().as_ref());
serializer.serialize_str(serialized.as_ref())
}
}
impl Deserialize for Bytes {
fn deserialize<D>(deserializer: &mut D) -> Result<Bytes, D::Error>
where D: Deserializer {
deserializer.deserialize(BytesVisitor)
}
}
struct BytesVisitor;
impl Visitor for BytesVisitor {
type Value = Bytes;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
if value.len() >= 2 && &value[0..2] == "0x" {
Ok(Bytes::new(FromHex::from_hex(&value[2..]).unwrap_or_else(|_| vec![])))
} else {
Err(Error::custom("invalid hex"))
}
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
use rustc_serialize::hex::FromHex;
#[test]
fn test_bytes_serialize() {
let bytes = Bytes("0123456789abcdef".from_hex().unwrap());
let serialized = serde_json::to_string(&bytes).unwrap();
assert_eq!(serialized, r#""0x0123456789abcdef""#);
}
}

View File

@@ -18,15 +18,23 @@ use util::hash::Address;
use util::numbers::U256;
use v1::types::Bytes;
/// Call request
#[derive(Debug, Default, PartialEq, Deserialize)]
pub struct CallRequest {
/// From
pub from: Option<Address>,
/// To
pub to: Option<Address>,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: Option<U256>,
/// Gas
pub gas: Option<U256>,
/// Value
pub value: Option<U256>,
/// Data
pub data: Option<Bytes>,
/// Nonce
pub nonce: Option<U256>,
}

View File

@@ -22,10 +22,14 @@ use v1::types::BlockNumber;
use ethcore::filter::Filter as EthFilter;
use ethcore::client::BlockID;
/// Variadic value
#[derive(Debug, PartialEq, Clone)]
pub enum VariadicValue<T> where T: Deserialize {
/// Single
Single(T),
/// List
Multiple(Vec<T>),
/// None
Null,
}
@@ -44,17 +48,24 @@ impl<T> Deserialize for VariadicValue<T> where T: Deserialize {
}
}
/// Filter Address
pub type FilterAddress = VariadicValue<Address>;
/// Topic
pub type Topic = VariadicValue<H256>;
/// Filter
#[derive(Debug, PartialEq, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Filter {
/// From Block
#[serde(rename="fromBlock")]
pub from_block: Option<BlockNumber>,
/// To Block
#[serde(rename="toBlock")]
pub to_block: Option<BlockNumber>,
/// Address
pub address: Option<FilterAddress>,
/// Topics
pub topics: Option<Vec<Topic>>,
}

View File

@@ -22,6 +22,7 @@ use serde::de::Visitor;
pub struct Index(usize);
impl Index {
/// Convert to usize
pub fn value(&self) -> usize {
self.0
}

View File

@@ -18,21 +18,31 @@ use util::numbers::*;
use ethcore::log_entry::{LocalizedLogEntry, LogEntry};
use v1::types::Bytes;
/// Log
#[derive(Debug, Serialize, PartialEq, Eq, Hash, Clone)]
pub struct Log {
/// Address
pub address: Address,
/// Topics
pub topics: Vec<H256>,
/// Data
pub data: Bytes,
/// Block Hash
#[serde(rename="blockHash")]
pub block_hash: Option<H256>,
/// Block Number
#[serde(rename="blockNumber")]
pub block_number: Option<U256>,
/// Transaction Hash
#[serde(rename="transactionHash")]
pub transaction_hash: Option<H256>,
/// Transaction Index
#[serde(rename="transactionIndex")]
pub transaction_index: Option<U256>,
/// Log Index
#[serde(rename="logIndex")]
pub log_index: Option<U256>,
/// Log Type
#[serde(rename="type")]
pub log_type: String,
}

View File

@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Structures used in RPC communication
#[cfg(feature = "serde_macros")]
include!("mod.rs.in");

View File

@@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
mod bytes;
mod block;
mod block_number;
mod filter;
@@ -22,13 +23,13 @@ mod log;
mod optionals;
mod sync;
mod transaction;
mod transaction_request;
mod call_request;
mod receipt;
mod trace;
mod trace_filter;
pub use signer::types::bytes::Bytes;
pub use signer::types::transaction_request::TransactionRequest;
pub use self::bytes::Bytes;
pub use self::block::{Block, BlockTransactions};
pub use self::block_number::BlockNumber;
pub use self::filter::Filter;
@@ -37,6 +38,7 @@ pub use self::log::Log;
pub use self::optionals::OptionalValue;
pub use self::sync::{SyncStatus, SyncInfo};
pub use self::transaction::Transaction;
pub use self::transaction_request::TransactionRequest;
pub use self::call_request::CallRequest;
pub use self::receipt::Receipt;
pub use self::trace::Trace;

View File

@@ -17,9 +17,12 @@
use serde::{Serialize, Serializer};
use serde_json::Value;
/// Optional value
#[derive(Debug)]
pub enum OptionalValue<T> where T: Serialize {
/// Some
Value(T),
/// None
Null
}

View File

@@ -19,22 +19,31 @@ use util::hash::{Address, H256};
use v1::types::Log;
use ethcore::receipt::LocalizedReceipt;
/// Receipt
#[derive(Debug, Serialize)]
pub struct Receipt {
/// Transaction Hash
#[serde(rename="transactionHash")]
pub transaction_hash: H256,
/// Transaction index
#[serde(rename="transactionIndex")]
pub transaction_index: U256,
/// Block hash
#[serde(rename="blockHash")]
pub block_hash: H256,
/// Block number
#[serde(rename="blockNumber")]
pub block_number: U256,
/// Cumulative gas used
#[serde(rename="cumulativeGasUsed")]
pub cumulative_gas_used: U256,
/// Gas used
#[serde(rename="gasUsed")]
pub gas_used: U256,
/// Contract address
#[serde(rename="contractAddress")]
pub contract_address: Option<Address>,
/// Logs
pub logs: Vec<Log>,
}

View File

@@ -17,19 +17,26 @@
use serde::{Serialize, Serializer};
use util::numbers::*;
/// Sync info
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct SyncInfo {
/// Starting block
#[serde(rename="startingBlock")]
pub starting_block: U256,
/// Current block
#[serde(rename="currentBlock")]
pub current_block: U256,
/// Highest block seen so far
#[serde(rename="highestBlock")]
pub highest_block: U256,
}
/// Sync status
#[derive(Debug, PartialEq)]
pub enum SyncStatus {
/// Info when syncing
Info(SyncInfo),
/// Not syncing
None
}

View File

@@ -19,11 +19,16 @@ use ethcore::trace::trace;
use ethcore::trace::LocalizedTrace;
use v1::types::Bytes;
/// Create response
#[derive(Debug, Serialize)]
pub struct Create {
/// Sender
from: Address,
/// Value
value: U256,
/// Gas
gas: U256,
/// Initialization code
init: Bytes,
}
@@ -38,12 +43,18 @@ impl From<trace::Create> for Create {
}
}
/// Call response
#[derive(Debug, Serialize)]
pub struct Call {
/// Sender
from: Address,
/// Recipient
to: Address,
/// Transfered Value
value: U256,
/// Gas
gas: U256,
/// Input data
input: Bytes,
}
@@ -59,10 +70,13 @@ impl From<trace::Call> for Call {
}
}
/// Action
#[derive(Debug, Serialize)]
pub enum Action {
/// Call
#[serde(rename="call")]
Call(Call),
/// Create
#[serde(rename="create")]
Create(Create),
}
@@ -76,10 +90,13 @@ impl From<trace::Action> for Action {
}
}
/// Call Result
#[derive(Debug, Serialize)]
pub struct CallResult {
/// Gas used
#[serde(rename="gasUsed")]
gas_used: U256,
/// Output bytes
output: Bytes,
}
@@ -92,11 +109,15 @@ impl From<trace::CallResult> for CallResult {
}
}
/// Craete Result
#[derive(Debug, Serialize)]
pub struct CreateResult {
/// Gas used
#[serde(rename="gasUsed")]
gas_used: U256,
/// Code
code: Bytes,
/// Assigned address
address: Address,
}
@@ -110,14 +131,19 @@ impl From<trace::CreateResult> for CreateResult {
}
}
/// Response
#[derive(Debug, Serialize)]
pub enum Res {
/// Call
#[serde(rename="call")]
Call(CallResult),
/// Create
#[serde(rename="create")]
Create(CreateResult),
/// Call failure
#[serde(rename="failedCall")]
FailedCall,
/// Creation failure
#[serde(rename="failedCreate")]
FailedCreate,
}
@@ -133,19 +159,28 @@ impl From<trace::Res> for Res {
}
}
/// Trace
#[derive(Debug, Serialize)]
pub struct Trace {
/// Action
action: Action,
/// Result
result: Res,
/// Trace address
#[serde(rename="traceAddress")]
trace_address: Vec<U256>,
/// Subtraces
subtraces: U256,
/// Transaction position
#[serde(rename="transactionPosition")]
transaction_position: U256,
/// Transaction hash
#[serde(rename="transactionHash")]
transaction_hash: H256,
/// Block Number
#[serde(rename="blockNumber")]
block_number: U256,
/// Block Hash
#[serde(rename="blockHash")]
block_hash: H256,
}

View File

@@ -21,14 +21,19 @@ use ethcore::client::BlockID;
use ethcore::client;
use super::BlockNumber;
/// Trace filter
#[derive(Debug, PartialEq, Deserialize)]
pub struct TraceFilter {
/// From block
#[serde(rename="fromBlock")]
pub from_block: Option<BlockNumber>,
/// To block
#[serde(rename="toBlock")]
pub to_block: Option<BlockNumber>,
/// From address
#[serde(rename="fromAddress")]
pub from_address: Option<Vec<Address>>,
/// To address
#[serde(rename="toAddress")]
pub to_address: Option<Vec<Address>>,
}

View File

@@ -18,22 +18,34 @@ use util::numbers::*;
use ethcore::transaction::{LocalizedTransaction, Action, SignedTransaction};
use v1::types::{Bytes, OptionalValue};
/// Transaction
#[derive(Debug, Default, Serialize)]
pub struct Transaction {
/// Hash
pub hash: H256,
/// Nonce
pub nonce: U256,
/// Block hash
#[serde(rename="blockHash")]
pub block_hash: OptionalValue<H256>,
/// Block number
#[serde(rename="blockNumber")]
pub block_number: OptionalValue<U256>,
/// Transaction Index
#[serde(rename="transactionIndex")]
pub transaction_index: OptionalValue<U256>,
/// Sender
pub from: Address,
/// Recipient
pub to: OptionalValue<Address>,
/// Transfered value
pub value: U256,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: U256,
/// Gas
pub gas: U256,
/// Data
pub input: Bytes
}

View File

@@ -0,0 +1,139 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! `TransactionRequest` type
use util::hash::Address;
use util::numbers::U256;
use v1::types::bytes::Bytes;
/// Transaction request coming from RPC
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Deserialize)]
pub struct TransactionRequest {
/// Sender
pub from: Address,
/// Recipient
pub to: Option<Address>,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: Option<U256>,
/// Gas
pub gas: Option<U256>,
/// Value of transaction in wei
pub value: Option<U256>,
/// Additional data sent with transaction
pub data: Option<Bytes>,
/// Transaction's nonce
pub nonce: Option<U256>,
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use serde_json;
use util::numbers::{U256};
use util::hash::Address;
use v1::types::bytes::Bytes;
use super::*;
#[test]
fn transaction_request_deserialize() {
let s = r#"{
"from":"0x0000000000000000000000000000000000000001",
"to":"0x0000000000000000000000000000000000000002",
"gasPrice":"0x1",
"gas":"0x2",
"value":"0x3",
"data":"0x123456",
"nonce":"0x4"
}"#;
let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, TransactionRequest {
from: Address::from(1),
to: Some(Address::from(2)),
gas_price: Some(U256::from(1)),
gas: Some(U256::from(2)),
value: Some(U256::from(3)),
data: Some(Bytes::new(vec![0x12, 0x34, 0x56])),
nonce: Some(U256::from(4)),
});
}
#[test]
fn transaction_request_deserialize2() {
let s = r#"{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}"#;
let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, TransactionRequest {
from: Address::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap(),
to: Some(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
gas_price: Some(U256::from_str("9184e72a000").unwrap()),
gas: Some(U256::from_str("76c0").unwrap()),
value: Some(U256::from_str("9184e72a").unwrap()),
data: Some(Bytes::new("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap())),
nonce: None
});
}
#[test]
fn transaction_request_deserialize_empty() {
let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#;
let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, TransactionRequest {
from: Address::from(1),
to: None,
gas_price: None,
gas: None,
value: None,
data: None,
nonce: None,
});
}
#[test]
fn transaction_request_deserialize_test() {
let s = r#"{
"from":"0xb5f7502a2807cb23615c7456055e1d65b2508625",
"to":"0x895d32f2db7d01ebb50053f9e48aacf26584fe40",
"data":"0x8595bab1",
"gas":"0x2fd618",
"gasPrice":"0x0ba43b7400"
}"#;
let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, TransactionRequest {
from: Address::from_str("b5f7502a2807cb23615c7456055e1d65b2508625").unwrap(),
to: Some(Address::from_str("895d32f2db7d01ebb50053f9e48aacf26584fe40").unwrap()),
gas_price: Some(U256::from_str("0ba43b7400").unwrap()),
gas: Some(U256::from_str("2fd618").unwrap()),
value: None,
data: Some(Bytes::new(vec![0x85, 0x95, 0xba, 0xb1])),
nonce: None,
});
}
}