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

evm: Move DFIIntrinsics and TransferDomain contracts #2437

Merged
merged 21 commits into from
Sep 19, 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
89 changes: 68 additions & 21 deletions lib/ain-contracts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ use sp_core::{Blake2Hasher, Hasher};

pub type Result<T> = std::result::Result<T, anyhow::Error>;

pub const DST20_ADDR_PREFIX_BYTE: u8 = 0xff;
pub const INTRINSICS_ADDR_PREFIX_BYTE: u8 = 0xdf;

macro_rules! solc_artifact_path {
($project_name:literal, $artifact:literal) => {
concat!(
Expand All @@ -30,6 +33,33 @@ macro_rules! solc_artifact_bytecode_str {
};
}

macro_rules! slice_20b {
($first_byte:tt, $last_byte:tt) => {
[
$first_byte,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
0x0,
$last_byte,
]
};
}

fn get_bytecode(input: &str) -> Result<Vec<u8>> {
let bytecode_json: serde_json::Value = serde_json::from_str(input)?;
let bytecode_raw = bytecode_json["object"]
Expand Down Expand Up @@ -63,20 +93,18 @@ pub fn get_dst20_deploy_input(init_bytecode: Vec<u8>, name: &str, symbol: &str)
.map_err(|e| format_err!(e))
}

pub fn dst20_address_from_token_id(token_id: u64) -> Result<H160> {
let number_str = format!("{token_id:x}");
let padded_number_str = format!("{number_str:0>38}");
let final_str = format!("ff{padded_number_str}");
pub fn generate_intrinsic_addr(prefix_byte: u8, suffix_num: u64) -> Result<H160> {
let s = format!("{prefix_byte:x}{suffix_num:0>38x}");

Ok(H160::from_str(&final_str)?)
Ok(H160::from_str(&s)?)
}

pub fn intrinsics_address_from_id(id: u64) -> Result<H160> {
let number_str = format!("{:x}", id);
let padded_number_str = format!("{number_str:0>37}");
let final_str = format!("ff1{padded_number_str}");
pub fn dst20_address_from_token_id(token_id: u64) -> Result<H160> {
generate_intrinsic_addr(DST20_ADDR_PREFIX_BYTE, token_id)
}

Ok(H160::from_str(&final_str)?)
pub fn intrinsics_address_from_id(id: u64) -> Result<H160> {
generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, id)
}

#[derive(Clone)]
Expand All @@ -102,17 +130,11 @@ lazy_static::lazy_static! {
runtime_bytecode: bytecode,
init_bytecode: Vec::new(),
},
fixed_address: H160([
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x3, 0x1,
]),
fixed_address: H160(slice_20b!(INTRINSICS_ADDR_PREFIX_BYTE, 0x0)),
}
};

pub static ref TRANSFERDOMAIN_CONTRACT: FixedContract = {
// Note that input, bytecode, and deployed bytecode is used in confusing ways since
// deployedBytecode was exposed as bytecode earlier in build script.
// TODO: Refactor terminology to align with the source of truth.
let bytecode = solc_artifact_bytecode_str!("transfer_domain", "deployed_bytecode.json");
let input = solc_artifact_bytecode_str!(
"transfer_domain",
Expand All @@ -125,10 +147,7 @@ lazy_static::lazy_static! {
runtime_bytecode: bytecode,
init_bytecode: input,
},
fixed_address: H160([
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x3, 0x2,
]),
fixed_address: H160(slice_20b!(INTRINSICS_ADDR_PREFIX_BYTE, 0x1)),
}
};

Expand Down Expand Up @@ -176,3 +195,31 @@ pub fn get_dst20_contract() -> Contract {
pub fn get_reserved_contract() -> Contract {
RESERVED_CONTRACT.clone()
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_addr_gen() {
let items: Vec<(Result<H160>, &str)> = vec![
(generate_intrinsic_addr(DST20_ADDR_PREFIX_BYTE, 0x0), "ff00000000000000000000000000000000000000"),
(generate_intrinsic_addr(DST20_ADDR_PREFIX_BYTE, 0x1), "ff00000000000000000000000000000000000001"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0x0), "df00000000000000000000000000000000000000"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0x1), "df00000000000000000000000000000000000001"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0x2), "df00000000000000000000000000000000000002"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0xff), "df000000000000000000000000000000000000ff"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0xfe), "df000000000000000000000000000000000000fe"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0x1fffe), "df0000000000000000000000000000000001fffe"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0xffff), "df0000000000000000000000000000000000ffff"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0xffff_ffff_ffff_ffff), "df0000000000000000000000ffffffffffffffff"),
(generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0xefff_ffff_ffff_ffff), "df0000000000000000000000efffffffffffffff"),
// Should not compile
// (generate_intrinsic_addr(INTRINSICS_ADDR_PREFIX_BYTE, 0x1ffff_ffff_ffff_ffff), "df0000000000000000000001ffffffffffffffff"),
];

for x in items {
assert_eq!(x.0.unwrap(), H160::from_str(x.1).unwrap());
}
}
}
6 changes: 4 additions & 2 deletions lib/ain-evm/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ impl EVMBackend {
storage.into_iter().for_each(|(k, v)| {
debug!("Apply::Modify storage, key: {:x} value: {:x}", k, v);
let _ = storage_trie.insert(k.as_bytes(), v.as_bytes());
storage_trie.commit();
});

let code_hash = match code {
Expand Down Expand Up @@ -120,6 +121,7 @@ impl EVMBackend {
self.state
.insert(address.as_bytes(), new_account.rlp_bytes().as_ref())
.map_err(|e| BackendError::TrieError(format!("{e}")))?;
self.state.commit();

Ok(new_account)
}
Expand Down Expand Up @@ -362,15 +364,15 @@ impl ApplyBackend for EVMBackend {
.expect("Error applying state");

if is_empty_account(&new_account) && delete_empty {
debug!("Deleting empty address {}", address);
debug!("Deleting empty address {:x?}", address);
self.trie_store.trie_db.trie_remove(address.as_bytes());
self.state
.remove(address.as_bytes())
.expect("Error removing address in state");
}
}
Apply::Delete { address } => {
debug!("Deleting address {}", address);
debug!("Deleting address {:x?}", address);
self.trie_store.trie_db.trie_remove(address.as_bytes());
self.state
.remove(address.as_bytes())
Expand Down
2 changes: 1 addition & 1 deletion lib/ain-evm/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl BlockService {
.unwrap_or_default();

block_handler.starting_block_number = block_number;
debug!("Current block number is {:#?}", block_number);
debug!("Current block number is {:x?}", block_number);

Ok(block_handler)
}
Expand Down
139 changes: 134 additions & 5 deletions lib/ain-evm/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
use ain_contracts::{
get_dst20_contract, get_intrinsic_contract, get_reserved_contract, get_transferdomain_contract,
Contract, FixedContract,
get_dst20_contract, get_dst20_deploy_input, get_intrinsic_contract, get_reserved_contract,
get_transferdomain_contract, Contract, FixedContract,
};
use anyhow::format_err;
use ethbloom::Bloom;
use ethereum::{
EIP1559ReceiptData, LegacyTransaction, ReceiptV3, TransactionAction, TransactionSignature,
TransactionV2,
};
use ethereum_types::{H160, H256, U256};
use log::debug;
use log::trace;
use sha3::{Digest, Keccak256};

use crate::{backend::EVMBackend, bytes::Bytes, transaction::system::TransferDirection, Result};
use crate::{
backend::EVMBackend,
bytes::Bytes,
executor::AinExecutor,
transaction::{
system::{DeployContractData, SystemTx, TransferDirection},
SignedTx, LOWER_H256,
},
txqueue::{QueueTx, QueueTxItem},
Result,
};

pub fn u256_to_h256(input: U256) -> H256 {
let mut bytes = [0_u8; 32];
Expand Down Expand Up @@ -67,7 +82,7 @@ pub fn intrinsics_contract(
let count =
backend.get_contract_storage(fixed_address, u256_to_h256(U256::one()).as_bytes())?;

debug!("Count: {:#x}", count + U256::one());
trace!("Count: {:#x}", count + U256::one());

Ok(DeployContractInfo {
address: fixed_address,
Expand Down Expand Up @@ -184,3 +199,117 @@ pub fn bridge_dst20(
],
})
}

pub fn reserve_dst20_namespace(executor: &mut AinExecutor) -> Result<()> {
let Contract {
runtime_bytecode, ..
} = get_reserved_contract();
let addresses = (0..1024)
.map(|token_id| ain_contracts::dst20_address_from_token_id(token_id).unwrap())
.collect::<Vec<H160>>();

for address in addresses {
trace!(
"[reserve_dst20_namespace] Deploying address to {:#?}",
address
);
executor.deploy_contract(address, runtime_bytecode.clone().into(), Vec::new())?;
}

Ok(())
}

pub fn reserve_intrinsics_namespace(executor: &mut AinExecutor) -> Result<()> {
let Contract {
runtime_bytecode, ..
} = get_reserved_contract();
let addresses = (0..128)
.map(|token_id| ain_contracts::intrinsics_address_from_id(token_id).unwrap())
.collect::<Vec<H160>>();

for address in addresses {
trace!(
"[reserve_intrinsics_namespace] Deploying address to {:#?}",
address
);
executor.deploy_contract(address, runtime_bytecode.clone().into(), Vec::new())?;
}

Ok(())
}

pub fn dst20_deploy_contract_tx(
token_id: u64,
base_fee: &U256,
name: &str,
symbol: &str,
) -> Result<(Box<SignedTx>, ReceiptV3)> {
let tx = TransactionV2::Legacy(LegacyTransaction {
nonce: U256::from(token_id),
gas_price: *base_fee,
gas_limit: U256::from(u64::MAX),
action: TransactionAction::Create,
value: U256::zero(),
input: get_dst20_deploy_input(get_dst20_contract().init_bytecode, name, symbol)
.map_err(|e| format_err!(e))?,
signature: TransactionSignature::new(27, LOWER_H256, LOWER_H256)
.ok_or(format_err!("Invalid transaction signature format"))?,
})
.try_into()?;

let receipt = get_default_successful_receipt();

Ok((Box::new(tx), receipt))
}

pub fn transfer_domain_deploy_contract_tx(base_fee: &U256) -> Result<(SignedTx, ReceiptV3)> {
let tx = TransactionV2::Legacy(LegacyTransaction {
nonce: U256::zero(),
gas_price: *base_fee,
gas_limit: U256::from(u64::MAX),
action: TransactionAction::Create,
value: U256::zero(),
input: get_transferdomain_contract().contract.init_bytecode,
signature: TransactionSignature::new(27, LOWER_H256, LOWER_H256)
.ok_or(format_err!("Invalid transaction signature format"))?,
})
.try_into()?;

let receipt = get_default_successful_receipt();

Ok((tx, receipt))
}

fn get_default_successful_receipt() -> ReceiptV3 {
ReceiptV3::Legacy(EIP1559ReceiptData {
status_code: 1u8,
used_gas: U256::zero(),
logs_bloom: Bloom::default(),
logs: Vec::new(),
})
}

pub fn get_dst20_migration_txs(mnview_ptr: usize) -> Result<Vec<QueueTxItem>> {
let mut txs = Vec::new();
for token in ain_cpp_imports::get_dst20_tokens(mnview_ptr) {
let address = ain_contracts::dst20_address_from_token_id(token.id)?;
trace!(
"[get_dst20_migration_txs] Deploying to address {:#?}",
address
);

let tx = QueueTx::SystemTx(SystemTx::DeployContract(DeployContractData {
name: token.name,
symbol: token.symbol,
token_id: token.id,
address,
}));
txs.push(QueueTxItem {
tx,
tx_hash: Default::default(),
gas_used: U256::zero(),
state_root: Default::default(),
});
}
Ok(txs)
}
Loading
Loading