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

Get block difficulty and chain work of block via CPP FFI #1931

Merged
merged 3 commits into from
Apr 24, 2023
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
2 changes: 2 additions & 0 deletions lib/ain-cpp-imports/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ pub mod ffi {
fn publishEthTransaction(data: Vec<u8>) -> bool;
fn getAccounts() -> Vec<String>;
fn getDatadir() -> String;
fn getDifficulty(_block_hash: [u8; 32]) -> u32;
fn getChainWork(_block_hash: [u8; 32]) -> [u8; 32];
}
}
16 changes: 16 additions & 0 deletions lib/ain-cpp-imports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ mod ffi {
pub fn getDatadir() -> String {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getDifficulty(_block_hash: [u8; 32]) -> u32 {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getChainWork(_block_hash: [u8; 32]) -> [u8; 32] {
unimplemented!("{}", UNIMPL_MSG)
}
}

pub fn get_chain_id() -> Result<u64, Box<dyn Error>> {
Expand Down Expand Up @@ -52,5 +58,15 @@ pub fn get_datadir() -> Result<String, Box<dyn Error>> {
Ok(datadir)
}

pub fn get_difficulty(block_hash: [u8; 32]) -> Result<u32, Box<dyn Error>> {
let bits = ffi::getDifficulty(block_hash);
Ok(bits)
}

pub fn get_chainwork(block_hash: [u8; 32]) -> Result<[u8; 32], Box<dyn Error>> {
let chainwork = ffi::getChainWork(block_hash);
Ok(chainwork)
}

#[cfg(test)]
mod tests {}
3 changes: 2 additions & 1 deletion lib/ain-evm/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ impl Handlers {
&self,
context: u64,
update_state: bool,
difficulty: u32,
_miner_address: Option<H160>,
) -> Result<(BlockAny, Vec<TransactionV2>), Box<dyn Error>> {
let mut successful_transactions = Vec::with_capacity(self.evm.tx_queues.len(context));
Expand Down Expand Up @@ -71,7 +72,7 @@ impl Handlers {
state_root: Default::default(),
receipts_root: Default::default(),
logs_bloom: Default::default(),
difficulty: Default::default(),
difficulty: U256::from(difficulty),
number,
gas_limit: Default::default(),
gas_used: Default::default(),
Expand Down
8 changes: 4 additions & 4 deletions lib/ain-evm/tests/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn test_finalize_block_and_do_not_update_state() {
handler.evm.tx_queues.add_signed_tx(context, tx1);

let old_state = handler.evm.state.read().unwrap();
let _ = handler.finalize_block(context, false, None).unwrap();
let _ = handler.finalize_block(context, false, 0, None).unwrap();

let new_state = handler.evm.state.read().unwrap();
assert_eq!(*new_state, *old_state);
Expand Down Expand Up @@ -60,7 +60,7 @@ fn test_finalize_block_and_update_state() {
assert_eq!(handler.evm.tx_queues.len(context), 3);
assert_eq!(handler.evm.tx_queues.len(handler.evm.get_context()), 0);

let (block, failed_txs) = handler.finalize_block(context, true, None).unwrap();
let (block, failed_txs) = handler.finalize_block(context, true, 0, None).unwrap();
assert_eq!(
block.transactions,
vec![tx1, tx2, tx3.clone()]
Expand Down Expand Up @@ -133,7 +133,7 @@ fn test_deploy_and_call_smart_contract() {
.tx_queues
.add_signed_tx(context, create_smart_contract_tx);

handler.finalize_block(context, true, None).unwrap();
handler.finalize_block(context, true, 0, None).unwrap();

// Fund caller address
handler.evm.add_balance(
Expand All @@ -152,7 +152,7 @@ fn test_deploy_and_call_smart_contract() {
.tx_queues
.add_signed_tx(context, call_smart_contract_tx);

handler.finalize_block(context, true, None).unwrap();
handler.finalize_block(context, true, 0, None).unwrap();

let smart_contract_storage = handler.evm.get_storage(smart_contract_address);
assert_eq!(
Expand Down
6 changes: 4 additions & 2 deletions lib/ain-grpc/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,13 @@ impl MetachainRPCServer for MetachainRPCModule {

let hash: H256 = hash.parse().expect("Invalid hash");

Ok(self
let block: Option<RpcBlock> = self
.handler
.storage
.get_block_by_hash(&hash)
.map(Into::into))
.map(Into::into);

Ok(block)
}

fn chain_id(&self) -> Result<String> {
Expand Down
2 changes: 1 addition & 1 deletion lib/ain-grpc/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ fn should_get_balance() {
.evm
.add_balance(ctx, H160::from_str(ALICE).unwrap(), U256::from(1337));

let _ = handler.finalize_block(ctx, true, None);
let _ = handler.finalize_block(ctx, true, 0, None);

let res2 = EthService::Eth_GetBalance(handler, input.into());
assert_eq!(res2.unwrap().balance, "1337");
Expand Down
4 changes: 3 additions & 1 deletion lib/ain-rs-exports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod ffi {
fn evm_finalize(
context: u64,
update_state: bool,
difficulty: u32,
miner_address: [u8; 20],
) -> Result<Vec<u8>>;

Expand Down Expand Up @@ -111,12 +112,13 @@ use rlp::Encodable;
fn evm_finalize(
context: u64,
update_state: bool,
difficulty: u32,
miner_address: [u8; 20],
) -> Result<Vec<u8>, Box<dyn Error>> {
let eth_address = H160::from(miner_address);
let (block, _failed_tx) =
RUNTIME
.handlers
.finalize_block(context, update_state, Some(eth_address))?;
.finalize_block(context, update_state, difficulty, Some(eth_address))?;
Ok(block.header.rlp_bytes().into())
}
41 changes: 41 additions & 0 deletions src/ffi/ffiexports.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,44 @@ rust::vec<rust::string> getAccounts() {
rust::string getDatadir() {
return GetDataDir().c_str();
}

uint32_t getDifficulty(std::array<uint8_t, 32> blockHash) {
uint256 hash{};
std::copy(blockHash.begin(), blockHash.end(), hash.begin());

const CBlockIndex* pblockindex;
uint32_t difficulty{};
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);

if (!pblockindex) {
return difficulty;
}

difficulty = pblockindex->nBits;
}

return difficulty;
}

std::array<uint8_t, 32> getChainWork(std::array<uint8_t, 32> blockHash) {
uint256 hash{};
std::copy(blockHash.begin(), blockHash.end(), hash.begin());

const CBlockIndex* pblockindex;
std::array<uint8_t, 32> chainWork{};
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);

if (!pblockindex) {
return chainWork;
}

const auto sourceWork = ArithToUint256(pblockindex->nChainWork);
std::copy(sourceWork.begin(), sourceWork.end(), chainWork.begin());
}

return chainWork;
}
2 changes: 2 additions & 0 deletions src/ffi/ffiexports.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ bool isMining();
bool publishEthTransaction(rust::Vec<uint8_t> rawTransaction);
rust::vec<rust::string> getAccounts();
rust::string getDatadir();
uint32_t getDifficulty(std::array<uint8_t, 32> blockHash);
std::array<uint8_t, 32> getChainWork(std::array<uint8_t, 32> blockHash);

#endif // DEFI_EVM_FFI_H
2 changes: 1 addition & 1 deletion src/miner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc

// TODO Get failed TXs and try to restore to mempool
std::array<uint8_t, 20> dummyAddress{};
const auto rustHeader = evm_finalize(evmContext, false, dummyAddress);
const auto rustHeader = evm_finalize(evmContext, false, pos::GetNextWorkRequired(pindexPrev, pblock->nTime, consensus), dummyAddress);

std::vector<uint8_t> evmHeader{};
evmHeader.resize(rustHeader.size());
Expand Down
6 changes: 3 additions & 3 deletions src/validation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2853,11 +2853,11 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
height = idHeight->blockHeight - GetMnResignDelay(std::numeric_limits<int>::max());
mnID = node->collateralTx;
}

const auto blockindex = ::ChainActive()[height];
assert(blockindex);


CTransactionRef tx;
uint256 hash_block;
assert(GetTransaction(mnID, tx, Params().GetConsensus(), hash_block, blockindex));
Expand All @@ -2873,7 +2873,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
std::copy(minter.begin(), minter.end(), minerAddress.begin());
}

evm_finalize(evmContext, true, minerAddress);
evm_finalize(evmContext, true, block.nBits, minerAddress);
}

auto &checkpoints = chainparams.Checkpoints().mapCheckpoints;
Expand Down