Skip to content

Commit

Permalink
[Rust/BNB]: Move BNB Beacon chain to Rust (#3589)
Browse files Browse the repository at this point in the history
* [BNB]: Generate BNB Beacon chain skeleton files in Rust

* [BNB]: Implement `BinanceAddress`, add Address tests

* [BNB]: Add TBinance address tests

* [BNB]: Add Transaction and its encoding, prehashing

* Add Amino encoding

* [BNB]: Sign a transaction

* TODO Add tests, handle all message types

* [BNB]: Add a signing test

* [BNB]: Add `SendOrder`, `CancelOrder`

* [BNB]: Add Token orders

* [BNB]: Add `TokenBurnOrder`, `HTLTOrder`

* [BNB]: Add `DepositHTLT`

* [BNB]: Add `ClaimHTLTOrder`, `RefundHTLTOrder`

* [BNB]: Add `TransferOutOrder`

* [BNB]: Add `SideChainDelegate`, `SideChainRedelegate`, `SideChainUndelegate` orders

* [BNB]: Add `TimeLock`, `TimeRelock`, `TimeUnlock` orders

* [BNB]: Implement Transaction Compiler

* [BNB]: Increase code coverage

* [BNB]: Replace C++ implementation

* [BNB]: Move TX preimage implementation to `JsonPreimager`

* Remove C++ Signing tests

* [BNB]: Extend `CoinEntry` documentation

* [CI] Trigger CI

* [BNB]: Remove `TransactionCompilerBuildInput`

* [BNB]: Avoid duplicating code

* [BNB]: Add fuzz tests
  • Loading branch information
satoshiotomakan authored Dec 13, 2023
1 parent f7bdfbe commit 2a63cda
Show file tree
Hide file tree
Showing 99 changed files with 3,419 additions and 1,643 deletions.
4 changes: 2 additions & 2 deletions codegen-v2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ path = "src/main.rs"
aho-corasick = "1.1.2"
convert_case = "0.6.0"
pathdiff = "0.2.1"
serde = { version = "1.0.159", features = ["derive"] }
serde_json = "1.0.95"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_yaml = "0.9.21"
toml_edit = "0.21.0"
handlebars = "4.3.6"
Expand Down
17 changes: 0 additions & 17 deletions include/TrustWalletCore/TWTransactionCompiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,6 @@ TW_EXTERN_C_BEGIN
TW_EXPORT_STRUCT
struct TWTransactionCompiler;

/// Builds a coin-specific SigningInput (proto object) from a simple transaction.
///
/// \deprecated `TWTransactionCompilerBuildInput` will be removed soon.
/// \param coin coin type.
/// \param from sender of the transaction.
/// \param to receiver of the transaction.
/// \param amount transaction amount in string
/// \param asset optional asset name, like "BNB"
/// \param memo optional memo
/// \param chainId optional chainId to override default
/// \return serialized data of the SigningInput proto object.
TW_EXPORT_STATIC_METHOD
TWData* _Nonnull TWTransactionCompilerBuildInput(enum TWCoinType coinType, TWString* _Nonnull from,
TWString* _Nonnull to, TWString* _Nonnull amount,
TWString* _Nonnull asset, TWString* _Nonnull memo,
TWString* _Nonnull chainId);

/// Obtains pre-signing hashes of a transaction.
///
/// We provide a default `PreSigningOutput` in TransactionCompiler.proto.
Expand Down
2 changes: 2 additions & 0 deletions registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -2440,6 +2440,7 @@
],
"curve": "secp256k1",
"publicKeyType": "secp256k1",
"addressHasher": "sha256ripemd",
"hrp": "bnb",
"chainId": "Binance-Chain-Tigris",
"explorer": {
Expand Down Expand Up @@ -2472,6 +2473,7 @@
],
"curve": "secp256k1",
"publicKeyType": "secp256k1",
"addressHasher": "sha256ripemd",
"hrp": "tbnb",
"explorer": {
"url": "https://testnet-explorer.binance.org",
Expand Down
33 changes: 33 additions & 0 deletions rust/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 rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[workspace]
members = [
"chains/tw_binance",
"chains/tw_cosmos",
"chains/tw_native_evmos",
"chains/tw_native_injective",
Expand Down
21 changes: 21 additions & 0 deletions rust/chains/tw_binance/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "tw_binance"
version = "0.1.0"
edition = "2021"

[dependencies]
quick-protobuf = "0.8.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_repr = "0.1"
strum_macros = "0.25"
tw_bech32_address = { path = "../../tw_bech32_address" }
tw_coin_entry = { path = "../../tw_coin_entry" }
tw_cosmos_sdk = { path = "../../tw_cosmos_sdk" }
tw_encoding = { path = "../../tw_encoding" }
tw_evm = { path = "../../tw_evm" }
tw_hash = { path = "../../tw_hash" }
tw_keypair = { path = "../../tw_keypair" }
tw_memory = { path = "../../tw_memory" }
tw_misc = { path = "../../tw_misc" }
tw_proto = { path = "../../tw_proto" }
5 changes: 5 additions & 0 deletions rust/chains/tw_binance/fuzz/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
target
corpus
artifacts
coverage
Cargo.lock
30 changes: 30 additions & 0 deletions rust/chains/tw_binance/fuzz/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[package]
name = "tw_binance-fuzz"
version = "0.0.0"
publish = false
edition = "2021"

[package.metadata]
cargo-fuzz = true

[dependencies]
libfuzzer-sys = "0.4"
tw_any_coin = { path = "../../../tw_any_coin", features = ["test-utils"] }
tw_coin_registry = { path = "../../../tw_coin_registry" }
tw_proto = { path = "../../../tw_proto", features = ["fuzz"] }

[dependencies.tw_binance]
path = ".."

# Prevent this from interfering with workspaces
[workspace]
members = ["."]

[profile.release]
debug = 1

[[bin]]
name = "sign"
path = "fuzz_targets/sign.rs"
test = false
doc = false
11 changes: 11 additions & 0 deletions rust/chains/tw_binance/fuzz/fuzz_targets/sign.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#![no_main]

use libfuzzer_sys::fuzz_target;
use tw_any_coin::test_utils::sign_utils::AnySignerHelper;
use tw_coin_registry::coin_type::CoinType;
use tw_proto::Binance::Proto;

fuzz_target!(|input: Proto::SigningInput<'_>| {
let mut signer = AnySignerHelper::<Proto::SigningOutput>::default();
let _ = signer.sign(CoinType::Binance, input);
});
91 changes: 91 additions & 0 deletions rust/chains/tw_binance/src/address.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// 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 serde::Serialize;
use std::fmt;
use std::str::FromStr;
use tw_bech32_address::bech32_prefix::Bech32Prefix;
use tw_bech32_address::Bech32Address;
use tw_coin_entry::coin_context::CoinContext;
use tw_coin_entry::coin_entry::CoinAddress;
use tw_coin_entry::error::{AddressError, AddressResult};
use tw_keypair::tw::PublicKey;
use tw_memory::Data;

/// The list of known BNB hrps.
const BNB_KNOWN_HRPS: [&str; 2] = [
BinanceAddress::VALIDATOR_HRP, // BNB Validator HRP.
"bca",
];

#[derive(Serialize)]
pub struct BinanceAddress(Bech32Address);

impl CoinAddress for BinanceAddress {
#[inline]
fn data(&self) -> Data {
self.0.data()
}
}

impl BinanceAddress {
pub const VALIDATOR_HRP: &'static str = "bva";

pub fn new_validator_addr(key_hash: Data) -> AddressResult<BinanceAddress> {
Bech32Address::new(Self::VALIDATOR_HRP.to_string(), key_hash).map(BinanceAddress)
}

/// Creates a Binance address with the only `prefix`
pub fn from_str_with_coin_and_prefix(
coin: &dyn CoinContext,
address_str: String,
prefix: Option<Bech32Prefix>,
) -> AddressResult<BinanceAddress>
where
Self: Sized,
{
let possible_hrps = match prefix {
Some(Bech32Prefix { hrp }) => vec![hrp],
None => {
let coin_hrp = coin.hrp().ok_or(AddressError::InvalidHrp)?;
let other_hrps = BNB_KNOWN_HRPS
.iter()
.map(|another_hrp| another_hrp.to_string());
std::iter::once(coin_hrp).chain(other_hrps).collect()
},
};
Bech32Address::from_str_checked(possible_hrps, address_str).map(BinanceAddress)
}

pub fn with_public_key_coin_context(
coin: &dyn CoinContext,
public_key: &PublicKey,
prefix: Option<Bech32Prefix>,
) -> AddressResult<BinanceAddress> {
Bech32Address::with_public_key_coin_context(coin, public_key, prefix).map(BinanceAddress)
}

pub fn from_key_hash_with_coin(
coin: &dyn CoinContext,
key_hash: Data,
) -> AddressResult<BinanceAddress> {
Bech32Address::from_key_hash_with_coin(coin, key_hash).map(BinanceAddress)
}
}

impl FromStr for BinanceAddress {
type Err = AddressError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
Bech32Address::from_str(s).map(BinanceAddress)
}
}

impl fmt::Display for BinanceAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
Loading

0 comments on commit 2a63cda

Please sign in to comment.