Skip to content

Commit

Permalink
provide block rpc
Browse files Browse the repository at this point in the history
  • Loading branch information
baichuan3 committed Dec 5, 2024
1 parent 8d05c5d commit b5ba1d7
Show file tree
Hide file tree
Showing 19 changed files with 286 additions and 25 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/rooch-proposer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ metrics = { workspace = true }
rooch-config = { workspace = true }
rooch-types = { workspace = true }
rooch-store = { workspace = true }
serde = { version = "1.0.197", features = ["derive"] }
13 changes: 0 additions & 13 deletions crates/rooch-proposer/src/actor/messages.rs

This file was deleted.

1 change: 0 additions & 1 deletion crates/rooch-proposer/src/actor/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

pub mod messages;
pub mod proposer;
27 changes: 26 additions & 1 deletion crates/rooch-proposer/src/actor/proposer.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use super::messages::ProposeBlock;
use crate::messages::{GetBlocksMessage, GetLastestBlockNumberMessage, ProposeBlock};
use crate::metrics::ProposerMetrics;
use crate::scc::StateCommitmentChain;
use anyhow::Result;
use async_trait::async_trait;
use coerce::actor::{context::ActorContext, message::Handler, Actor};
use moveos_store::MoveOSStore;
use prometheus::Registry;
use rooch_config::proposer_config::ProposerConfig;
use rooch_store::proposer_store::ProposerStore;
use rooch_store::RoochStore;
use rooch_types::block::Block;
use rooch_types::crypto::RoochKeyPair;
use std::sync::Arc;

Expand Down Expand Up @@ -99,3 +101,26 @@ impl Handler<ProposeBlock> for ProposerActor {
}
}
}

#[async_trait]
impl Handler<GetBlocksMessage> for ProposerActor {
async fn handle(
&mut self,
msg: GetBlocksMessage,
_ctx: &mut ActorContext,
) -> Result<Vec<Option<Block>>> {
let GetBlocksMessage { block_numbers } = msg;
self.scc.get_blocks(block_numbers)
}
}

#[async_trait]
impl Handler<GetLastestBlockNumberMessage> for ProposerActor {
async fn handle(
&mut self,
_msg: GetLastestBlockNumberMessage,
_ctx: &mut ActorContext,
) -> Result<u128> {
Ok(self.scc.lastest_proposed_block_number())
}
}
2 changes: 2 additions & 0 deletions crates/rooch-proposer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

pub mod actor;
pub mod messages;
pub mod metrics;
pub mod proxy;
pub mod scc;
32 changes: 32 additions & 0 deletions crates/rooch-proposer/src/messages.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use coerce::actor::{message::Message, scheduler::timer::TimerTick};
use rooch_types::block::Block;
use serde::{Deserialize, Serialize};

#[derive(Clone)]
pub struct ProposeBlock {}

impl Message for ProposeBlock {
type Result = ();
}

impl TimerTick for ProposeBlock {}

#[derive(Debug, Serialize, Deserialize)]
pub struct GetBlocksMessage {
pub block_numbers: Vec<u128>,
}

impl Message for GetBlocksMessage {
type Result = Result<Vec<Option<Block>>>;
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GetLastestBlockNumberMessage {}

impl Message for GetLastestBlockNumberMessage {
type Result = Result<u128>;
}
27 changes: 27 additions & 0 deletions crates/rooch-proposer/src/proxy/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use crate::actor::proposer::ProposerActor;
use crate::messages::{GetBlocksMessage, GetLastestBlockNumberMessage};
use anyhow::Result;
use coerce::actor::ActorRef;
use rooch_types::block::Block;

#[derive(Clone)]
pub struct ProposerProxy {
pub actor: ActorRef<ProposerActor>,
}

impl ProposerProxy {
pub fn new(actor: ActorRef<ProposerActor>) -> Self {
Self { actor }
}

pub async fn get_blocks(&self, block_numbers: Vec<u128>) -> Result<Vec<Option<Block>>> {
self.actor.send(GetBlocksMessage { block_numbers }).await?
}

pub async fn latest_block_number(&self) -> Result<u128> {
self.actor.send(GetLastestBlockNumberMessage {}).await?
}
}
40 changes: 40 additions & 0 deletions crates/rooch-proposer/src/scc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,46 @@ impl StateCommitmentChain {
prev_tx_accumulator_root,
tx_accumulator_root,
tx_state_root,
0,
))
}
None => Err(anyhow::anyhow!("No block has been proposed")),
}
}

// TODO fill Block fields when necessary
// Skip check when multi get blocks, distinguish with get block by signle
pub fn get_blocks(&self, block_number: Vec<u128>) -> anyhow::Result<Vec<Option<Block>>> {
let block_da_submit_states = self.rooch_store.try_get_block_states(block_number)?;
block_da_submit_states
.into_iter()
.map(
|block_da_submit_state_opt| match block_da_submit_state_opt {
Some(block_da_submit_state) => {
if !block_da_submit_state.done {
return Err(anyhow::anyhow!(
"block: {} is not done but proposed. database is inconsistent",
block_da_submit_state.block_range.block_number,
));
}
let block_range = block_da_submit_state.block_range;
let batch_size = block_range.tx_order_end - block_range.tx_order_start + 1;
Ok(Some(Block::new(
block_range.block_number,
batch_size,
block_da_submit_state.batch_hash,
H256::zero(),
H256::zero(),
H256::zero(),
0,
)))
}
None => Ok(None),
},
)
.collect::<Result<Vec<_>, _>>()
}

// get_roots returns the tx accumulator root & state root of the transaction with the given tx_order
fn get_roots(&self, tx_order: u64) -> anyhow::Result<(H256, H256)> {
let mut ledger_tx = get_ledger_tx(self.rooch_store.clone(), tx_order)?;
Expand Down Expand Up @@ -138,6 +172,8 @@ impl StateCommitmentChain {
prev_tx_accumulator_root,
tx_accumulator_root,
tx_state_root,
// TODO generate block timestamp
0,
);
self.last_proposed_block_number = Some(block_number);
self.last_proposed_block_accumulator_root = tx_accumulator_root;
Expand Down Expand Up @@ -173,6 +209,10 @@ impl StateCommitmentChain {
}
}
}

pub fn lastest_proposed_block_number(&self) -> u128 {
self.last_proposed_block_number.unwrap_or(0)
}
}

fn get_ledger_tx(rooch_store: RoochStore, tx_order: u64) -> anyhow::Result<LedgerTransaction> {
Expand Down
14 changes: 11 additions & 3 deletions crates/rooch-rpc-api/src/api/rooch_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use crate::jsonrpc_types::event_view::{EventFilterView, IndexerEventIDView};
use crate::jsonrpc_types::repair_view::{RepairIndexerParamsView, RepairIndexerTypeView};
use crate::jsonrpc_types::transaction_view::{TransactionFilterView, TransactionWithInfoView};
use crate::jsonrpc_types::{
AccessPathView, AnnotatedFunctionResultView, BalanceInfoPageView, BytesView, EventOptions,
EventPageView, ExecuteTransactionResponseView, FieldKeyView, FunctionCallView, H256View,
IndexerEventPageView, IndexerObjectStatePageView, IndexerStateIDView, ModuleABIView,
AccessPathView, AnnotatedFunctionResultView, BalanceInfoPageView, BlockPageView, BytesView,
EventOptions, EventPageView, ExecuteTransactionResponseView, FieldKeyView, FunctionCallView,
H256View, IndexerEventPageView, IndexerObjectStatePageView, IndexerStateIDView, ModuleABIView,
ObjectIDVecView, ObjectIDView, ObjectStateFilterView, ObjectStateView, QueryOptions,
RoochAddressView, StateChangeSetPageView, StateOptions, StatePageView, StrView, StructTagView,
SyncStateFilterView, TransactionWithInfoPageView, TxOptions,
Expand Down Expand Up @@ -214,4 +214,12 @@ pub trait RoochAPI {
/// Get the chain and service status
#[method(name = "status")]
async fn status(&self) -> RpcResult<Status>;

#[method(name = "getBlocksByNumber")]
async fn get_blocks_by_number(
&self,
cursor: Option<StrView<u128>>,
limit: Option<StrView<u64>>,
descending_order: Option<bool>,
) -> RpcResult<BlockPageView>;
}
35 changes: 35 additions & 0 deletions crates/rooch-rpc-api/src/jsonrpc_types/block_view.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use crate::jsonrpc_types::{H256View, StrView};
use rooch_types::block::Block;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BlockView {
/// The index if the block
pub block_number: StrView<u128>,
/// How many transactions in the block
// pub batch_size: StrView<u64>,
/// The hash of the block, made by DA
pub block_hash: H256View,
/// The previous tx accumulator root of the block
// pub prev_tx_accumulator_root: H256View,
/// The tx accumulator root after the last transaction append to the accumulator
// pub tx_accumulator_root: H256View,
/// The last transaction's state root
// pub state_root: H256View,
/// the block generate timestamp
pub time: StrView<u64>,
}

impl From<Block> for BlockView {
fn from(block: Block) -> Self {
Self {
block_number: block.block_number.into(),
block_hash: block.block_hash.into(),
time: block.time.into(),
}
}
}
1 change: 1 addition & 0 deletions crates/rooch-rpc-api/src/jsonrpc_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub mod json_to_table_display;
pub mod transaction_view;

pub mod address;
pub mod block_view;
pub mod btc;
pub mod repair_view;

Expand Down
3 changes: 3 additions & 0 deletions crates/rooch-rpc-api/src/jsonrpc_types/rooch_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use super::event_view::IndexerEventIDView;
use super::{HumanReadableDisplay, IndexerStateIDView, StateChangeSetWithTxOrderView};
use crate::jsonrpc_types::account_view::BalanceInfoView;
use crate::jsonrpc_types::block_view::BlockView;
use crate::jsonrpc_types::btc::ord::InscriptionStateView;
use crate::jsonrpc_types::btc::utxo::UTXOStateView;
use crate::jsonrpc_types::event_view::{EventView, IndexerEventView};
Expand Down Expand Up @@ -31,6 +32,8 @@ pub type UTXOPageView = PageView<UTXOStateView, IndexerStateIDView>;
pub type InscriptionPageView = PageView<InscriptionStateView, IndexerStateIDView>;
pub type StateChangeSetPageView = PageView<StateChangeSetWithTxOrderView, StrView<u64>>;

pub type BlockPageView = PageView<BlockView, StrView<u128>>;

/// `next_cursor` points to the last item in the page;
/// Reading with `next_cursor` will start from the next item after `next_cursor` if
/// `next_cursor` is `Some`, otherwise it will start from the first item.
Expand Down
5 changes: 4 additions & 1 deletion crates/rooch-rpc-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ use rooch_indexer::actor::reader_indexer::IndexerReaderActor;
use rooch_indexer::proxy::IndexerProxy;
use rooch_pipeline_processor::actor::processor::PipelineProcessorActor;
use rooch_pipeline_processor::proxy::PipelineProcessorProxy;
use rooch_proposer::actor::messages::ProposeBlock;
use rooch_proposer::actor::proposer::ProposerActor;
use rooch_proposer::messages::ProposeBlock;
use rooch_proposer::proxy::ProposerProxy;
use rooch_relayer::actor::messages::RelayTick;
use rooch_relayer::actor::relayer::RelayerActor;
use rooch_rpc_api::api::RoochRpcModule;
Expand Down Expand Up @@ -328,6 +329,7 @@ pub async fn run_start_server(opt: RoochOpt, server_opt: ServerOpt) -> Result<Se
)?
.into_actor(Some("Proposer"), &actor_system)
.await?;
let proposer_proxy = ProposerProxy::new(proposer.clone().into());
let block_propose_duration_in_seconds: u64 =
opt.proposer.interval.unwrap_or(PROPOSER_CHECK_INTERVAL);
let mut timers = vec![];
Expand Down Expand Up @@ -415,6 +417,7 @@ pub async fn run_start_server(opt: RoochOpt, server_opt: ServerOpt) -> Result<Se
network.genesis_config.bitcoin_network,
executor_proxy,
sequencer_proxy,
proposer_proxy,
indexer_proxy,
processor_proxy,
bitcoin_client_proxy,
Expand Down
Loading

0 comments on commit b5ba1d7

Please sign in to comment.