Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rpc: event filter now support filter by address or typetag #2682

Merged
merged 1 commit into from
Jul 9, 2021
Merged
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
10 changes: 10 additions & 0 deletions chain/tests/test_block_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ fn test_chain_filter_events() {
from_block: 1,
to_block: 5,
event_keys: vec![evt_key],
addrs: vec![],
type_tags: vec![],
limit: None,
reverse: false,
};
Expand All @@ -45,6 +47,8 @@ fn test_chain_filter_events() {
from_block: 1,
to_block: 10,
event_keys: vec![EventKey::new_from_address(&genesis_address(), 4)],
addrs: vec![],
type_tags: vec![],
limit: Some(5),
reverse: false,
};
Expand All @@ -59,6 +63,8 @@ fn test_chain_filter_events() {
from_block: 1,
to_block: 10,
event_keys: vec![EventKey::new_from_address(&genesis_address(), 4)],
addrs: vec![],
type_tags: vec![],
limit: Some(5),
reverse: true,
};
Expand All @@ -75,6 +81,8 @@ fn test_chain_filter_events() {
from_block: 0,
to_block: 10,
event_keys: vec![EventKey::new_from_address(&genesis_address(), 4)],
addrs: vec![],
type_tags: vec![],
limit: Some(20),
reverse: true,
};
Expand All @@ -91,6 +99,8 @@ fn test_chain_filter_events() {
from_block: 0,
to_block: 20,
event_keys: vec![EventKey::new_from_address(&genesis_address(), 4)],
addrs: vec![],
type_tags: vec![],
limit: Some(20),
reverse: true,
};
Expand Down
14 changes: 10 additions & 4 deletions cmd/indexer/src/block_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,11 @@ impl BlockClient {

let events: Vec<TransactionEventView> = self
.node_client
.get_events_by_txn_hash(txn_info.transaction_hash)
.await?;
.get_events_by_txn_hash(txn_info.transaction_hash, None)
.await?
.into_iter()
.map(|d| d.event)
.collect();
txns_data.push(TransactionData {
info: txn_info.into(),
block_metadata: txn.block_metadata,
Expand All @@ -74,7 +77,7 @@ impl BlockClient {
let fetch_events_tasks = txn_infos
.iter()
.map(|txn_info| txn_info.transaction_hash)
.map(|txn_hash| self.node_client.get_events_by_txn_hash(txn_hash));
.map(|txn_hash| self.node_client.get_events_by_txn_hash(txn_hash, None));

let events = futures_util::future::try_join_all(fetch_events_tasks).await?;

Expand All @@ -83,7 +86,10 @@ impl BlockClient {
{
txns_data.push(TransactionData {
info: txn_info.into(),
events: events.iter().map(|event| event.clone().into()).collect(),
events: events
.iter()
.map(|event| event.event.clone().into())
.collect(),
user_transaction: Some(user_txn),
block_metadata: None,
timestamp: block.header.timestamp.0,
Expand Down
8 changes: 4 additions & 4 deletions cmd/starcoin/src/chain/get_events_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
// SPDX-License-Identifier: Apache-2.0

use crate::cli_state::CliState;
use crate::view::EventView;
use crate::StarcoinOpt;
use anyhow::Result;
use scmd::{CommandAction, ExecContext};
use starcoin_crypto::HashValue;
use starcoin_rpc_api::chain::{GetEventOption, GetEventResponse};
use structopt::StructOpt;

/// Get chain's events by txn hash
Expand All @@ -24,16 +24,16 @@ impl CommandAction for GetEventsCommand {
type State = CliState;
type GlobalOpt = StarcoinOpt;
type Opt = GetEventsOpt;
type ReturnItem = Vec<EventView>;
type ReturnItem = Vec<GetEventResponse>;

fn run(
&self,
ctx: &ExecContext<Self::State, Self::GlobalOpt, Self::Opt>,
) -> Result<Self::ReturnItem> {
let client = ctx.state().client();
let opt = ctx.opt();
let events = client.chain_get_events_by_txn_hash(opt.hash)?;
let events: Vec<EventView> = events.into_iter().map(|e| e.into()).collect::<Vec<_>>();
let events =
client.chain_get_events_by_txn_hash(opt.hash, Some(GetEventOption { decode: true }))?;
Ok(events)
}
}
5 changes: 4 additions & 1 deletion cmd/starcoin/src/cli_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use starcoin_account_api::AccountInfo;
use starcoin_config::{ChainNetworkID, DataDirPath};
use starcoin_crypto::HashValue;
use starcoin_node::NodeHandle;
use starcoin_rpc_api::chain::GetEventOption;
use starcoin_rpc_api::types::{
DryRunOutputView as ServerDryRunOutputView, TransactionInfoView, TransactionStatusView,
};
Expand Down Expand Up @@ -260,7 +261,9 @@ impl CliState {
let (_block, txn_info) = self.watch_txn(txn_hash)?;
output.txn_status = Some(explained_status);
output.txn_info = txn_info;
let events = self.client.chain_get_events_by_txn_hash(txn_hash)?;
let events = self
.client
.chain_get_events_by_txn_hash(txn_hash, Some(GetEventOption { decode: true }))?;
output.events = Some(events);
}
Ok(ExecuteResultView::Run(output))
Expand Down
4 changes: 3 additions & 1 deletion cmd/starcoin/src/dev/subscribe_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ impl CommandAction for SubscribeEventCommand {
let filter = EventFilter {
from_block: ctx.opt().from_block,
to_block: ctx.opt().to_block,
event_keys: ctx.opt().event_key.clone().unwrap_or_default(),
event_keys: ctx.opt().event_key.clone(),
addrs: None,
type_tags: None,
limit: ctx.opt().limit,
};

Expand Down
3 changes: 2 additions & 1 deletion cmd/starcoin/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use anyhow::format_err;
use serde::{Deserialize, Serialize};
use starcoin_account_api::AccountInfo;
use starcoin_crypto::HashValue;
use starcoin_rpc_api::chain::GetEventResponse;
pub use starcoin_rpc_api::types::TransactionOutputView;
use starcoin_rpc_api::types::{
StrView, TransactionEventView, TransactionInfoView, VmStatusExplainView,
Expand Down Expand Up @@ -279,7 +280,7 @@ pub struct ExecutionOutputView {
pub txn_hash: HashValue,
pub txn_info: Option<TransactionInfoView>,
pub txn_status: Option<VmStatusExplainView>,
pub events: Option<Vec<TransactionEventView>>,
pub events: Option<Vec<GetEventResponse>>,
}

impl ExecutionOutputView {
Expand Down
7 changes: 6 additions & 1 deletion node/src/rpc_service_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,12 @@ impl ServiceFactory<RpcService> for RpcServiceFactory {
let chain_api = ctx
.service_ref_opt::<ChainReaderService>()?
.map(|service_ref| {
ChainRpcImpl::new(config.clone(), genesis.block().id(), service_ref.clone())
ChainRpcImpl::new(
config.clone(),
genesis.block().id(),
storage.clone(),
service_ref.clone(),
)
});
let txpool_service = ctx.get_shared::<TxPoolService>()?;
let txpool_api = Some(TxPoolRpcImpl::new(txpool_service.clone()));
Expand Down
25 changes: 22 additions & 3 deletions rpc/api/src/chain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ pub use self::gen_client::Client as ChainClient;
use crate::types::pubsub::EventFilter;
use crate::types::{
BlockHeaderView, BlockSummaryView, BlockView, ChainId, ChainInfoView, EpochUncleSummaryView,
TransactionEventView, TransactionInfoView, TransactionView,
MoveValueView, TransactionEventView, TransactionInfoView, TransactionView,
};
use crate::FutureResult;
use jsonrpc_core::Result;
use jsonrpc_derive::rpc;
use serde::{Deserialize, Serialize};
use starcoin_crypto::HashValue;
use starcoin_types::block::{BlockInfo, BlockNumber};
use starcoin_vm_types::on_chain_resource::{EpochInfo, GlobalTimeOnChain};
Expand Down Expand Up @@ -64,10 +65,15 @@ pub trait ChainApi {
fn get_events_by_txn_hash(
&self,
txn_hash: HashValue,
) -> FutureResult<Vec<TransactionEventView>>;
option: Option<GetEventOption>,
) -> FutureResult<Vec<GetEventResponse>>;

#[rpc(name = "chain.get_events")]
fn get_events(&self, filter: EventFilter) -> FutureResult<Vec<TransactionEventView>>;
fn get_events(
&self,
filter: EventFilter,
option: Option<GetEventOption>,
) -> FutureResult<Vec<GetEventResponse>>;

/// Get current epoch info.
#[rpc(name = "chain.epoch")]
Expand Down Expand Up @@ -99,3 +105,16 @@ pub trait ChainApi {
number: BlockNumber,
) -> FutureResult<EpochUncleSummaryView>;
}

#[derive(Copy, Clone, Default, Serialize, Deserialize)]
pub struct GetEventOption {
#[serde(default)]
pub decode: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GetEventResponse {
pub decode_event_data: Option<MoveValueView>,
#[serde(flatten)]
pub event: TransactionEventView,
}
6 changes: 5 additions & 1 deletion rpc/api/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ fn value_to_json(origin: AnnotatedMoveValue) -> serde_json::Value {
AnnotatedMoveValue::Bool(v) => Value::Bool(v),
AnnotatedMoveValue::Address(v) => Value::String(v.to_string()),
AnnotatedMoveValue::Vector(v) => Value::Array(v.into_iter().map(value_to_json).collect()),
AnnotatedMoveValue::Bytes(v) => Value::String(format!("0x{}", hex::encode(&v))), // encode bytes to hex string.
// try bytes to string, or else to hex string.
AnnotatedMoveValue::Bytes(v) => match String::from_utf8(v) {
Ok(s) => Value::String(s),
Err(e) => Value::String(format!("0x{}", hex::encode(e.as_bytes()))),
},
AnnotatedMoveValue::Struct(v) => struct_to_json(v),
}
}
Expand Down
25 changes: 22 additions & 3 deletions rpc/api/src/types/pubsub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
// SPDX-License-Identifier: Apache-2.0

use crate::errors;
use crate::types::{BlockView, TransactionEventView};
use crate::types::{BlockView, TransactionEventView, TypeTagView};
use jsonrpc_core::error::Error as JsonRpcError;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{from_value, Value};
use starcoin_crypto::HashValue;
use starcoin_types::account_address::AccountAddress;
use starcoin_types::event::EventKey;
use starcoin_types::filter::Filter;
use starcoin_types::system_events::MintBlockEvent;
Expand Down Expand Up @@ -99,8 +100,19 @@ pub struct EventFilter {
#[serde(default)]
pub to_block: Option<u64>,
/// Event keys
/// /// if `event_keys` is empty, event always match.
#[serde(default)]
pub event_keys: Vec<EventKey>,
pub event_keys: Option<Vec<EventKey>>,
/// Account addresses which event comes from.
/// match if event belongs to any og the addresses.
/// if `addrs` is empty, event always match.
#[serde(default)]
pub addrs: Option<Vec<AccountAddress>>,
/// type tags of the event.
/// match if the event is any type of the type tags.
/// /// if `type_tags` is empty, event always match.
#[serde(default)]
pub type_tags: Option<Vec<TypeTagView>>,
/// Limit: from latest to oldest
#[serde(default)]
pub limit: Option<usize>,
Expand All @@ -122,7 +134,14 @@ impl TryInto<Filter> for EventFilter {
Ok(Filter {
from_block: self.from_block.unwrap_or(0),
to_block: self.to_block.unwrap_or(std::u64::MAX),
event_keys: self.event_keys,
event_keys: self.event_keys.unwrap_or_default(),
addrs: self.addrs.unwrap_or_default(),
type_tags: self
.type_tags
.unwrap_or_default()
.into_iter()
.map(|t| t.0)
.collect(),
limit: self.limit,
reverse: true,
})
Expand Down
6 changes: 4 additions & 2 deletions rpc/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use serde_json::Value;
use starcoin_account_api::AccountInfo;
use starcoin_crypto::HashValue;
use starcoin_logger::{prelude::*, LogPattern};
use starcoin_rpc_api::chain::{GetEventOption, GetEventResponse};
use starcoin_rpc_api::node::NodeInfo;
use starcoin_rpc_api::service::RpcAsyncService;
use starcoin_rpc_api::types::pubsub::EventFilter;
Expand Down Expand Up @@ -626,8 +627,9 @@ impl RpcClient {
pub fn chain_get_events_by_txn_hash(
&self,
txn_hash: HashValue,
) -> anyhow::Result<Vec<TransactionEventView>> {
self.call_rpc_blocking(|inner| inner.chain_client.get_events_by_txn_hash(txn_hash))
option: Option<GetEventOption>,
) -> anyhow::Result<Vec<GetEventResponse>> {
self.call_rpc_blocking(|inner| inner.chain_client.get_events_by_txn_hash(txn_hash, option))
.map_err(map_err)
}

Expand Down
Loading