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

feat: implement test mode #224

Merged
merged 4 commits into from Jun 23, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 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/block-producer/Cargo.toml
Expand Up @@ -45,3 +45,4 @@ smol = "1.2.5"
lazy_static = "1.4"
sqlx = { version = "0.5", features = [ "runtime-async-std-native-tls", "postgres", "sqlite", "chrono", "decimal" ] }
hex = "0.4"
async-trait = "0.1"
1 change: 1 addition & 0 deletions crates/block-producer/src/lib.rs
Expand Up @@ -6,6 +6,7 @@ pub mod produce_block;
pub mod rpc_client;
pub mod runner;
pub mod stake;
pub mod test_mode_control;
pub mod transaction_skeleton;
pub mod types;
pub mod utils;
Expand Down
44 changes: 33 additions & 11 deletions crates/block-producer/src/runner.rs
@@ -1,20 +1,21 @@
use crate::{
block_producer::BlockProducer, poller::ChainUpdater, rpc_client::RPCClient, types::ChainEvent,
utils::CKBGenesisInfo,
block_producer::BlockProducer, poller::ChainUpdater, rpc_client::RPCClient,
test_mode_control::TestModeControl, types::ChainEvent, utils::CKBGenesisInfo,
};
use anyhow::{anyhow, Context, Result};
use async_jsonrpc_client::HttpClient;
use futures::{executor::block_on, select, FutureExt};
use gw_chain::chain::Chain;
use gw_common::H256;
use gw_config::Config;
use gw_config::{Config, TestMode};
use gw_db::{config::Config as DBConfig, schema::COLUMNS, RocksDB};
use gw_generator::{
account_lock_manage::{secp256k1::Secp256k1Eth, AccountLockManage},
backend_manage::BackendManage,
genesis::init_genesis,
Generator, RollupContext,
};
use gw_jsonrpc_types::test_mode::TestModePayload;
use gw_mem_pool::pool::MemPool;
use gw_rpc_server::{registry::Registry, server::start_jsonrpc_server};
use gw_store::Store;
Expand All @@ -40,6 +41,7 @@ async fn poll_loop(
rpc_client: RPCClient,
chain_updater: ChainUpdater,
block_producer: BlockProducer,
test_mode_control: TestModeControl,
poll_interval: Duration,
) -> Result<()> {
struct Inner {
Expand Down Expand Up @@ -99,13 +101,21 @@ async fn poll_loop(
err
);
}
if let Err(err) = inner.block_producer.handle_event(event.clone()).await {
log::error!(
"Error occured when polling block_producer, event: {:?}, error: {}",
event,
err
);

// TODO: implement test mode challenge control
if TestMode::Disable == test_mode_control.mode()
|| TestMode::Enable == test_mode_control.mode()
&& Some(TestModePayload::None) == test_mode_control.take_payload().await
{
if let Err(err) = inner.block_producer.handle_event(event.clone()).await {
log::error!(
"Error occured when polling block_producer, event: {:?}, error: {}",
event,
err
);
}
}

// }
// })
// .detach();
Expand Down Expand Up @@ -215,7 +225,15 @@ pub fn run(config: Config) -> Result<()> {
));

// RPC registry
let rpc_registry = Registry::new(store.clone(), mem_pool.clone(), generator.clone());
let test_mode_control =
TestModeControl::create(config.test_mode, rpc_client.clone(), &block_producer_config)?;
let rpc_registry = Registry::new(
store.clone(),
mem_pool.clone(),
generator.clone(),
config.test_mode,
test_mode_control.clone(),
);

// create web3 indexer
let web3_indexer = match config.web3_indexer {
Expand Down Expand Up @@ -301,10 +319,14 @@ pub fn run(config: Config) -> Result<()> {
log::info!("Rollup config hash: {}", rollup_config_hash);
}

if TestMode::Enable == config.test_mode {
log::info!("Test mode enabled!!!");
}

smol::block_on(async {
select! {
_ = ctrl_c.recv().fuse() => log::info!("Exiting..."),
e = poll_loop(rpc_client, chain_updater, block_producer, Duration::from_secs(3)).fuse() => {
e = poll_loop(rpc_client, chain_updater, block_producer, test_mode_control ,Duration::from_secs(3)).fuse() => {
log::error!("Error in main poll loop: {:?}", e);
}
e = start_jsonrpc_server(rpc_address, rpc_registry).fuse() => {
Expand Down
116 changes: 116 additions & 0 deletions crates/block-producer/src/test_mode_control.rs
@@ -0,0 +1,116 @@
use crate::poa::{PoA, ShouldIssueBlock};
use crate::rpc_client::RPCClient;
use crate::types::InputCellInfo;
use crate::wallet::Wallet;

use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use ckb_types::prelude::{Builder, Entity};
use gw_common::H256;
use gw_config::{BlockProducerConfig, TestMode};
use gw_jsonrpc_types::{
godwoken::GlobalState,
test_mode::{ShouldProduceBlock, TestModePayload},
};
use gw_rpc_server::registry::TestModeRPC;
use gw_types::{packed::CellInput, prelude::Unpack};
use smol::lock::Mutex;

use std::sync::Arc;

#[derive(Clone)]
pub struct TestModeControl {
mode: TestMode,
payload: Arc<Mutex<Option<TestModePayload>>>,
rpc_client: RPCClient,
poa: Arc<Mutex<PoA>>,
}

impl TestModeControl {
pub fn create(
mode: TestMode,
rpc_client: RPCClient,
config: &BlockProducerConfig,
) -> Result<Self> {
let wallet = Wallet::from_config(&config.wallet_config).with_context(|| "init wallet")?;
let poa = PoA::new(
rpc_client.clone(),
wallet.lock_script().to_owned(),
config.poa_lock_dep.clone().into(),
config.poa_state_dep.clone().into(),
);

Ok(TestModeControl {
mode,
payload: Arc::new(Mutex::new(None)),
rpc_client,
poa: Arc::new(Mutex::new(poa)),
})
}

pub fn mode(&self) -> TestMode {
self.mode
}

pub async fn get_payload(&self) -> Option<TestModePayload> {
self.payload.lock().await.to_owned()
}

pub async fn take_payload(&self) -> Option<TestModePayload> {
self.payload.lock().await.take()
}
}

#[async_trait]
impl TestModeRPC for TestModeControl {
async fn get_global_state(&self) -> Result<GlobalState> {
let rollup_cell = {
let opt = self.rpc_client.query_rollup_cell().await?;
opt.ok_or_else(|| anyhow!("rollup cell not found"))?
};

let global_state = gw_types::packed::GlobalState::from_slice(&rollup_cell.data)
.map_err(|_| anyhow!("parse rollup up global state"))?;

Ok(global_state.into())
}

async fn produce_block(&self, payload: TestModePayload) -> Result<()> {
*self.payload.lock().await = Some(payload);

Ok(())
}

async fn should_produce_block(&self) -> Result<ShouldProduceBlock> {
let rollup_cell = {
let opt = self.rpc_client.query_rollup_cell().await?;
opt.ok_or_else(|| anyhow!("rollup cell not found"))?
};

let tip_hash: H256 = {
let l1_tip_hash_number = self.rpc_client.get_tip().await?;
let tip_hash: [u8; 32] = l1_tip_hash_number.block_hash().unpack();
tip_hash.into()
};

let ret = {
let median_time = self.rpc_client.get_block_median_time(tip_hash).await?;
let poa_cell_input = InputCellInfo {
input: CellInput::new_builder()
.previous_output(rollup_cell.out_point.clone())
.build(),
cell: rollup_cell.clone(),
};

let mut poa = self.poa.lock().await;
poa.should_issue_next_block(median_time, &poa_cell_input)
.await?
};

Ok(match ret {
ShouldIssueBlock::Yes => ShouldProduceBlock::Yes,
ShouldIssueBlock::YesIfFull => ShouldProduceBlock::YesIfFull,
ShouldIssueBlock::No => ShouldProduceBlock::No,
})
}
}
14 changes: 14 additions & 0 deletions crates/config/src/config.rs
Expand Up @@ -8,6 +8,7 @@ use std::path::PathBuf;

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
pub test_mode: TestMode,
pub backends: Vec<BackendConfig>,
pub store: StoreConfig,
pub genesis: GenesisConfig,
Expand Down Expand Up @@ -87,3 +88,16 @@ pub struct Web3IndexerConfig {
pub polyjuice_script_type_hash: H256,
pub eth_account_lock_hash: H256,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TestMode {
Enable,
Disable,
}

impl Default for TestMode {
fn default() -> Self {
TestMode::Disable
}
}
1 change: 1 addition & 0 deletions crates/jsonrpc-types/src/lib.rs
Expand Up @@ -2,3 +2,4 @@ pub mod blockchain;
pub mod godwoken;
// re-exports
pub use ckb_jsonrpc_types;
pub mod test_mode;
34 changes: 34 additions & 0 deletions crates/jsonrpc-types/src/test_mode.rs
@@ -0,0 +1,34 @@
use ckb_jsonrpc_types::{Uint32, Uint64};
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ShouldProduceBlock {
Yes,
YesIfFull,
No,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChallengeType {
TxExecution,
TxSignature,
WithdrawalSignature,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum TestModePayload {
None,
BadBlock {
target_index: Uint32,
target_type: ChallengeType,
},
Challenge {
block_number: Uint64,
target_index: Uint32,
target_type: ChallengeType,
},
WaitForChallengeMaturity,
}
1 change: 1 addition & 0 deletions crates/rpc-server/Cargo.toml
Expand Up @@ -39,3 +39,4 @@ serde_json = "1.0"
smol = "1.2.5"
tokio = { version = "1.0.1", default-features = false, features = ["rt-multi-thread"] }
bytes-v10 = { version = "1.0", package = "bytes" }
async-trait = "0.1"