Skip to content

Commit

Permalink
Merge branch 'master' into v2.0-testnet
Browse files Browse the repository at this point in the history
  • Loading branch information
peilun-conflux committed Jun 8, 2023
2 parents 4ab3f74 + ee99dd4 commit b945518
Show file tree
Hide file tree
Showing 77 changed files with 2,833 additions and 3,024 deletions.
17 changes: 17 additions & 0 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion blockgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,7 @@ impl BlockGenerator {
pub fn generate_custom_block_with_parent(
&self, parent_hash: H256, referee: Vec<H256>,
transactions: Vec<Arc<SignedTransaction>>, adaptive: bool,
maybe_custom: Option<Vec<Vec<u8>>>,
) -> Result<H256, String>
{
let consensus_graph = self.consensus_graph();
Expand All @@ -580,7 +581,7 @@ impl BlockGenerator {
&parent_hash,
)?;

let block = self.assemble_new_block_impl(
let mut block = self.assemble_new_block_impl(
parent_hash,
referee,
state_blame_info,
Expand All @@ -590,6 +591,9 @@ impl BlockGenerator {
Some(adaptive),
self.get_pos_reference(&parent_hash),
);
if let Some(custom) = maybe_custom {
block.block_header.set_custom(custom);
}

Ok(self.generate_block_impl(block))
}
Expand Down
10 changes: 10 additions & 0 deletions cfx_math/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
description = "Conflux math library"
homepage = "https://www.confluxnetwork.org"
license = "GPL-3.0"
name = "cfx-math"
version = "0.1.0"

[dependencies]
num = "0.2"
cfx-types = { path = "../cfx_types" }
61 changes: 61 additions & 0 deletions cfx_math/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
extern crate cfx_types;
extern crate num;

use cfx_types::U256;
use num::integer::Roots;

pub fn sqrt_u256(input: U256) -> U256 {
let bits = input.bits();
if bits <= 64 {
return input.as_u64().sqrt().into();
}

/************************************************************
** Step 1: pick the most significant 64 bits and estimate an
** approximate root.
************************************************************
**/
let significant_bits = 64 - bits % 2;
// The `rest_bits` must be even number.
let rest_bits = bits - significant_bits;
// The `input >> rest_bits` has `significant_bits`
let significant_word = (input >> rest_bits).as_u64();
// The `init_root` is slightly larger than the correct root.
let init_root =
U256::from(significant_word.sqrt() + 1u64) << (rest_bits / 2);

/******************************************************************
** Step 2: use the Newton's method to estimate the accurate value.
******************************************************************
**/
let mut root = init_root;
// Will iterate for at most 4 rounds.
while root * root > input {
root = (input / root + root) / 2;
}

root
}

pub fn power_two_fractional(ratio: u64, increase: bool, precision: u8) -> U256 {
assert!(precision <= 127);

let mut base = U256::one();
base <<= 254usize;

for i in 0..64u64 {
if ratio & (1 << i) != 0 {
if increase {
base <<= 1usize;
} else {
base >>= 1usize;
}
}
base = sqrt_u256(base);
base <<= 127usize;
}

base >>= (254 - precision) as usize;
// Computing error < 5.2 * 2 ^ -127
base
}
12 changes: 12 additions & 0 deletions changelogs/JSONRPC.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
# JSON-RPC CHANGELOG
## v2.2.5
- Use hex format for `pos` RPC data.
- Add RPC `pos_getLedgerInfoByBlockNumber` and `pos_getLedgerInfoByEpochAndRound` to get PoS ledger infos.
- Add `cfx_getEpochReceiptProofByTransaction` to get epoch receipt proof.
- Add `include_eth_recepits` option (default to false) for `cfx_getEpochReceipts`.

## v2.2.4
- Update the `Log` data format returned by cfx filter RPCs.
- Implement `trace_epoch` in the core space RPC endpoint to return traces of two spaces in an epoch.

## v2.2.3
- Add debug RPCs `cfx_getTransactionsByEpoch` and `cfx_getTransactionsByBlock` to get the original transactions in both spaces atomically. This is only available in the local RPC port and phantom transactions will not be returned.

## v2.2.2

Expand Down
12 changes: 12 additions & 0 deletions client/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use diem_types::term_state::{
};
use metrics::MetricsConfiguration;
use network::DiscoveryConfiguration;
use primitives::block_header::CIP112_TRANSITION_HEIGHT;
use txgen::TransactionGeneratorConfig;

use crate::rpc::{
Expand Down Expand Up @@ -156,6 +157,7 @@ build_config! {
(cip105_transition_number, (Option<u64>), Some(122700000))
(sigma_fix_transition_number, (Option<u64>), Some(125360000))
(cip107_transition_number, (Option<u64>), None)
(cip112_transition_height, (Option<u64>), None)
(referee_bound, (usize), REFEREE_DEFAULT_BOUND)
(params_dao_vote_period, (u64), DAO_PARAMETER_VOTE_PERIOD)
(timer_chain_beta, (u64), TIMER_CHAIN_DEFAULT_BETA)
Expand Down Expand Up @@ -322,6 +324,8 @@ build_config! {
(vrf_proposal_threshold, (U256), U256::from_str("1111111111111100000000000000000000000000000000000000000000000000").unwrap())
// Deferred epoch count before a confirmed epoch.
(pos_pivot_decision_defer_epoch_count, (u64), 50)
(cip113_pivot_decision_defer_epoch_count, (u64), 20)
(cip113_transition_height, (u64), u64::MAX)
(pos_reference_enable_height, (u64), 55665000)
(pos_initial_nodes_path, (String), "./pos_config/initial_nodes.json".to_string())
(pos_private_key_path, (String), "./pos_config/pos_key".to_string())
Expand Down Expand Up @@ -412,6 +416,10 @@ impl Configuration {
config.raw_conf.node_type = Some(NodeType::Light);
}

CIP112_TRANSITION_HEIGHT
.set(config.raw_conf.cip112_transition_height.unwrap_or(u64::MAX))
.expect("called once");

Ok(config)
}

Expand Down Expand Up @@ -580,6 +588,8 @@ impl Configuration {
enable_optimistic_execution,
enable_state_expose: self.raw_conf.enable_state_expose,
pos_pivot_decision_defer_epoch_count: self.raw_conf.pos_pivot_decision_defer_epoch_count,
cip113_pivot_decision_defer_epoch_count: self.raw_conf.cip113_pivot_decision_defer_epoch_count,
cip113_transition_height: self.raw_conf.cip113_transition_height,
debug_dump_dir_invalid_state_root: if self
.raw_conf
.debug_invalid_state_root
Expand Down Expand Up @@ -1279,6 +1289,8 @@ impl Configuration {
.raw_conf
.dao_vote_transition_height
.unwrap_or(non_genesis_default_transition_time);
params.transition_heights.cip112 =
*CIP112_TRANSITION_HEIGHT.get().expect("initialized");
params.params_dao_vote_period = self.raw_conf.params_dao_vote_period;

let mut base_block_rewards = BTreeMap::new();
Expand Down
34 changes: 21 additions & 13 deletions client/src/rpc/impls/cfx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ use crate::rpc::types::{
TokenSupplyInfo, VoteParamsInfo, WrapTransaction,
};
use blockgen::BlockGenerator;
use cfx_statedb::StateDbExt;
use cfx_statedb::{
global_params::{
AccumulateInterestRate, DistributablePoSInterest, InterestRate,
LastDistributeBlock, PowBaseReward, TotalPosStaking,
},
StateDbExt,
};
use cfx_types::{
Address, AddressSpaceUtil, BigEndianHash, Space, H256, H520, U128, U256,
U64,
Expand Down Expand Up @@ -409,7 +415,7 @@ impl RpcImpl {
.consensus
.get_state_db_by_epoch_number(epoch_num, "epoch_num")?;

Ok(state_db.get_annual_interest_rate()?.into())
Ok(state_db.get_global_param::<InterestRate>()?.into())
}

/// Returns accumulate interest rate of the given epoch
Expand All @@ -421,7 +427,9 @@ impl RpcImpl {
.consensus
.get_state_db_by_epoch_number(epoch_num, "epoch_num")?;

Ok(state_db.get_accumulate_interest_rate()?.into())
Ok(state_db
.get_global_param::<AccumulateInterestRate>()?
.into())
}

/// Returns accumulate interest rate of the given epoch
Expand All @@ -435,11 +443,11 @@ impl RpcImpl {

Ok(PoSEconomics {
total_pos_staking_tokens: state_db
.get_total_pos_staking_tokens()?,
.get_global_param::<TotalPosStaking>()?,
distributable_pos_interest: state_db
.get_distributable_pos_interest()?,
.get_global_param::<DistributablePoSInterest>()?,
last_distribute_block: U64::from(
state_db.get_last_distribute_block()?,
state_db.get_global_param::<LastDistributeBlock>()?.as_u64(),
),
})
}
Expand Down Expand Up @@ -1004,7 +1012,7 @@ impl RpcImpl {

fn generate_custom_block(
&self, parent_hash: H256, referee: Vec<H256>, raw_txs: Bytes,
adaptive: Option<bool>,
adaptive: Option<bool>, custom: Option<Vec<Bytes>>,
) -> RpcResult<H256>
{
info!("RPC Request: generate_custom_block()");
Expand All @@ -1016,6 +1024,7 @@ impl RpcImpl {
referee,
transactions,
adaptive.unwrap_or(false),
custom.map(|list| list.into_iter().map(|bytes| bytes.0).collect()),
)?)
}

Expand Down Expand Up @@ -1371,7 +1380,7 @@ impl RpcImpl {
let user_account = state_db.get_account(&account_addr)?;
let contract_account = state_db.get_account(&contract_addr)?;
let state = State::new(state_db)?;
let is_sponsored = state.check_commission_privilege(
let is_sponsored = state.check_contract_whitelist(
&contract_addr.address,
&account_addr.address,
)?;
Expand Down Expand Up @@ -1556,10 +1565,9 @@ impl RpcImpl {
let state_db = self
.consensus
.get_state_db_by_epoch_number(epoch, "epoch_num")?;
let interest_rate =
state_db.get_annual_interest_rate()? / U256::from(BLOCKS_PER_YEAR);
let pow_base_reward =
state_db.get_pow_base_reward()?.unwrap_or_default();
let interest_rate = state_db.get_global_param::<InterestRate>()?
/ U256::from(BLOCKS_PER_YEAR);
let pow_base_reward = state_db.get_global_param::<PowBaseReward>()?;

Ok(VoteParamsInfo {
pow_base_reward,
Expand Down Expand Up @@ -2188,7 +2196,7 @@ impl TestRpc for TestRpcImpl {
&self, raw_txs_without_data: Bytes, adaptive: Option<bool>, tx_data_len: Option<usize>)
-> JsonRpcResult<H256>;
fn generate_custom_block(
&self, parent_hash: H256, referee: Vec<H256>, raw_txs: Bytes, adaptive: Option<bool>)
&self, parent_hash: H256, referee: Vec<H256>, raw_txs: Bytes, adaptive: Option<bool>, custom: Option<Vec<Bytes>>)
-> JsonRpcResult<H256>;
fn get_pivot_chain_and_weight(&self, height_range: Option<(u64, u64)>) -> JsonRpcResult<Vec<(H256, U256)>>;
fn get_executed_info(&self, block_hash: H256) -> JsonRpcResult<(H256, H256)> ;
Expand Down
2 changes: 1 addition & 1 deletion client/src/rpc/impls/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1202,7 +1202,7 @@ impl TestRpc for TestRpcImpl {
fn generate_block_with_blame_info(&self, num_txs: usize, block_size_limit: usize, blame_info: BlameInfo) -> JsonRpcResult<H256>;
fn generate_block_with_fake_txs(&self, raw_txs_without_data: Bytes, adaptive: Option<bool>, tx_data_len: Option<usize>) -> JsonRpcResult<H256>;
fn generate_block_with_nonce_and_timestamp(&self, parent: H256, referees: Vec<H256>, raw: Bytes, nonce: U256, timestamp: u64, adaptive: bool) -> JsonRpcResult<H256>;
fn generate_custom_block(&self, parent_hash: H256, referee: Vec<H256>, raw_txs: Bytes, adaptive: Option<bool>) -> JsonRpcResult<H256>;
fn generate_custom_block(&self, parent_hash: H256, referee: Vec<H256>, raw_txs: Bytes, adaptive: Option<bool>, custom: Option<Vec<Bytes>>) -> JsonRpcResult<H256>;
fn generate_empty_blocks(&self, num_blocks: usize) -> JsonRpcResult<Vec<H256>>;
fn generate_fixed_block(&self, parent_hash: H256, referee: Vec<H256>, num_txs: usize, adaptive: bool, difficulty: Option<u64>, pos_reference: Option<H256>) -> JsonRpcResult<H256>;
fn generate_one_block_with_direct_txgen(&self, num_txs: usize, block_size_limit: usize, num_txs_simple: usize, num_txs_erc20: usize) -> JsonRpcResult<H256>;
Expand Down
2 changes: 1 addition & 1 deletion client/src/rpc/impls/pos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ impl PosHandler {
let call_request = CallRequest {
from: None,
to: Some(RpcAddress::try_from_h160(
*POS_REGISTER_CONTRACT_ADDRESS,
POS_REGISTER_CONTRACT_ADDRESS,
self.network_type,
)?),
gas_price: None,
Expand Down
14 changes: 7 additions & 7 deletions client/src/rpc/impls/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,10 @@ impl EthTrace for EthTraceHandler {
.map_err(|_| JsonRpcError::internal_error())?,
result: EthRes::None,
trace_address: vec![],
subtraces: subtraces.into(),
transaction_position: Some(idx.into()),
subtraces,
transaction_position: Some(idx),
transaction_hash: Some(tx_hash),
block_number: block_number.into(),
block_number,
block_hash,
// action and its result should have the same `valid`.
valid: action.valid,
Expand Down Expand Up @@ -418,10 +418,10 @@ impl EthTrace for EthTraceHandler {
.map_err(|_| JsonRpcError::internal_error())?,
result: EthRes::None,
trace_address: vec![],
subtraces: subtraces.into(),
transaction_position: Some(id.into()),
subtraces,
transaction_position: Some(id),
transaction_hash: Some(tx.hash()),
block_number: epoch_num.into(),
block_number: epoch_num,
block_hash: phantom_block.pivot_header.hash(),
// action and its result should have the same `valid`.
valid: action.valid,
Expand Down Expand Up @@ -468,7 +468,7 @@ fn to_eth_traces(
eth_traces[index].set_result(trace.action)?;

eth_traces[index].subtraces =
sublen_stack.pop().expect("stack_index matches").into();
sublen_stack.pop().expect("stack_index matches");
}
RpcAction::InternalTransferAction(_) => {}
}
Expand Down
2 changes: 1 addition & 1 deletion client/src/rpc/traits/cfx_space/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub trait TestRpc {
#[rpc(name = "test_generatecustomblock")]
fn generate_custom_block(
&self, parent: H256, referees: Vec<H256>, raw: Bytes,
adaptive: Option<bool>,
adaptive: Option<bool>, custom: Option<Vec<Bytes>>,
) -> RpcResult<H256>;

#[rpc(name = "test_generateblockwithfaketxs")]
Expand Down
Loading

0 comments on commit b945518

Please sign in to comment.