Skip to content

Commit

Permalink
feat(eth): Add comments, move ABI resources into a separate dir
Browse files Browse the repository at this point in the history
  • Loading branch information
satoshiotomakan committed Jul 24, 2023
1 parent 97cf9f4 commit 973c770
Show file tree
Hide file tree
Showing 23 changed files with 47 additions and 12 deletions.
12 changes: 6 additions & 6 deletions rust/tw_any_coin/src/any_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.

// Copyright © 2017-2023 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.

use tw_coin_entry::coin_entry_ext::CoinEntryExt;
use tw_coin_entry::derivation::Derivation;
use tw_coin_entry::error::{AddressError, AddressResult};
Expand All @@ -19,18 +13,21 @@ use tw_coin_registry::coin_type::CoinType;
use tw_keypair::tw::PublicKey;
use tw_misc::try_or_false;

/// Represents an address in Rust for almost any blockchain.
#[derive(Debug, PartialEq)]
pub struct AnyAddress {
coin: CoinType,
address: String,
}

impl AnyAddress {
/// Determines if the string is a valid Any address.
pub fn is_valid(coin: CoinType, address: &str, prefix: Option<AddressPrefix>) -> bool {
let (ctx, entry) = try_or_false!(coin_dispatcher(coin));
entry.validate_address(&ctx, address, prefix).is_ok()
}

/// Creates an address from a string representation and a coin type.
pub fn with_string(
coin: CoinType,
address: &str,
Expand All @@ -41,6 +38,7 @@ impl AnyAddress {
Ok(AnyAddress { coin, address })
}

/// Creates an address from a public key, derivation and prefix option.
pub fn with_public_key(
coin: CoinType,
public_key: PublicKey,
Expand All @@ -52,11 +50,13 @@ impl AnyAddress {
Ok(AnyAddress { coin, address })
}

/// Returns underlying data (public key or key hash).
pub fn get_data(&self) -> AddressResult<Vec<u8>> {
let (ctx, entry) = coin_dispatcher(self.coin).map_err(|_| AddressError::UnknownCoinType)?;
entry.address_to_data(&ctx, &self.address, None)
}

/// Returns the address string representation.
pub fn description(&self) -> &str {
&self.address
}
Expand Down
2 changes: 2 additions & 0 deletions rust/tw_any_coin/src/any_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ use tw_coin_entry::error::{SigningError, SigningResult};
use tw_coin_registry::coin_dispatcher;
use tw_coin_registry::coin_type::CoinType;

/// Represents a signer to sign transactions for any blockchain.
pub struct AnySigner;

impl AnySigner {
/// Signs a transaction specified by the signing input and coin type.
pub fn sign(input: &[u8], coin: CoinType) -> SigningResult<Vec<u8>> {
let (ctx, entry) = coin_dispatcher(coin)?;
entry.sign(&ctx, input).map_err(SigningError::from)
Expand Down
6 changes: 6 additions & 0 deletions rust/tw_any_coin/src/ffi/tw_any_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use tw_memory::ffi::tw_string::TWString;
use tw_memory::ffi::RawPtrTrait;
use tw_misc::{try_or_else, try_or_false};

/// Represents an address in Rust for almost any blockchain.
pub struct TWAnyAddress(AnyAddress);

impl RawPtrTrait for TWAnyAddress {}
Expand All @@ -31,6 +32,11 @@ pub unsafe extern "C" fn tw_any_address_is_valid(string: *mut TWString, coin: u3
AnyAddress::is_valid(coin, string, None)
}

/// Creates an address from a string representation and a coin type. Must be deleted with `TWAnyAddressDelete` after use.
///
/// \param string address to create.
/// \param coin coin type of the address.
/// \return `TWAnyAddress` pointer or nullptr if address and coin are invalid.
#[no_mangle]
pub unsafe extern "C" fn tw_any_address_create_with_string(
string: *mut TWString,
Expand Down
4 changes: 4 additions & 0 deletions rust/tw_any_coin/src/transaction_compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ use tw_coin_entry::modules::input_builder::BuildSigningInputArgs;
use tw_coin_registry::coin_dispatcher;
use tw_coin_registry::coin_type::CoinType;

/// Non-core transaction utility methods, like building a transaction using an external signature.
pub struct TransactionCompiler;

impl TransactionCompiler {
/// Builds a coin-specific SigningInput (proto object) from a simple transaction.
pub fn build_input(coin: CoinType, args: BuildSigningInputArgs) -> SigningResult<Vec<u8>> {
let (ctx, entry) = coin_dispatcher(coin)?;
match entry.build_signing_input(&ctx, args) {
Expand All @@ -24,13 +26,15 @@ impl TransactionCompiler {
}
}

/// Obtains pre-signing hashes of a transaction.
pub fn preimage_hashes(coin: CoinType, input: &[u8]) -> SigningResult<Vec<u8>> {
let (ctx, entry) = coin_dispatcher(coin)?;
entry
.preimage_hashes(&ctx, input)
.map_err(SigningError::from)
}

/// Compiles a complete transaction with one or more external signatures.
pub fn compile(
coin: CoinType,
input: &[u8],
Expand Down
2 changes: 1 addition & 1 deletion rust/tw_coin_entry/src/coin_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub trait CoinEntry {
prefix: Option<Self::AddressPrefix>,
) -> AddressResult<Self::Address>;

/// Derives an address associated with the given `public_key` by `coin` type, `derivation` and address `prefix`.
/// Derives an address associated with the given `public_key` by `coin` context, `derivation` and address `prefix`.
fn derive_address(
&self,
coin: &dyn CoinContext,
Expand Down
7 changes: 7 additions & 0 deletions rust/tw_coin_entry/src/coin_entry_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub trait CoinEntryExt {
prefix: Option<AddressPrefix>,
) -> AddressResult<String>;

/// Derives an address associated with the given `public_key` by `coin` context, `derivation` and address `prefix`.
fn derive_address(
&self,
coin: &dyn CoinContext,
Expand All @@ -41,18 +42,23 @@ pub trait CoinEntryExt {
prefix: Option<AddressPrefix>,
) -> AddressResult<String>;

/// Returns underlying data (public key or key hash).
fn address_to_data(
&self,
coin: &dyn CoinContext,
address: &str,
prefix: Option<AddressPrefix>,
) -> AddressResult<Vec<u8>>;

/// Signs a transaction declared as the given `input`.
fn sign(&self, coin: &dyn CoinContext, input: &[u8]) -> ProtoResult<Vec<u8>>;

/// Returns `true` if the chain supports JSON signing.
fn supports_json_signing(&self) -> bool;

/// Signs a transaction specified by the JSON representation of signing input and a private key.
/// Returns the JSON representation of the signing output if the blockchain supports JSON signing.
/// Checks [`CoinEntryExt::supports_json_signing`].
fn sign_json(
&self,
coin: &dyn CoinContext,
Expand All @@ -74,6 +80,7 @@ pub trait CoinEntryExt {
public_keys: Vec<PublicKeyBytes>,
) -> ProtoResult<Vec<u8>>;

/// Plans a transaction (for UTXO chains only).
fn plan(&self, coin: &dyn CoinContext, input: &[u8]) -> ProtoResult<Option<Vec<u8>>>;

/// Optional helper to prepare a `SigningInput` from simple parameters.
Expand Down
1 change: 1 addition & 0 deletions rust/tw_coin_entry/src/test_utils/empty_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use crate::coin_context::CoinContext;
use tw_keypair::tw::PublicKeyType;

/// Test coin context that panics on any `CoinContext` method call.
pub struct EmptyCoinContext;

impl CoinContext for EmptyCoinContext {
Expand Down
2 changes: 1 addition & 1 deletion rust/tw_coin_registry/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ lazy_static! {
static ref REGISTRY: RegistryMap = parse_registry_json();
}

/// TODO extend this structure according to `registry.json`.
/// Extend this structure according to `registry.json`.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CoinItem {
Expand Down
2 changes: 1 addition & 1 deletion rust/tw_evm/src/abi/prebuild/erc1155.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tw_number::U256;

/// Generated via https://remix.ethereum.org
/// Solidity: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.9.2/contracts/token/ERC1155/IERC1155.sol
const ERC1155_ABI: &str = include_str!("erc1155.abi.json");
const ERC1155_ABI: &str = include_str!("resource/erc1155.abi.json");

lazy_static! {
static ref ERC1155: Contract = serde_json::from_str(ERC1155_ABI).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion rust/tw_evm/src/abi/prebuild/erc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tw_number::U256;

/// Generated via https://remix.ethereum.org
/// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.9.2/contracts/token/ERC20/IERC20.sol
const ERC20_ABI: &str = include_str!("erc20.abi.json");
const ERC20_ABI: &str = include_str!("resource/erc20.abi.json");

lazy_static! {
static ref ERC20: Contract = serde_json::from_str(ERC20_ABI).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion rust/tw_evm/src/abi/prebuild/erc4337.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use tw_number::U256;
/// Generated via https://remix.ethereum.org
/// Modified solidity interface: [`erc4337.simple_account.sol`].
/// Original: https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/samples/SimpleAccount.sol
const ERC4337_SIMPLE_ACCOUNT_ABI: &str = include_str!("erc4337.simple_account.abi.json");
const ERC4337_SIMPLE_ACCOUNT_ABI: &str = include_str!("resource/erc4337.simple_account.abi.json");

lazy_static! {
static ref ERC4337_SIMPLE_ACCOUNT: Contract =
Expand Down
2 changes: 1 addition & 1 deletion rust/tw_evm/src/abi/prebuild/erc721.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tw_number::U256;

/// Generated via https://remix.ethereum.org
/// Solidity: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.9.2/contracts/token/ERC721/IERC721.sol
const ERC721_ABI: &str = include_str!("erc721.abi.json");
const ERC721_ABI: &str = include_str!("resource/erc721.abi.json");

lazy_static! {
static ref ERC721: Contract = serde_json::from_str(ERC721_ABI).unwrap();
Expand Down
File renamed without changes.
2 changes: 2 additions & 0 deletions rust/tw_evm/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub struct Address {
impl Address {
pub const LEN: usize = 20;

/// Tries to parse an address from the string representation.
/// Returns `Ok(None)` if the given `s` string is empty.
pub fn from_str_optional(s: &str) -> AddressResult<Option<Address>> {
if s.is_empty() {
return Ok(None);
Expand Down
7 changes: 7 additions & 0 deletions rust/tw_evm/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.

//! Transactions can be:
//! - Non-typed (legacy, pre-EIP2718) transactions:
//! -- simple ETH transfer
//! -- others with payload, function call, e.g. ERC20 transfer
//! - Typed transactions (enveloped, EIP2718), with specific type and transaction payload
//! - User operations (EIP4337)

use crate::transaction::signature::EthSignature;
use tw_hash::{sha3::keccak256, H256};
use tw_keypair::ecdsa::secp256k1;
Expand Down
2 changes: 2 additions & 0 deletions rust/tw_evm/src/transaction/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub trait EthSignature {
fn s(&self) -> U256;
}

/// R-S-V Signature values.
pub struct Signature {
v: U256,
r: U256,
Expand Down Expand Up @@ -52,6 +53,7 @@ impl EthSignature for Signature {
}
}

/// R-S-V Signature values EIP115.
pub struct SignatureEip155 {
v: U256,
r: U256,
Expand Down
1 change: 1 addition & 0 deletions rust/tw_evm/src/transaction/transaction_eip1559.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const EIP1559_TX_TYPE: u8 = 0x02;
const TX_FIELDS_LEN: usize = 9;
const TX_FIELDS_WITH_SIGNATURE_LEN: usize = TX_FIELDS_LEN + 3;

/// EIP1559 transaction.
pub struct TransactionEip1559 {
pub nonce: U256,
pub max_inclusion_fee_per_gas: U256,
Expand Down
1 change: 1 addition & 0 deletions rust/tw_evm/src/transaction/transaction_non_typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use tw_number::U256;

const TX_FIELDS_LEN: usize = 9;

/// Original transaction format, with no explicit type, legacy as pre-EIP2718.
pub struct TransactionNonTyped {
pub nonce: U256,
pub gas_price: U256,
Expand Down
2 changes: 2 additions & 0 deletions rust/tw_evm/src/transaction/user_operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use tw_hash::sha3::keccak256;
use tw_hash::H256;
use tw_number::U256;

/// EIP4337 UserOperation
/// https://github.com/ethereum/EIPs/blob/3fd65b1a782912bfc18cb975c62c55f733c7c96e/EIPS/eip-4337.md#specification
pub struct UserOperation {
pub nonce: U256,
pub entry_point: Address,
Expand Down

0 comments on commit 973c770

Please sign in to comment.