diff --git a/README.md b/README.md index 1e2696eb3..167950ece 100644 --- a/README.md +++ b/README.md @@ -27,3 +27,5 @@ The primary license for Platform is the Business Source License 1.1 (`BUSL-1.1`) ### Exceptions - All files in `components/contracts` are licensed under `Apache-2.0` + + diff --git a/src/components/abciapp/Cargo.toml b/src/components/abciapp/Cargo.toml index e761d510d..5a0716399 100644 --- a/src/components/abciapp/Cargo.toml +++ b/src/components/abciapp/Cargo.toml @@ -15,18 +15,18 @@ path = "src/bins/abcid.rs" [dependencies] parking_lot = "0.12" -base64 = "0.12" +base64 = "0.13" bincode = "1.3.1" tracing = "0.1" rand = "0.8" -rand_chacha = "0.2" -rand_core = { version = "0.5", default-features = false, features = ["alloc"] } +rand_chacha = "0.3" +rand_core = { version = "0.6", default-features = false, features = ["alloc"] } attohttpc = { version = "0.23", default-features = false, features = ["compress", "json", "tls-rustls"] } serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0.40" lazy_static = "1.4.0" futures = { version = "0.3.16", features = ["thread-pool"] } -hex = "0.4.2" +hex = "0.4.3" ctrlc = { version = "=3.2.5", features = ["termination"] } protobuf = "2.16" toml = "0.5.8" @@ -41,15 +41,14 @@ percent-encoding = "2.1.0" nix = "0.22.1" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } ruc = { version = "1.0.5", default-features = false, features = ["compact"] } abci = { git = "https://github.com/FindoraNetwork/tendermint-abci", tag = "0.7.6" } config = { path = "../config"} ledger = { path = "../../ledger" } -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } -cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", tag = "v1.0.0" } - +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } +cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", branch = "develop" } finutils = { path = "../finutils" } tempfile = "3.1.0" diff --git a/src/components/abciapp/src/abci/server/callback/mod.rs b/src/components/abciapp/src/abci/server/callback/mod.rs index d0ae04da8..081c1d023 100644 --- a/src/components/abciapp/src/abci/server/callback/mod.rs +++ b/src/components/abciapp/src/abci/server/callback/mod.rs @@ -7,7 +7,7 @@ use ledger::{ data_model::ASSET_TYPE_FRA, staking::{FF_ADDR_EXTRA_120_0000, FF_ADDR_LIST}, }; -use zei::xfr::asset_record::AssetRecordType; +use zei::noah_api::xfr::asset_record::AssetRecordType; mod utils; diff --git a/src/components/abciapp/src/abci/server/callback/utils.rs b/src/components/abciapp/src/abci/server/callback/utils.rs index 109bf5ec2..767fe014e 100644 --- a/src/components/abciapp/src/abci/server/callback/utils.rs +++ b/src/components/abciapp/src/abci/server/callback/utils.rs @@ -6,7 +6,7 @@ use { protobuf::RepeatedField, serde::Serialize, std::time::SystemTime, - zei::xfr::structs::{XfrAmount, XfrAssetType}, + zei::noah_api::xfr::structs::{XfrAmount, XfrAssetType}, }; /// generate attr(tags) for index-ops of tendermint diff --git a/src/components/abciapp/src/abci/staking/mod.rs b/src/components/abciapp/src/abci/staking/mod.rs index d65de6ae3..4b0fd6422 100644 --- a/src/components/abciapp/src/abci/staking/mod.rs +++ b/src/components/abciapp/src/abci/staking/mod.rs @@ -39,6 +39,7 @@ use { ops::{Deref, DerefMut}, sync::atomic::Ordering, }, + zei::XfrPublicKey, }; // The top 50~ candidate validators @@ -365,7 +366,7 @@ pub fn system_prism_mint_pay( let atc = AssetTypeCode { val: mint.asset }; let at = if let Some(mut at) = la.get_asset_type(&atc) { at.properties.issuer = IssuerPublicKey { - key: *BLACK_HOLE_PUBKEY_STAKING, + key: XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), }; if mint.max_supply != 0 { at.properties.asset_rules.max_units = Some(mint.max_supply); @@ -375,7 +376,7 @@ pub fn system_prism_mint_pay( } else { let mut at = AssetType::default(); at.properties.issuer = IssuerPublicKey { - key: *BLACK_HOLE_PUBKEY_STAKING, + key: XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), }; if mint.max_supply != 0 { diff --git a/src/components/abciapp/src/abci/staking/test.rs b/src/components/abciapp/src/abci/staking/test.rs index b046ba6fb..d51880391 100644 --- a/src/components/abciapp/src/abci/staking/test.rs +++ b/src/components/abciapp/src/abci/staking/test.rs @@ -14,10 +14,12 @@ use { rand_chacha::ChaChaRng, rand_core::SeedableRng, ruc::*, - zei::xfr::{ - asset_record::{open_blind_asset_record, AssetRecordType}, - sig::{XfrKeyPair, XfrPublicKey}, - structs::{AssetRecordTemplate, XfrAmount}, + zei::{ + noah_api::xfr::{ + asset_record::{open_blind_asset_record, AssetRecordType}, + structs::{AssetRecordTemplate, XfrAmount}, + }, + {XfrKeyPair, XfrPublicKey}, }, }; @@ -51,7 +53,7 @@ fn check_block_rewards_rate() -> Result<()> { let tx = gen_transfer_tx( &ledger, &root_kp, - &FF_PK_LIST[random::() % FF_PK_LIST.len()], + &XfrPublicKey::from_noah(&FF_PK_LIST[random::() % FF_PK_LIST.len()]), FRA_PRE_ISSUE_AMOUNT / 200, seq_id, ) @@ -99,7 +101,8 @@ fn gen_transfer_tx( ) -> Result { let mut tx_builder = TransactionBuilder::from_seq_id(seq_id); - let target_list = vec![(target_pk, am), (&*BLACK_HOLE_PUBKEY, TX_FEE_MIN)]; + let binding = XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY); + let target_list = vec![(target_pk, am), (&binding, TX_FEE_MIN)]; let mut trans_builder = TransferOperationBuilder::new(); @@ -118,7 +121,11 @@ fn gen_transfer_tx( continue; } - open_blind_asset_record(&utxo.0.record, &owner_memo, owner_kp) + open_blind_asset_record( + &utxo.0.record.into_noah(), + &owner_memo.map(|o| o.into_noah()), + &owner_kp.into_noah(), + ) .c(d!()) .and_then(|ob| { trans_builder @@ -138,7 +145,7 @@ fn gen_transfer_tx( n, ASSET_TYPE_FRA, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - *pk, + pk.into_noah(), ) }); diff --git a/src/components/abciapp/src/api/query_server/query_api/ledger_api.rs b/src/components/abciapp/src/api/query_server/query_api/ledger_api.rs index f40706e47..9c45577a4 100644 --- a/src/components/abciapp/src/api/query_server/query_api/ledger_api.rs +++ b/src/components/abciapp/src/api/query_server/query_api/ledger_api.rs @@ -13,8 +13,8 @@ use { globutils::HashOf, ledger::{ data_model::{ - AssetType, AssetTypeCode, AuthenticatedUtxo, StateCommitmentData, TxnSID, - TxoSID, UnAuthenticatedUtxo, Utxo, + AssetType, AssetTypeCode, AssetTypePrefix, AuthenticatedUtxo, StateCommitmentData, + TxnSID, TxoSID, UnAuthenticatedUtxo, Utxo, }, staking::{ DelegationRwdDetail, DelegationState, Staking, TendermintAddr, @@ -25,7 +25,7 @@ use { ruc::*, serde::{Deserialize, Serialize}, std::{collections::BTreeMap, mem, sync::Arc}, - zei::xfr::{sig::XfrPublicKey, structs::OwnerMemo}, + zei::{OwnerMemo, XfrPublicKey}, }; /// Ping route to check for liveness of API @@ -149,6 +149,27 @@ pub async fn query_asset( } } +/// get_derived asset code according to `AssetTypeCode` +pub async fn get_derived_asset_code( + data: web::Data>>, + info: web::Path, +) -> actix_web::Result> { + let qs = data.read(); + if let Ok(token_code) = AssetTypeCode::new_from_base64(&info) { + let derived_asset_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &token_code, + &CFG.checkpoint, + qs.ledger_cloned.get_tendermint_height(), + ); + Ok(web::Json(derived_asset_code.to_base64())) + } else { + Err(actix_web::error::ErrorBadRequest( + "Invalid asset definition encoding.", + )) + } +} + /// query tx according to `TxnSID` pub async fn query_txn( data: web::Data>>, @@ -698,6 +719,7 @@ pub enum ApiRoutes { UtxoSidList, AssetIssuanceNum, AssetToken, + GetDerivedAssetCode, GlobalState, TxnSid, TxnSidLight, @@ -717,6 +739,7 @@ impl NetworkRoute for ApiRoutes { ApiRoutes::UtxoSidList => "utxo_sid_list", ApiRoutes::AssetIssuanceNum => "asset_issuance_num", ApiRoutes::AssetToken => "asset_token", + ApiRoutes::GetDerivedAssetCode => "get_derived_asset_code", ApiRoutes::GlobalState => "global_state", ApiRoutes::TxnSid => "txn_sid", ApiRoutes::TxnSidLight => "txn_sid_light", diff --git a/src/components/abciapp/src/api/query_server/query_api/mod.rs b/src/components/abciapp/src/api/query_server/query_api/mod.rs index e90d15ae2..325a078d1 100644 --- a/src/components/abciapp/src/api/query_server/query_api/mod.rs +++ b/src/components/abciapp/src/api/query_server/query_api/mod.rs @@ -33,10 +33,7 @@ use { sync::Arc, }, tracing::info, - zei::{ - serialization::ZeiFromToBytes, - xfr::{sig::XfrPublicKey, structs::OwnerMemo}, - }, + zei::{noah_algebra::serialization::NoahFromToBytes, OwnerMemo, XfrPublicKey}, }; /// Returns the git commit hash and commit date of this build @@ -160,7 +157,7 @@ pub async fn get_created_assets( info: web::Path, ) -> actix_web::Result>> { // Convert from base64 representation - let key: XfrPublicKey = XfrPublicKey::zei_from_bytes( + let key: XfrPublicKey = XfrPublicKey::noah_from_bytes( &b64dec(&*info) .c(d!()) .map_err(|e| error::ErrorBadRequest(e.to_string()))?, @@ -178,7 +175,7 @@ pub async fn get_issued_records( info: web::Path, ) -> actix_web::Result)>>> { // Convert from base64 representation - let key: XfrPublicKey = XfrPublicKey::zei_from_bytes( + let key: XfrPublicKey = XfrPublicKey::noah_from_bytes( &b64dec(&*info) .c(d!()) .map_err(|e| error::ErrorBadRequest(e.to_string()))?, @@ -388,7 +385,7 @@ pub async fn get_related_txns( info: web::Path, ) -> actix_web::Result>> { // Convert from base64 representation - let key: XfrPublicKey = XfrPublicKey::zei_from_bytes( + let key: XfrPublicKey = XfrPublicKey::noah_from_bytes( &b64dec(&*info) .c(d!()) .map_err(|e| error::ErrorBadRequest(e.to_string()))?, @@ -452,8 +449,8 @@ pub async fn get_total_supply( data: web::Data>>, ) -> actix_web::Result>, actix_web::error::Error> { let l = data.read(); - let burn_pubkey = *BLACK_HOLE_PUBKEY; - let extra_pubkey = *FF_PK_EXTRA_120_0000; + let burn_pubkey = XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY); + let extra_pubkey = XfrPublicKey::from_noah(&FF_PK_EXTRA_120_0000); let burn_balance = l .ledger_cloned @@ -596,6 +593,10 @@ impl QueryApi { &ApiRoutes::AssetToken.with_arg_template("code"), web::get().to(query_asset), ) + .route( + &ApiRoutes::GetDerivedAssetCode.with_arg_template("code"), + web::get().to(get_derived_asset_code), + ) .route( &ApiRoutes::GlobalState.route(), web::get().to(query_global_state), diff --git a/src/components/abciapp/src/api/query_server/query_api/server.rs b/src/components/abciapp/src/api/query_server/query_api/server.rs index f05e5ebf2..a1198a4d8 100644 --- a/src/components/abciapp/src/api/query_server/query_api/server.rs +++ b/src/components/abciapp/src/api/query_server/query_api/server.rs @@ -15,7 +15,7 @@ use { parking_lot::{Condvar, Mutex, RwLock}, ruc::*, std::{collections::HashSet, sync::Arc}, - zei::xfr::structs::OwnerMemo, + zei::OwnerMemo, }; lazy_static! { diff --git a/src/components/config/Cargo.toml b/src/components/config/Cargo.toml index ec2670aee..fc41b5e6b 100644 --- a/src/components/config/Cargo.toml +++ b/src/components/config/Cargo.toml @@ -16,7 +16,7 @@ serde_json = "1.0" serde-strz = "1.1.1" toml = "0.5.8" -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } [target.'cfg(target_os= "linux")'.dependencies] btm = "0.1.6" diff --git a/src/components/config/src/abci/mod.rs b/src/components/config/src/abci/mod.rs index 66b6ec98b..9d92ac6ae 100644 --- a/src/components/config/src/abci/mod.rs +++ b/src/components/config/src/abci/mod.rs @@ -103,6 +103,9 @@ pub struct CheckPointConfig { #[serde(default = "def_utxo_asset_prefix_height")] pub utxo_asset_prefix_height: u64, + #[serde(default = "def_utxo_asset_prefix_height_2nd_update")] + pub utxo_asset_prefix_height_2nd_update: u64, + #[serde(default = "def_prismxx_inital_height")] pub prismxx_inital_height: i64, @@ -172,6 +175,10 @@ fn def_prismxx_inital_height() -> i64 { DEFAULT_CHECKPOINT_CONFIG.prismxx_inital_height } +fn def_utxo_asset_prefix_height_2nd_update() -> u64 { + DEFAULT_CHECKPOINT_CONFIG.utxo_asset_prefix_height_2nd_update +} + fn def_prism_bridge_address() -> String { DEFAULT_CHECKPOINT_CONFIG.prism_bridge_address.clone() } @@ -255,6 +262,7 @@ lazy_static! { check_signatures_num: 0, fix_deliver_tx_revert_nonce_height: 0, utxo_asset_prefix_height: 0, + utxo_asset_prefix_height_2nd_update: 0, prismxx_inital_height: 128, prism_bridge_address: "0x5f9552fEd754F20B636C996DaDB32806554Bb995".to_owned(), remove_fake_staking_hash: 0, @@ -302,6 +310,7 @@ lazy_static! { check_signatures_num: 4004430, fix_deliver_tx_revert_nonce_height: 4004430, utxo_asset_prefix_height: 4004430, + utxo_asset_prefix_height_2nd_update: 5000_0000, prismxx_inital_height: 4004430, prism_bridge_address: "0x4672372fDB139B7295Fc59b55b43EC5fF2761A0b".to_owned(), remove_fake_staking_hash: 4004430, diff --git a/src/components/contracts/baseapp/Cargo.toml b/src/components/contracts/baseapp/Cargo.toml index 5a2598c54..65cdd155b 100644 --- a/src/components/contracts/baseapp/Cargo.toml +++ b/src/components/contracts/baseapp/Cargo.toml @@ -22,10 +22,10 @@ protobuf = "2.16" ruc = "1.0" serde = {version = "1.0.124", features = ["derive"]} serde_json = "1.0.40" -storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } -fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } -sha3 = "0.8" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } +fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } +sha3 = "0.10" +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } config = { path = "../../config"} diff --git a/src/components/contracts/baseapp/src/staking.rs b/src/components/contracts/baseapp/src/staking.rs index a99f360f2..74cfc7e97 100644 --- a/src/components/contracts/baseapp/src/staking.rs +++ b/src/components/contracts/baseapp/src/staking.rs @@ -15,7 +15,8 @@ use module_evm::{ use ruc::{d, Result, RucResult}; use sha3::{Digest, Keccak256}; use std::{collections::BTreeMap, str::FromStr}; -use zei::xfr::sig::XfrPublicKey; +use zei::noah_algebra::prelude::NoahFromToBytes; +use zei::XfrPublicKey; impl EVMStaking for BaseApp { fn import_validators( @@ -41,7 +42,7 @@ impl EVMStaking for BaseApp { memo: serde_json::to_string(&v.memo).c(d!())?, rate: mapping_rate(v.commission_rate), staker: mapping_address(&v.id), - staker_pk: v.id.as_bytes().to_vec(), + staker_pk: v.id.noah_to_bytes(), power: U256::from(v.td_power), begin_block: U256::from(begin_block), }); @@ -111,7 +112,7 @@ impl EVMStaking for BaseApp { delegators.push(DelegatorParam { validator: *validator_address, delegator: delegator_address, - delegator_pk: public_key.as_bytes().to_vec(), + delegator_pk: public_key.noah_to_bytes(), bound_amount, unbound_amount, }); @@ -182,7 +183,7 @@ impl EVMStaking for BaseApp { memo: String, rate: [u64; 2], ) -> Result<()> { - let staker_pk = staker.as_bytes().to_vec(); + let staker_pk = staker.noah_to_bytes(); let staker_address = mapping_address(staker); let amount = @@ -224,7 +225,7 @@ impl EVMStaking for BaseApp { amount: u64, td_addr: &[u8], ) -> Result<()> { - let delegator_pk = delegator.as_bytes().to_vec(); + let delegator_pk = delegator.noah_to_bytes(); let delegator_address = mapping_address(delegator); let amount = @@ -376,6 +377,6 @@ fn mapping_rate(rate: [u64; 2]) -> U256 { } pub fn mapping_address(pk: &XfrPublicKey) -> H160 { - let result = Keccak256::digest(pk.as_bytes()); + let result = Keccak256::digest(pk.noah_to_bytes()); H160::from_slice(&result.as_slice()[..20]) } diff --git a/src/components/contracts/modules/account/Cargo.toml b/src/components/contracts/modules/account/Cargo.toml index 5fedd1cad..41ab844e4 100644 --- a/src/components/contracts/modules/account/Cargo.toml +++ b/src/components/contracts/modules/account/Cargo.toml @@ -15,7 +15,7 @@ primitive-types = { version = "0.11.1", default-features = false, features = ["r ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0.64" -storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } +storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } # primitives, don't depend on any modules fp-core = { path = "../../primitives/core" } @@ -26,7 +26,7 @@ enterprise-web3 = { path = "../../primitives/enterprise-web3" } config = { path = "../../../config"} [dev-dependencies] -rand_chacha = "0.2" +rand_chacha = "0.3" parking_lot = "0.12" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } -fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } +fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } diff --git a/src/components/contracts/modules/account/src/tests.rs b/src/components/contracts/modules/account/src/tests.rs index aa07f72f4..2ce7dbc7f 100644 --- a/src/components/contracts/modules/account/src/tests.rs +++ b/src/components/contracts/modules/account/src/tests.rs @@ -11,7 +11,7 @@ use rand_chacha::rand_core::SeedableRng; use rand_chacha::ChaChaRng; use std::{env::temp_dir, sync::Arc, time::SystemTime}; use storage::state::ChainState; -use zei::xfr::sig::XfrKeyPair; +use zei::XfrKeyPair; fn setup() -> Context { let time = SystemTime::now() diff --git a/src/components/contracts/modules/ethereum/Cargo.toml b/src/components/contracts/modules/ethereum/Cargo.toml index c40e523aa..ca374d979 100644 --- a/src/components/contracts/modules/ethereum/Cargo.toml +++ b/src/components/contracts/modules/ethereum/Cargo.toml @@ -19,7 +19,7 @@ rlp = "0.5" ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0.64" -sha3 = "0.8" +sha3 = "0.10" lazy_static = "1.4.0" # primitives, don't depend on any modules @@ -37,8 +37,8 @@ enterprise-web3 = { path = "../../primitives/enterprise-web3" } baseapp = { path = "../../baseapp" } fp-mocks = { path = "../../primitives/mocks" } module-account = { path = "../account" } -storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } -fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } +storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } +fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } [features] default = [] diff --git a/src/components/contracts/modules/ethereum/src/impls.rs b/src/components/contracts/modules/ethereum/src/impls.rs index f28cde195..7c6d7567d 100644 --- a/src/components/contracts/modules/ethereum/src/impls.rs +++ b/src/components/contracts/modules/ethereum/src/impls.rs @@ -73,7 +73,7 @@ impl App { let pubkey = secp256k1_ecdsa_recover(&sig, &msg).ok()?; Some(H160::from(H256::from_slice( - Keccak256::digest(&pubkey).as_slice(), + Keccak256::digest(pubkey).as_slice(), ))) } diff --git a/src/components/contracts/modules/evm/Cargo.toml b/src/components/contracts/modules/evm/Cargo.toml index 4f57c3c6e..b865a7885 100644 --- a/src/components/contracts/modules/evm/Cargo.toml +++ b/src/components/contracts/modules/evm/Cargo.toml @@ -22,9 +22,9 @@ ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0.64" sha3 = { version = "0.10", default-features = false } -hex = "0.4.2" +hex = "0.4.3" ethabi = "17.1.0" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } protobuf = "2.16" # primitives, don't depend on any modules @@ -35,8 +35,8 @@ fp-traits = { path = "../../primitives/traits" } fp-types = { path = "../../primitives/types" } fp-utils = { path = "../../primitives/utils" } config = { path = "../../../config"} -storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } -fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } +storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } +fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } ledger = { path = "../../../../ledger" } enterprise-web3 = { path = "../../primitives/enterprise-web3" } module-ethereum = { path = "../ethereum" } @@ -44,7 +44,7 @@ module-ethereum = { path = "../ethereum" } [dev-dependencies] baseapp = { path = "../../baseapp" } fp-mocks = { path = "../../primitives/mocks" } -hex = "0.4.2" +hex = "0.4.3" module-account = { path = "../account" } serde_json = "1.0.64" diff --git a/src/components/contracts/modules/evm/precompile/anemoi/Cargo.toml b/src/components/contracts/modules/evm/precompile/anemoi/Cargo.toml index 05897e824..c8e970ed0 100644 --- a/src/components/contracts/modules/evm/precompile/anemoi/Cargo.toml +++ b/src/components/contracts/modules/evm/precompile/anemoi/Cargo.toml @@ -16,8 +16,7 @@ evm-precompile-utils = { path = "../utils"} tracing = "0.1" module-evm = { path = "../../../../modules/evm"} num_enum = { version = "0.5.4", default-features = false } -noah-algebra = { git = "https://github.com/FindoraNetwork/noah", tag = "v0.4.3-1" } -noah-crypto = { git = "https://github.com/FindoraNetwork/noah", tag = "v0.4.3-1" } +platform-lib-noah = { git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } [dev-dependencies] baseapp = { path = "../../../../baseapp" } diff --git a/src/components/contracts/modules/evm/precompile/anemoi/benches/anemoi.rs b/src/components/contracts/modules/evm/precompile/anemoi/benches/anemoi.rs index a03a28479..98fdd54e2 100644 --- a/src/components/contracts/modules/evm/precompile/anemoi/benches/anemoi.rs +++ b/src/components/contracts/modules/evm/precompile/anemoi/benches/anemoi.rs @@ -1,4 +1,4 @@ -use evm_precompile_anemoi::Anemoi; +use evm_precompile_anemoi::Anemoi381; use noah_algebra::bls12_381::BLSScalar; use noah_algebra::prelude::Scalar; use std::time::Instant; @@ -19,10 +19,10 @@ fn main() { println!("Benchmarking 2 field elements for 1000 times"); let start = Instant::now(); for _ in 0..1000 { - _ = Anemoi::execute_with_input_and_gas(&data[0..64], None); + _ = Anemoi381::execute_with_input_and_gas(&data[0..64], None); } let time = start.elapsed().as_nanos() / 1000; - let gas = Anemoi::GAS_PER_PERM; + let gas = Anemoi381::GAS_PER_PERM; println!("Result = {} ns every time", time); println!("Cost = {} every time", gas); println!("NS per gas = {}", (time as f64) / (gas as f64)); @@ -30,10 +30,10 @@ fn main() { println!("Benchmarking 32 field elements for 1000 times"); let start = Instant::now(); for _ in 0..1000 { - _ = Anemoi::execute_with_input_and_gas(&data[0..1024], None); + _ = Anemoi381::execute_with_input_and_gas(&data[0..1024], None); } let time = start.elapsed().as_nanos() / 1000; - let gas = Anemoi::GAS_PER_PERM * 11; + let gas = Anemoi381::GAS_PER_PERM * 11; println!("Result = {} ns every time", time); println!("Cost = {} every time", gas); println!("NS per gas = {}", (time as f64) / (gas as f64)); diff --git a/src/components/contracts/modules/evm/precompile/anemoi/src/lib.rs b/src/components/contracts/modules/evm/precompile/anemoi/src/lib.rs index 49e824828..5204468aa 100644 --- a/src/components/contracts/modules/evm/precompile/anemoi/src/lib.rs +++ b/src/components/contracts/modules/evm/precompile/anemoi/src/lib.rs @@ -1,16 +1,21 @@ use evm::executor::stack::{PrecompileFailure, PrecompileOutput}; use evm::{Context, ExitError, ExitSucceed}; use module_evm::precompile::{FinState, Precompile, PrecompileId, PrecompileResult}; -use noah_algebra::bls12_381::BLSScalar; -use noah_algebra::prelude::Scalar; -use noah_crypto::basic::anemoi_jive::{AnemoiJive, AnemoiJive381}; +use platform_lib_noah::noah_algebra::{ + bls12_381::BLSScalar, bn254::BN254Scalar, prelude::Scalar, +}; +#[allow(deprecated)] +use platform_lib_noah::noah_crypto::anemoi_jive::{ + bls12_381_deprecated::AnemoiJive381Deprecated, AnemoiJive, AnemoiJive254, +}; -/// The Anemoi precompile -pub struct Anemoi; +/// The Anemoi precompile for BLS12-381 +pub struct Anemoi381; -impl Anemoi { +impl Anemoi381 { pub const GAS_PER_PERM: u64 = 125000; + #[allow(deprecated)] pub fn execute_with_input_and_gas( input: &[u8], target_gas: Option, @@ -55,7 +60,8 @@ impl Anemoi { } } - let mut res = AnemoiJive381::eval_variable_length_hash(&field_elems).to_bytes(); + let mut res = + AnemoiJive381Deprecated::eval_variable_length_hash(&field_elems).to_bytes(); res.reverse(); Ok(PrecompileOutput { @@ -67,13 +73,92 @@ impl Anemoi { } } -impl PrecompileId for Anemoi { +impl PrecompileId for Anemoi381 { fn contract_id() -> u64 { 0x2002 } } -impl Precompile for Anemoi { +impl Precompile for Anemoi381 { + fn execute( + input: &[u8], + target_gas: Option, + _context: &Context, + _state: &FinState, + ) -> PrecompileResult { + Self::execute_with_input_and_gas(input, target_gas) + } +} + +/// The Anemoi precompile for BN254 +pub struct Anemoi254; + +impl Anemoi254 { + pub const GAS_PER_PERM: u64 = 125000; + + pub fn execute_with_input_and_gas( + input: &[u8], + target_gas: Option, + ) -> PrecompileResult { + if input.len() % 32 != 0 { + return Err(PrecompileFailure::Error { + exit_status: ExitError::Other( + "input must be multiplies of 32 bytes".into(), + ), + }); + } + + let num_elems = input.len() / 32; + + let gas_cost = ((num_elems + 2) / 3) as u64 * Self::GAS_PER_PERM; + if let Some(gas_left) = target_gas { + if gas_left < gas_cost { + return Err(PrecompileFailure::Error { + exit_status: ExitError::OutOfGas, + }); + } + }; + + let mut field_elems = Vec::with_capacity(num_elems); + + for i in 0..num_elems { + let res = BN254Scalar::from_bytes( + &input[i * 32..(i + 1) * 32] + .iter() + .rev() + .copied() + .collect::>(), + ); + if let Ok(res) = res { + field_elems.push(res); + } else { + return Err(PrecompileFailure::Error { + exit_status: ExitError::Other( + "Cannot convert bytes to field elements".into(), + ), + }); + } + } + + let mut res = AnemoiJive254::eval_variable_length_hash(&field_elems).to_bytes(); + res.reverse(); + + Ok(PrecompileOutput { + exit_status: ExitSucceed::Returned, + cost: gas_cost, + output: res.to_vec(), + logs: Default::default(), + }) + } +} + +impl PrecompileId for Anemoi254 { + fn contract_id() -> u64 { + 0x2003 + } +} + +impl Precompile for Anemoi254 { fn execute( input: &[u8], target_gas: Option, diff --git a/src/components/contracts/modules/evm/precompile/basic/Cargo.toml b/src/components/contracts/modules/evm/precompile/basic/Cargo.toml index 5f60c3d6e..e8b9ad551 100644 --- a/src/components/contracts/modules/evm/precompile/basic/Cargo.toml +++ b/src/components/contracts/modules/evm/precompile/basic/Cargo.toml @@ -16,7 +16,7 @@ harness = false [dependencies] evm = { version = "0.35.0", default-features = false, features = ["with-serde"] } module-evm = { path = "../../../../modules/evm"} -ripemd160 = "0.9" +ripemd = "0.1" # primitives #fp-core = { path = "../../../../primitives/core" } diff --git a/src/components/contracts/modules/evm/precompile/basic/src/lib.rs b/src/components/contracts/modules/evm/precompile/basic/src/lib.rs index 4a8ebab8d..c1cf4662b 100644 --- a/src/components/contracts/modules/evm/precompile/basic/src/lib.rs +++ b/src/components/contracts/modules/evm/precompile/basic/src/lib.rs @@ -98,10 +98,10 @@ impl LinearCostPrecompile for Ripemd160 { input: &[u8], _cost: u64, ) -> core::result::Result<(ExitSucceed, Vec), PrecompileFailure> { - use ripemd160::Digest; + use ripemd::Digest; let mut ret = [0u8; 32]; - ret[12..32].copy_from_slice(&ripemd160::Ripemd160::digest(input)); + ret[12..32].copy_from_slice(&ripemd::Ripemd160::digest(input)); Ok((ExitSucceed::Returned, ret.to_vec())) } } diff --git a/src/components/contracts/modules/evm/precompile/frc20/Cargo.toml b/src/components/contracts/modules/evm/precompile/frc20/Cargo.toml index e5845d173..b4d318269 100644 --- a/src/components/contracts/modules/evm/precompile/frc20/Cargo.toml +++ b/src/components/contracts/modules/evm/precompile/frc20/Cargo.toml @@ -22,4 +22,4 @@ config = { path = "../../../../../config" } [dev-dependencies] baseapp = { path = "../../../../baseapp" } fp-mocks = { path = "../../../../primitives/mocks" } -sha3 = "0.8" +sha3 = "0.10" diff --git a/src/components/contracts/modules/evm/precompile/modexp/Cargo.toml b/src/components/contracts/modules/evm/precompile/modexp/Cargo.toml index 1e046763a..27630ce3b 100644 --- a/src/components/contracts/modules/evm/precompile/modexp/Cargo.toml +++ b/src/components/contracts/modules/evm/precompile/modexp/Cargo.toml @@ -15,5 +15,5 @@ num = { version = "0.4", features = ["alloc"] } ethereum-types = { version = "0.13.1", default-features = false } [dev-dependencies] -hex = "0.4.2" +hex = "0.4.3" fp-mocks = { path = "../../../../primitives/mocks" } diff --git a/src/components/contracts/modules/evm/precompile/src/lib.rs b/src/components/contracts/modules/evm/precompile/src/lib.rs index 994ec14ae..266b7d6aa 100644 --- a/src/components/contracts/modules/evm/precompile/src/lib.rs +++ b/src/components/contracts/modules/evm/precompile/src/lib.rs @@ -3,7 +3,7 @@ use evm::{executor::stack::PrecompileSet, Context}; use module_evm::precompile::{Precompile, PrecompileResult}; use std::marker::PhantomData; -use evm_precompile_anemoi::Anemoi; +use evm_precompile_anemoi::{Anemoi254, Anemoi381}; use evm_precompile_basic::{ECRecover, Identity, Ripemd160, Sha256}; use evm_precompile_blake2::Blake2F; use evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; @@ -76,8 +76,11 @@ where a if a == H160::from_low_u64_be(FRC20::::contract_id()) => { Some(FRC20::::execute(input, target_gas, context, ctx)) } - a if a == H160::from_low_u64_be(Anemoi::contract_id()) => { - Some(Anemoi::execute(input, target_gas, context, ctx)) + a if a == H160::from_low_u64_be(Anemoi381::contract_id()) => { + Some(Anemoi381::execute(input, target_gas, context, ctx)) + } + a if a == H160::from_low_u64_be(Anemoi254::contract_id()) => { + Some(Anemoi254::execute(input, target_gas, context, ctx)) } //a if a == H160::from_low_u64_be(EthPairing::contract_id()) => { // Some(EthPairing::execute(input, target_gas, context, ctx)) diff --git a/src/components/contracts/modules/evm/precompile/utils/macro/Cargo.toml b/src/components/contracts/modules/evm/precompile/utils/macro/Cargo.toml index e3eb436e3..f0e736630 100644 --- a/src/components/contracts/modules/evm/precompile/utils/macro/Cargo.toml +++ b/src/components/contracts/modules/evm/precompile/utils/macro/Cargo.toml @@ -15,5 +15,5 @@ path = "tests/tests.rs" [dependencies] quote = "1.0" proc-macro2 = "1.0" -sha3 = "0.8" +sha3 = "0.10" syn = { version = "1.0", features = ["full", "fold", "extra-traits", "visit"] } diff --git a/src/components/contracts/modules/evm/precompile/utils/macro/src/lib.rs b/src/components/contracts/modules/evm/precompile/utils/macro/src/lib.rs index d1aad50a5..cb5263844 100644 --- a/src/components/contracts/modules/evm/precompile/utils/macro/src/lib.rs +++ b/src/components/contracts/modules/evm/precompile/utils/macro/src/lib.rs @@ -64,9 +64,7 @@ pub fn generate_function_selector(_: TokenStream, input: TokenStream) -> TokenSt Some((_, Expr::Lit(ExprLit { lit, .. }))) => { if let Lit::Str(lit_str) = lit { let selector = u32::from_be_bytes( - Keccak256::digest(lit_str.value().as_ref())[..4] - .try_into() - .unwrap(), + Keccak256::digest(lit_str.value())[..4].try_into().unwrap(), ); ident_expressions.push(variant.ident); variant_expressions.push(Expr::Lit(ExprLit { diff --git a/src/components/contracts/modules/evm/src/lib.rs b/src/components/contracts/modules/evm/src/lib.rs index 60d6400d2..9ded144a5 100644 --- a/src/components/contracts/modules/evm/src/lib.rs +++ b/src/components/contracts/modules/evm/src/lib.rs @@ -50,7 +50,8 @@ use std::marker::PhantomData; use std::str::FromStr; use system_contracts::{SystemContracts, SYSTEM_ADDR}; use utils::parse_evm_staking_coinbase_mint_event; -use zei::xfr::sig::XfrPublicKey; +use zei::noah_algebra::serialization::NoahFromToBytes; +use zei::XfrPublicKey; use crate::utils::parse_evm_staking_mint_event; @@ -149,7 +150,7 @@ impl App { let asset = Token::FixedBytes(Vec::from(_asset)); - let from = Token::Bytes(from.as_bytes().to_vec()); + let from = Token::Bytes(from.noah_to_bytes()); let to = Token::Address(*to); diff --git a/src/components/contracts/modules/evm/src/utils.rs b/src/components/contracts/modules/evm/src/utils.rs index a10e5a9c8..8ff1898d3 100644 --- a/src/components/contracts/modules/evm/src/utils.rs +++ b/src/components/contracts/modules/evm/src/utils.rs @@ -7,11 +7,9 @@ use fp_types::actions::xhub::NonConfidentialOutput; use ledger::data_model::ASSET_TYPE_FRA; use ruc::*; use zei::{ - serialization::ZeiFromToBytes, - xfr::{ - sig::XfrPublicKey, - structs::{AssetType, ASSET_TYPE_LENGTH}, - }, + noah_algebra::serialization::NoahFromToBytes, + noah_api::xfr::structs::{AssetType, ASSET_TYPE_LENGTH}, + XfrPublicKey, }; pub fn deposit_asset_event() -> Event { @@ -72,7 +70,7 @@ pub fn parse_deposit_asset_event(data: Vec) -> Result .clone() .into_bytes() .unwrap_or_default(); - let target = XfrPublicKey::zei_from_bytes(receiver.as_slice()).c(d!())?; + let target = XfrPublicKey::noah_from_bytes(receiver.as_slice()).c(d!())?; let amount = result.params[2].value.clone().into_uint().c(d!())?; @@ -235,7 +233,8 @@ pub fn parse_evm_staking_mint_event( let result = event.parse_log(log).map_err(|e| eg!(e))?; let public_key_bytes = result.params[0].value.clone().into_bytes().c(d!())?; - let public_key = XfrPublicKey::zei_from_bytes(public_key_bytes.as_slice())?; + let public_key = + XfrPublicKey::noah_from_bytes(public_key_bytes.as_slice()).c(d!())?; let amount = result.params[1].value.clone().into_uint().c(d!())?.as_u64(); @@ -292,7 +291,8 @@ pub fn parse_evm_staking_coinbase_mint_event( if public_key_bytes.is_empty() { return Ok((delegator, None, amount)); } - let public_key = XfrPublicKey::zei_from_bytes(public_key_bytes.as_slice())?; + let public_key = + XfrPublicKey::noah_from_bytes(public_key_bytes.as_slice()).c(d!())?; Ok((delegator, Some(public_key), amount)) } diff --git a/src/components/contracts/primitives/core/Cargo.toml b/src/components/contracts/primitives/core/Cargo.toml index e265036a7..ce27fb03e 100644 --- a/src/components/contracts/primitives/core/Cargo.toml +++ b/src/components/contracts/primitives/core/Cargo.toml @@ -16,9 +16,9 @@ parking_lot = "0.12" primitive-types = { version = "0.11.1", default-features = false, features = ["rlp", "byteorder", "serde"] } ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } -storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5", optional = true } -fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5", optional = true } -serde_with = { version = "1.9.4"} +storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6", optional = true } +fin_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6", optional = true } +serde_with = { version = "2.0.1"} # primitives fp-types = { path = "../types" } diff --git a/src/components/contracts/primitives/mocks/Cargo.toml b/src/components/contracts/primitives/mocks/Cargo.toml index de327d5c9..681dc54b4 100644 --- a/src/components/contracts/primitives/mocks/Cargo.toml +++ b/src/components/contracts/primitives/mocks/Cargo.toml @@ -14,11 +14,11 @@ ethereum = { version = "0.12.0", default-features = false, features = ["with-ser lazy_static = "1.4.0" libsecp256k1 = { version = "0.7", features = ["static-context", "hmac"] } primitive-types = { version = "0.11.1", default-features = false, features = ["rlp", "byteorder", "serde"] } -rand_chacha = "0.2" +rand_chacha = "0.3" rlp = "0.5" serde_json = "1.0" -sha3 = "0.8" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +sha3 = "0.10" +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } # primitives fp-traits = { path = "../traits" } diff --git a/src/components/contracts/primitives/mocks/src/lib.rs b/src/components/contracts/primitives/mocks/src/lib.rs index 37819ccf9..687ae1a52 100644 --- a/src/components/contracts/primitives/mocks/src/lib.rs +++ b/src/components/contracts/primitives/mocks/src/lib.rs @@ -20,7 +20,7 @@ use std::env::temp_dir; use std::path::PathBuf; use std::sync::Mutex; use std::time::SystemTime; -use zei::xfr::sig::XfrKeyPair; +use zei::XfrKeyPair; lazy_static! { pub static ref BASE_APP: Mutex = Mutex::new( @@ -68,7 +68,7 @@ pub fn build_signed_transaction( let signer: Address = who.get_pk().into(); let msg = serde_json::to_vec(&(function.clone(), extra.clone())).unwrap(); - let sig = who.get_sk_ref().sign(msg.as_slice(), who.get_pk_ref()); + let sig = who.get_sk_ref().sign(msg.as_slice()).unwrap(); let signature = MultiSignature::from(sig); UncheckedTransaction::new_signed(function, signer, signature, extra) diff --git a/src/components/contracts/primitives/storage/Cargo.toml b/src/components/contracts/primitives/storage/Cargo.toml index bab9bfc4c..6dca51852 100644 --- a/src/components/contracts/primitives/storage/Cargo.toml +++ b/src/components/contracts/primitives/storage/Cargo.toml @@ -14,12 +14,12 @@ paste = "1.0" ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0" -sha2 = "0.9.5" -storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } +sha2 = "0.10" +storage = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } # primitives fp-core = { path = "../core" } config = { path = "../../../config"} [dev-dependencies] -temp_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.5" } +temp_db = { git = "https://github.com/FindoraNetwork/storage.git", tag = "v1.1.6" } diff --git a/src/components/contracts/primitives/types/Cargo.toml b/src/components/contracts/primitives/types/Cargo.toml index 8b974d520..23795d7ff 100644 --- a/src/components/contracts/primitives/types/Cargo.toml +++ b/src/components/contracts/primitives/types/Cargo.toml @@ -11,21 +11,21 @@ readme = "README.md" [dependencies] bech32 = "0.7.2" ethereum = { version = "0.12.0", default-features = false, features = ["with-serde"] } -hex = "0.4.2" +hex = "0.4.3" -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } libsecp256k1 = { version = "0.7", features = ["static-context", "hmac"] } primitive-types = { version = "0.11.1", default-features = false, features = ["rlp", "byteorder", "serde"] } ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0" -sha3 = "0.8" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } -fixed-hash = "0.7.0" +sha3 = "0.10" +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } +fixed-hash = "0.8.0" # primitives fp-utils = { path = "../utils" } [dev-dependencies] -rand_chacha = "0.2" +rand_chacha = "0.3" diff --git a/src/components/contracts/primitives/types/src/actions/account.rs b/src/components/contracts/primitives/types/src/actions/account.rs index 701e091f9..dc608aa2a 100644 --- a/src/components/contracts/primitives/types/src/actions/account.rs +++ b/src/components/contracts/primitives/types/src/actions/account.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use zei::xfr::sig::XfrPublicKey; -use zei::xfr::structs::AssetType; +use zei::XfrPublicKey; +use zei::noah_api::xfr::structs::AssetType; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Action { diff --git a/src/components/contracts/primitives/types/src/actions/xhub.rs b/src/components/contracts/primitives/types/src/actions/xhub.rs index 622de4050..f74e53676 100644 --- a/src/components/contracts/primitives/types/src/actions/xhub.rs +++ b/src/components/contracts/primitives/types/src/actions/xhub.rs @@ -1,6 +1,5 @@ use serde::{Deserialize, Serialize}; -use zei::xfr::sig::XfrPublicKey; -use zei::xfr::structs::AssetType; +use zei::{noah_api::xfr::structs::AssetType, XfrPublicKey}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Action { diff --git a/src/components/contracts/primitives/types/src/crypto.rs b/src/components/contracts/primitives/types/src/crypto.rs index 7dcb34a4a..f29de6cb8 100644 --- a/src/components/contracts/primitives/types/src/crypto.rs +++ b/src/components/contracts/primitives/types/src/crypto.rs @@ -1,17 +1,19 @@ -use bech32::{FromBase32, ToBase32}; -use core::convert::TryFrom; -use core::fmt::Formatter; -use core::str::FromStr; -use fp_utils::{ecdsa, hashing::keccak_256}; -use globutils::wallet; -use hex::FromHex; -use primitive_types::{H160, H256}; -use ruc::{d, eg, RucResult}; -use serde::{Deserialize, Serialize}; -use sha3::{Digest, Keccak256}; -use std::ops::{Deref, DerefMut}; -use zei::serialization::ZeiFromToBytes; -use zei::xfr::sig::{XfrPublicKey, XfrSignature}; +use { + bech32::{FromBase32, ToBase32}, + core::convert::TryFrom, + core::fmt::Formatter, + core::str::FromStr, + fp_utils::{ecdsa, hashing::keccak_256}, + globutils::wallet, + hex::FromHex, + primitive_types::{H160, H256}, + ruc::{d, eg, RucResult}, + serde::{Deserialize, Serialize}, + sha3::{Digest, Keccak256}, + std::ops::{Deref, DerefMut}, + zei::noah_algebra::serialization::NoahFromToBytes, + zei::{XfrPublicKey, XfrSignature}, +}; /// An opaque 32-byte cryptographic identifier. #[derive( @@ -83,7 +85,7 @@ impl<'a> TryFrom<&'a [u8]> for Address32 { impl From for Address32 { fn from(k: XfrPublicKey) -> Self { - Address32::try_from(k.zei_to_bytes().as_slice()).unwrap() + Address32::try_from(k.noah_to_bytes().as_slice()).unwrap() } } @@ -205,7 +207,7 @@ pub trait Verify { /// Signature verify that can work with any known signature types.. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum MultiSignature { - /// An zei xfr signature. + /// An noah xfr signature. Xfr(XfrSignature), /// An ECDSA/SECP256k1 signature. Ecdsa(ecdsa::Signature), @@ -250,17 +252,14 @@ impl Verify for MultiSignature { fn verify(&self, msg: &[u8], signer: &Address32) -> bool { match self { - Self::Xfr(ref sig) => match XfrPublicKey::zei_from_bytes(signer.as_ref()) { - Ok(who) => sig.verify(msg, &who), - _ => false, - }, - // Self::Ecdsa(ref sig) => match sig.recover(msg) { - // Some(pubkey) => { - // &keccak_256(pubkey.as_ref()) - // == >::as_ref(signer) - // } - // _ => false, - // }, + Self::Xfr(ref sig) => { + let mut bytes = [0u8; 32]; + bytes[0..32].copy_from_slice(signer.as_ref()); + match XfrPublicKey::noah_from_bytes(&bytes) { + Ok(who) => sig.verify(msg, &who), + _ => false, + } + } Self::Ecdsa(ref sig) => { // let mut msg_hashed = [0u8; 32]; // msg_hashed.copy_from_slice(msg); @@ -269,7 +268,7 @@ impl Verify for MultiSignature { match secp256k1_ecdsa_recover(sig.as_ref(), &msg_hashed) { Ok(pubkey) => { Address32::from(H160::from(H256::from_slice( - Keccak256::digest(&pubkey).as_slice(), + Keccak256::digest(pubkey).as_slice(), ))) == signer.clone() } _ => false, @@ -281,7 +280,7 @@ impl Verify for MultiSignature { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum MultiSigner { - /// An zei xfr identity. + /// An noah xfr identity. Xfr(XfrPublicKey), // /// An SECP256k1/ECDSA identity (actually, the keccak 256 hash of the compressed pub key). // Ecdsa(ecdsa::Public), @@ -434,13 +433,13 @@ mod tests { use super::*; use rand_chacha::rand_core::SeedableRng; use rand_chacha::ChaChaRng; - use zei::xfr::sig::XfrKeyPair; + use zei::XfrKeyPair; #[test] fn xfr_sign_verify_work() { let mut prng = ChaChaRng::from_entropy(); let alice = XfrKeyPair::generate(&mut prng); - let sig = alice.get_sk_ref().sign(b"hello", alice.get_pk_ref()); + let sig = alice.get_sk_ref().sign(b"hello").unwrap(); let signer = MultiSigner::from(alice.get_pk()); let sig = MultiSignature::from(sig); assert!( diff --git a/src/components/contracts/primitives/utils/Cargo.toml b/src/components/contracts/primitives/utils/Cargo.toml index 936d60bd9..98e9c2403 100644 --- a/src/components/contracts/primitives/utils/Cargo.toml +++ b/src/components/contracts/primitives/utils/Cargo.toml @@ -10,19 +10,19 @@ readme = "README.md" [dependencies] futures = "0.3.16" -base64 = "0.12" +base64 = "0.13" bip0039 = "0.8.0" blake2-rfc = "0.2.18" byteorder = "1.4.3" -hex = "0.4.2" +hex = "0.4.3" libsecp256k1 = { version = "0.7", features = ["static-context", "hmac"] } primitive-types = { version = "0.11.1", default-features = false, features = ["rlp", "byteorder", "serde"] } protobuf = "2.16" rand = "0.8" ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } -sha2 = "0.9.5" -sha3 = "0.8" +sha2 = "0.10" +sha3 = "0.10" bip32 = "0.2.1" tiny-keccak = { version = "2.0", features = ["keccak"] } twox-hash = "1.6.0" diff --git a/src/components/contracts/primitives/utils/src/ecdsa.rs b/src/components/contracts/primitives/utils/src/ecdsa.rs index b01ed4483..0cb896f26 100644 --- a/src/components/contracts/primitives/utils/src/ecdsa.rs +++ b/src/components/contracts/primitives/utils/src/ecdsa.rs @@ -356,6 +356,7 @@ impl SecpPair { } /// Ethereum address format. + #[allow(clippy::needless_borrow)] pub fn address(&self) -> H160 { let mut res = [0u8; 64]; res.copy_from_slice(&self.public.serialize()[1..65]); diff --git a/src/components/contracts/primitives/wasm/Cargo.toml b/src/components/contracts/primitives/wasm/Cargo.toml index 3e91916d9..106d875df 100644 --- a/src/components/contracts/primitives/wasm/Cargo.toml +++ b/src/components/contracts/primitives/wasm/Cargo.toml @@ -20,7 +20,7 @@ fp-types = { path = "../../primitives/types" } fp-utils = { path = "../../primitives/utils" } rlp = "0.5" ruc = "1.0" -sha3 = "0.8" +sha3 = "0.10" serde_json = "1.0" wasm-bindgen = { version = "=0.2.84", features = ["serde-serialize"] } diff --git a/src/components/contracts/primitives/wasm/src/wasm.rs b/src/components/contracts/primitives/wasm/src/wasm.rs index 7db2c4315..41c51ed99 100644 --- a/src/components/contracts/primitives/wasm/src/wasm.rs +++ b/src/components/contracts/primitives/wasm/src/wasm.rs @@ -29,7 +29,7 @@ pub fn recover_signer(transaction: &Transaction) -> Option { let pubkey = secp256k1_ecdsa_recover(&sig, &msg).ok()?; Some(H160::from(H256::from_slice( - Keccak256::digest(&pubkey).as_slice(), + Keccak256::digest(pubkey).as_slice(), ))) } diff --git a/src/components/contracts/rpc/Cargo.toml b/src/components/contracts/rpc/Cargo.toml index 3194801d3..10400b9c5 100644 --- a/src/components/contracts/rpc/Cargo.toml +++ b/src/components/contracts/rpc/Cargo.toml @@ -38,7 +38,7 @@ rustc-hex = { version = "2.1.0" } rustc_version = "0.4.0" semver = "1.0.4" serde_json = "1.0" -sha3 = "0.8" +sha3 = "0.10" tendermint = { git = "https://github.com/FindoraNetwork/tendermint-rs", tag = "v0.19.0a-fk" } tendermint-rpc = { git = "https://github.com/FindoraNetwork/tendermint-rs", features = ["http-client", "websocket-client"], tag = "v0.19.0a-fk" } tokio = { version = "1.10.1", features = ["full"] } diff --git a/src/components/contracts/rpc/src/eth.rs b/src/components/contracts/rpc/src/eth.rs index 7a4ffff85..75ce0a2a8 100644 --- a/src/components/contracts/rpc/src/eth.rs +++ b/src/components/contracts/rpc/src/eth.rs @@ -1437,7 +1437,7 @@ fn transaction_build( { match pubkey { Some(pk) => { - H160::from(H256::from_slice(Keccak256::digest(&pk).as_slice())) + H160::from(H256::from_slice(Keccak256::digest(pk).as_slice())) } _ => H160::default(), } @@ -1613,11 +1613,11 @@ fn dummy_block(height: u64, full: bool) -> Rich { let hash = if height == (CFG.checkpoint.evm_first_block_height as u64) - 1 { H256([0; 32]) } else { - H256::from_slice(&sha3::Keccak256::digest(&height.to_le_bytes())) + H256::from_slice(&sha3::Keccak256::digest(height.to_le_bytes())) }; let parent_hash = - H256::from_slice(&sha3::Keccak256::digest(&(height - 1).to_le_bytes())); + H256::from_slice(&sha3::Keccak256::digest((height - 1).to_le_bytes())); let transactions = if full { BlockTransactions::Full(vec![]) diff --git a/src/components/contracts/rpc/src/web3.rs b/src/components/contracts/rpc/src/web3.rs index 40237395d..3cba4b8ff 100644 --- a/src/components/contracts/rpc/src/web3.rs +++ b/src/components/contracts/rpc/src/web3.rs @@ -31,7 +31,7 @@ impl Web3Api for Web3ApiImpl { fn sha3(&self, input: Bytes) -> Result { Ok(H256::from_slice( - Keccak256::digest(&input.into_vec()).as_slice(), + Keccak256::digest(input.into_vec()).as_slice(), )) } } diff --git a/src/components/finutils/Cargo.toml b/src/components/finutils/Cargo.toml index d76cef1cd..d630f1a58 100644 --- a/src/components/finutils/Cargo.toml +++ b/src/components/finutils/Cargo.toml @@ -7,28 +7,28 @@ edition = "2021" [dependencies] -hex = "0.4.2" -base64 = "0.12" +hex = "0.4.3" +base64 = "0.13" clap = { version = "2.33.3", features = ["yaml"] } lazy_static = "1.4.0" attohttpc = { version = "0.23", default-features = false, features = ["compress", "json", "tls-rustls"] } serde_json = "1.0.40" serde = { version = "1.0.124", features = ["derive"] } rand = "0.8" -rand_core = { version = "0.5", default-features = false, features = ["alloc"] } -rand_chacha = "0.2" -curve25519-dalek = { version = "3.0", features = ["serde"] } +rand_core = { version = "0.6", default-features = false, features = ["alloc"] } +rand_chacha = "0.3" +noah-curve25519-dalek = { version = "4.0.0", features = ["serde"] } wasm-bindgen = { version = "=0.2.84", features = ["serde-serialize"] } sha2 = "0.10" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } ruc = "1.0" rucv4 = { package = "ruc", version = "4.0" } nix = "0.25" ledger = { path = "../../ledger" } -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } -credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", tag = "v1.0.0" } +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } +credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", branch = "develop" } eth_checksum = { version = "0.1.2", optional = true } fp-core = { path = "../contracts/primitives/core", default-features = false } diff --git a/src/components/finutils/src/bins/stt/init/mod.rs b/src/components/finutils/src/bins/stt/init/mod.rs index a5a372eb4..606f9931f 100644 --- a/src/components/finutils/src/bins/stt/init/mod.rs +++ b/src/components/finutils/src/bins/stt/init/mod.rs @@ -44,7 +44,7 @@ pub fn init(mut interval: u64, is_mainnet: bool, skip_validator: bool) -> Result .values() .map(|u| &u.pubkey) .chain(VALIDATOR_LIST.values().map(|v| &v.pubkey)) - .map(|pk| (pk, FRA_PRE_ISSUE_AMOUNT / 2_000)) + .map(|pk| (*pk, FRA_PRE_ISSUE_AMOUNT / 2_000)) .collect::>(); // Wallet Address: fra18xkez3fum44jq0zhvwq380rfme7u624cccn3z56fjeex6uuhpq6qv9e4g5 @@ -56,7 +56,7 @@ pub fn init(mut interval: u64, is_mainnet: bool, skip_validator: bool) -> Result let bank = pnk!(wallet::public_key_from_base64( "Oa2RRTzdayA8V2OBE7xp3n3NKrjGJxFTSZZybXOXCDQ=" )); - target_list.push((&bank, FRA_PRE_ISSUE_AMOUNT / 100 * 98)); + target_list.push((bank, FRA_PRE_ISSUE_AMOUNT / 100 * 98)); println!(">>> Transfer FRAs to validators ..."); common::utils::transfer_batch(&root_kp, target_list, None, true, true) diff --git a/src/components/finutils/src/bins/stt/stt.rs b/src/components/finutils/src/bins/stt/stt.rs index 84eb29643..082f61fe9 100644 --- a/src/components/finutils/src/bins/stt/stt.rs +++ b/src/components/finutils/src/bins/stt/stt.rs @@ -27,7 +27,7 @@ use { ruc::*, serde::Serialize, std::{collections::BTreeMap, env}, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey}, + zei::{BlindAssetRecord, XfrKeyPair, XfrPublicKey}, }; lazy_static! { @@ -210,8 +210,8 @@ mod issue { }, rand_chacha::rand_core::SeedableRng, rand_chacha::ChaChaRng, - zei::setup::PublicParams, - zei::xfr::{ + zei::noah_algebra::ristretto::PedersenCommitmentRistretto, + zei::noah_api::xfr::{ asset_record::{build_blind_asset_record, AssetRecordType}, structs::AssetRecordTemplate, }, @@ -233,21 +233,21 @@ mod issue { FRA_PRE_ISSUE_AMOUNT / 2, ASSET_TYPE_FRA, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - root_kp.get_pk(), + root_kp.get_pk().into_noah(), ); - let params = PublicParams::default(); + let pc_gens = PedersenCommitmentRistretto::default(); let outputs = (0..2) .map(|_| { let (ba, _, _) = build_blind_asset_record( &mut ChaChaRng::from_entropy(), - ¶ms.pc_gens, + &pc_gens, &template, vec![], ); ( TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None, @@ -271,7 +271,7 @@ mod issue { } mod delegate { - use {super::*, zei::xfr::asset_record::AssetRecordType}; + use {super::*, zei::noah_api::xfr::asset_record::AssetRecordType}; pub fn gen_tx( user: NameRef, @@ -291,7 +291,7 @@ mod delegate { common::utils::gen_transfer_op( owner_kp, - vec![(&BLACK_HOLE_PUBKEY_STAKING, amount)], + vec![(XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), amount)], None, false, false, diff --git a/src/components/finutils/src/common/ddev/init.rs b/src/components/finutils/src/common/ddev/init.rs index 3db94fca6..63261be3a 100644 --- a/src/components/finutils/src/common/ddev/init.rs +++ b/src/components/finutils/src/common/ddev/init.rs @@ -17,10 +17,8 @@ use ledger::{ }; use ruc::*; use serde::{Deserialize, Serialize}; -use zei::xfr::{ - asset_record::AssetRecordType, - sig::{XfrKeyPair, XfrPublicKey, XfrSecretKey}, -}; +use zei::noah_api::xfr::asset_record::AssetRecordType; +use zei::{XfrKeyPair, XfrPublicKey, XfrSecretKey}; #[derive(Deserialize)] struct TmValidators { @@ -102,7 +100,7 @@ pub(super) fn init(env: &mut Env) -> Result<()> { .custom_data .initial_validators .iter() - .map(|v| (v.xfr_keypair.get_pk_ref(), 500_0000 * FRA)) + .map(|v| (v.xfr_keypair.get_pk(), 500_0000 * FRA)) .collect::>(); println!("[ {} ] >>> Transfer FRAs to validators ...", &env.name); @@ -118,7 +116,7 @@ pub(super) fn init(env: &mut Env) -> Result<()> { gen_transfer_op_xx( Some(&gen_8668_endpoint(env)), &v.xfr_keypair, - vec![(&BLACK_HOLE_PUBKEY_STAKING, am)], + vec![(XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), am)], None, true, false, @@ -174,7 +172,7 @@ fn send_tx(env: &Env, tx: &Transaction) -> Result<()> { fn transfer_batch( env: &Env, owner_kp: &XfrKeyPair, - target_list: Vec<(&XfrPublicKey, u64)>, + target_list: Vec<(XfrPublicKey, u64)>, token_code: Option, confidential_am: bool, confidential_ty: bool, diff --git a/src/components/finutils/src/common/evm.rs b/src/components/finutils/src/common/evm.rs index 14dfde63e..6dd2ff291 100644 --- a/src/components/finutils/src/common/evm.rs +++ b/src/components/finutils/src/common/evm.rs @@ -29,7 +29,8 @@ use tendermint::block::Height; use tendermint_rpc::endpoint::abci_query::AbciQuery; use tendermint_rpc::{Client, HttpClient}; use tokio::runtime::Runtime; -use zei::xfr::{asset_record::AssetRecordType, sig::XfrKeyPair}; +use zei::noah_api::xfr::asset_record::AssetRecordType; +use zei::{XfrKeyPair, XfrPublicKey}; /// transfer utxo assets to account(ed25519 or ecdsa address) balance. pub fn transfer_to_account( @@ -51,7 +52,7 @@ pub fn transfer_to_account( let transfer_op = utils::gen_transfer_op( &kp, - vec![(&BLACK_HOLE_PUBKEY_STAKING, amount)], + vec![(XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), amount)], asset, false, false, @@ -94,7 +95,7 @@ impl Keypair { match self { Keypair::Ecdsa(kp) => MultiSignature::from(kp.sign(data)), Keypair::Ed25519(kp) => { - MultiSignature::from(kp.get_sk_ref().sign(data, kp.get_pk_ref())) + MultiSignature::from(kp.get_sk_ref().sign(data).unwrap()) } } } diff --git a/src/components/finutils/src/common/mod.rs b/src/components/finutils/src/common/mod.rs index 534364f6c..c460a7847 100644 --- a/src/components/finutils/src/common/mod.rs +++ b/src/components/finutils/src/common/mod.rs @@ -37,11 +37,8 @@ use { utils::{get_block_height, get_local_block_height, parse_td_validator_keys}, web3::types::H160, zei::{ - setup::PublicParams, - xfr::{ - asset_record::AssetRecordType, - sig::{XfrKeyPair, XfrPublicKey, XfrSecretKey}, - }, + noah_api::xfr::asset_record::AssetRecordType, XfrKeyPair, XfrPublicKey, + XfrSecretKey, }, }; @@ -151,7 +148,7 @@ pub fn stake( .c(d!())?; utils::gen_transfer_op( &kp, - vec![(&BLACK_HOLE_PUBKEY_STAKING, am)], + vec![(XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), am)], None, false, false, @@ -190,7 +187,7 @@ pub fn stake_append( builder.add_operation_delegation(&kp, am, td_addr); utils::gen_transfer_op( &kp, - vec![(&BLACK_HOLE_PUBKEY_STAKING, am)], + vec![(XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), am)], None, false, false, @@ -481,7 +478,7 @@ pub fn transfer_asset_batch_x( ) -> Result<()> { utils::transfer_batch( kp, - target_addr.iter().map(|addr| (addr, am)).collect(), + target_addr.iter().map(|addr| (*addr, am)).collect(), token_code, confidential_am, confidential_ty, @@ -699,7 +696,7 @@ fn gen_delegate_tx( utils::gen_transfer_op( owner_kp, - vec![(&BLACK_HOLE_PUBKEY_STAKING, amount)], + vec![(XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING), amount)], None, false, false, @@ -753,7 +750,7 @@ pub fn create_asset_x( code: Option, ) -> Result { let code = code.unwrap_or_else(AssetTypeCode::gen_random); - let asset_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + let asset_code = AssetTypeCode::from_prefix_and_raw_asset_type_code_2nd_update( AssetTypePrefix::UserDefined, &code, ); @@ -806,7 +803,6 @@ pub fn issue_asset_x( builder.get_seq_id(), amount, confidentiality_flags, - &PublicParams::default(), ) .c(d!())?; utils::gen_fee_op(kp) diff --git a/src/components/finutils/src/common/utils.rs b/src/components/finutils/src/common/utils.rs index 9b0dfc99a..0849dbf2d 100644 --- a/src/components/finutils/src/common/utils.rs +++ b/src/components/finutils/src/common/utils.rs @@ -35,10 +35,12 @@ use { types::{BlockId, BlockNumber, Bytes, CallRequest, H160}, Web3, }, - zei::xfr::{ - asset_record::{open_blind_asset_record, AssetRecordType}, - sig::{XfrKeyPair, XfrPublicKey}, - structs::{AssetRecordTemplate, OwnerMemo}, + zei::{ + noah_api::xfr::{ + asset_record::{open_blind_asset_record, AssetRecordType}, + structs::{AssetRecordTemplate, OwnerMemo}, + }, + {XfrKeyPair, XfrPublicKey}, }, }; @@ -102,7 +104,7 @@ pub fn transfer( } transfer_batch( owner_kp, - vec![(target_pk, am)], + vec![(*target_pk, am)], token_code, confidential_am, confidential_ty, @@ -114,7 +116,7 @@ pub fn transfer( #[allow(missing_docs)] pub fn transfer_batch( owner_kp: &XfrKeyPair, - target_list: Vec<(&XfrPublicKey, u64)>, + target_list: Vec<(XfrPublicKey, u64)>, token_code: Option, confidential_am: bool, confidential_ty: bool, @@ -142,7 +144,7 @@ pub fn transfer_batch( #[inline(always)] pub fn gen_transfer_op( owner_kp: &XfrKeyPair, - target_list: Vec<(&XfrPublicKey, u64)>, + target_list: Vec<(XfrPublicKey, u64)>, token_code: Option, confidential_am: bool, confidential_ty: bool, @@ -163,7 +165,7 @@ pub fn gen_transfer_op( #[allow(missing_docs)] pub fn gen_transfer_op_x( owner_kp: &XfrKeyPair, - target_list: Vec<(&XfrPublicKey, u64)>, + target_list: Vec<(XfrPublicKey, u64)>, token_code: Option, auto_fee: bool, confidential_am: bool, @@ -188,7 +190,7 @@ pub fn gen_transfer_op_x( pub fn gen_transfer_op_xx( rpc_endpoint: Option<&str>, owner_kp: &XfrKeyPair, - mut target_list: Vec<(&XfrPublicKey, u64)>, + mut target_list: Vec<(XfrPublicKey, u64)>, token_code: Option, auto_fee: bool, confidential_am: bool, @@ -197,7 +199,7 @@ pub fn gen_transfer_op_xx( ) -> Result { let mut op_fee: u64 = 0; if auto_fee { - target_list.push((&*BLACK_HOLE_PUBKEY, TX_FEE_MIN)); + target_list.push((XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), TX_FEE_MIN)); op_fee += TX_FEE_MIN; } let asset_type = token_code.map(|code| code.val).unwrap_or(ASSET_TYPE_FRA); @@ -217,8 +219,12 @@ pub fn gen_transfer_op_xx( .into_iter(); for (sid, (utxo, owner_memo)) in utxos { - let oar = - open_blind_asset_record(&utxo.0.record, &owner_memo, owner_kp).c(d!())?; + let oar = open_blind_asset_record( + &utxo.0.record.into_noah(), + &owner_memo, + &owner_kp.into_noah(), + ) + .c(d!())?; if oar.asset_type != asset_type && oar.asset_type != ASSET_TYPE_FRA { continue; @@ -278,7 +284,7 @@ pub fn gen_transfer_op_xx( n, token_code.map(|code| code.val).unwrap_or(ASSET_TYPE_FRA), art, - *pk, + pk.into_noah(), ) }); @@ -468,9 +474,13 @@ pub fn get_asset_balance(kp: &XfrKeyPair, asset: Option) -> Resul .c(d!())? .values() .map(|(utxo, owner_memo)| { - open_blind_asset_record(&utxo.0.record, owner_memo, kp) - .c(d!()) - .map(|obr| alt!(obr.asset_type == asset_type, obr.amount, 0)) + open_blind_asset_record( + &utxo.0.record.into_noah(), + owner_memo, + &kp.into_noah(), + ) + .c(d!()) + .map(|obr| alt!(obr.asset_type == asset_type, obr.amount, 0)) }) .collect::>>() .c(d!())? @@ -488,7 +498,9 @@ pub fn get_asset_all(kp: &XfrKeyPair) -> Result> { let mut set = BTreeMap::new(); for (_k, v) in info { - let res = open_blind_asset_record(&v.0 .0.record, &v.1, kp)?; + let res = + open_blind_asset_record(&v.0 .0.record.into_noah(), &v.1, &kp.into_noah()) + .c(d!())?; let code = AssetTypeCode { val: res.asset_type, diff --git a/src/components/finutils/src/txn_builder/mod.rs b/src/components/finutils/src/txn_builder/mod.rs index dc4e37c45..032a9ad9e 100644 --- a/src/components/finutils/src/txn_builder/mod.rs +++ b/src/components/finutils/src/txn_builder/mod.rs @@ -7,7 +7,6 @@ use { credentials::CredUserSecretKey, - curve25519_dalek::scalar::Scalar, fp_types::{crypto::MultiSigner, H160}, globutils::SignatureOf, ledger::{ @@ -36,6 +35,7 @@ use { TendermintAddr, Validator, }, }, + noah_curve25519_dalek::scalar::Scalar, rand_chacha::ChaChaRng, rand_core::{CryptoRng, RngCore, SeedableRng}, ruc::*, @@ -45,26 +45,26 @@ use { collections::{BTreeMap, HashSet}, }, tendermint::PrivateKey, - zei::{ - api::anon_creds::{ + zei::noah_algebra::prelude::*, + zei::noah_algebra::ristretto::PedersenCommitmentRistretto, + zei::noah_api::{ + anon_creds::{ ac_confidential_open_commitment, ACCommitment, ACCommitmentKey, ConfidentialAC, Credential, }, - serialization::ZeiFromToBytes, - setup::PublicParams, xfr::{ asset_record::{ build_blind_asset_record, build_open_asset_record, open_blind_asset_record, AssetRecordType, }, - lib::XfrNotePolicies, - sig::{XfrKeyPair, XfrPublicKey}, structs::{ - AssetRecord, AssetRecordTemplate, BlindAssetRecord, OpenAssetRecord, - OwnerMemo, TracingPolicies, TracingPolicy, + AssetRecord, AssetRecordTemplate, OpenAssetRecord, TracingPolicies, + TracingPolicy, }, + XfrNotePolicies, }, }, + zei::{BlindAssetRecord, OwnerMemo, XfrKeyPair, XfrPublicKey}, }; macro_rules! no_transfer_err { @@ -179,9 +179,13 @@ impl TransactionBuilder { let mut am = TX_FEE_MIN; for (idx, (o, om)) in outputs.into_iter().enumerate() { if 0 < am { - if let Ok(oar) = open_blind_asset_record(&o, &om, &kp) { + if let Ok(oar) = open_blind_asset_record( + &o.into_noah(), + &om.map(|o| o.into_noah()), + &kp.into_noah(), + ) { if ASSET_TYPE_FRA == oar.asset_type - && kp.get_pk_ref().as_bytes() == o.public_key.as_bytes() + && kp.get_pk_ref().to_bytes() == o.public_key.to_bytes() { let n = alt!(oar.amount > am, am, oar.amount); am = am.saturating_sub(oar.amount); @@ -214,24 +218,40 @@ impl TransactionBuilder { /// As the last operation of any transaction, /// add a static fee to the transaction. pub fn add_fee(&mut self, inputs: FeeInputs) -> Result<&mut TransactionBuilder> { + self.add_fee_custom(inputs, TX_FEE_MIN) + } + + /// As the last operation of any transaction, + /// add a static fee to the transaction. + pub fn add_fee_custom(&mut self, inputs: FeeInputs, fee: u64) -> Result<&mut TransactionBuilder> { let mut kps = vec![]; let mut opb = TransferOperationBuilder::default(); + let mut am = fee; for i in inputs.inner.into_iter() { - open_blind_asset_record(&i.ar.record, &i.om, &i.kp) - .c(d!()) - .and_then(|oar| { - opb.add_input(i.tr, oar, None, None, i.am) - .map(|_| { - kps.push(i.kp); - }) - .c(d!()) - })?; + open_blind_asset_record( + &i.ar.record.into_noah(), + &i.om.map(|o| o.into_noah()), + &i.kp.into_noah(), + ) + .c(d!()) + .and_then(|oar| { + if oar.asset_type != ASSET_TYPE_FRA { + return Err(eg!("Incorrect fee input asset_type, expected Findora AssetType record")); + } + let n = alt!(oar.amount > am, am, oar.amount); + am = am.saturating_sub(oar.amount); + opb.add_input(i.tr, oar, None, None, n) + .map(|_| { + kps.push(i.kp); + }) + .c(d!()) + })?; } opb.add_output( &AssetRecordTemplate::with_no_asset_tracing( - TX_FEE_MIN, + fee, ASSET_TYPE_FRA, AssetRecordType::from_flags(false, false), *BLACK_HOLE_PUBKEY, @@ -245,7 +265,7 @@ impl TransactionBuilder { .and_then(|o| o.create(TransferType::Standard).c(d!())) .and_then(|o| { let cmp = |a: &XfrKeyPair, b: &XfrKeyPair| { - a.get_pk().as_bytes().cmp(b.get_pk().as_bytes()) + a.get_pk().to_bytes().cmp(&b.get_pk().to_bytes()) }; kps.sort_by(cmp); kps.dedup_by(|a, b| matches!(cmp(a, b), Ordering::Equal)); @@ -300,18 +320,18 @@ impl TransactionBuilder { seq_num: u64, amount: u64, confidentiality_flags: AssetRecordType, - zei_params: &PublicParams, ) -> Result<&mut Self> { let mut prng = ChaChaRng::from_entropy(); let ar = AssetRecordTemplate::with_no_asset_tracing( amount, token_code.val, confidentiality_flags, - key_pair.get_pk(), + key_pair.get_pk().into_noah(), ); + let pc_gens = PedersenCommitmentRistretto::default(); let (ba, _, owner_memo) = - build_blind_asset_record(&mut prng, &zei_params.pc_gens, &ar, vec![]); + build_blind_asset_record(&mut prng, &pc_gens, &ar, vec![]); self.add_operation_issue_asset( key_pair, token_code, @@ -319,10 +339,10 @@ impl TransactionBuilder { &[( TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }, - owner_memo, + owner_memo.map(|om| OwnerMemo::from_noah(&om).unwrap()), )], ) .c(d!()) @@ -741,10 +761,10 @@ pub(crate) fn build_record_and_get_blinds( } }; // 2. Use record template and ciphertexts to build open asset record - let params = PublicParams::default(); + let pc_gens = PedersenCommitmentRistretto::default(); let (open_asset_record, asset_tracing_memos, owner_memo) = build_open_asset_record( prng, - ¶ms.pc_gens, + &pc_gens, template, vec![attr_ctext.unwrap_or_default()], ); @@ -1129,11 +1149,11 @@ impl TransferOperationBuilder { if !sig.verify(&trn.body) { return Err(eg!(("Invalid signature"))); } - sig_keys.insert(sig.address.key.zei_to_bytes()); + sig_keys.insert(sig.address.key.noah_to_bytes()); } for record in &trn.body.transfer.inputs { - if !sig_keys.contains(&record.public_key.zei_to_bytes()) { + if !sig_keys.contains(&record.public_key.noah_to_bytes()) { return Err(eg!(("Not all signatures present"))); } } @@ -1150,10 +1170,11 @@ mod tests { ledger::store::{utils::fra_gen_initial_tx, LedgerState}, rand_chacha::ChaChaRng, rand_core::SeedableRng, - zei::setup::PublicParams, - zei::xfr::asset_record::AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - zei::xfr::asset_record::{build_blind_asset_record, open_blind_asset_record}, - zei::xfr::sig::XfrKeyPair, + zei::noah_api::xfr::asset_record::{ + build_blind_asset_record, open_blind_asset_record, + AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, + }, + zei::XfrKeyPair, }; // Defines an asset type @@ -1183,7 +1204,7 @@ mod tests { fn test_transfer_op_builder_inner() -> Result<()> { let mut prng = ChaChaRng::from_entropy(); - let params = PublicParams::default(); + let pc_gens = PedersenCommitmentRistretto::default(); let code_1 = AssetTypeCode::gen_random(); let code_2 = AssetTypeCode::gen_random(); let alice = XfrKeyPair::generate(&mut prng); @@ -1195,18 +1216,18 @@ mod tests { 1000, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - alice.get_pk(), + alice.get_pk().into_noah(), ); let ar_2 = AssetRecordTemplate::with_no_asset_tracing( 1000, code_2.val, NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let (ba_1, _, memo1) = - build_blind_asset_record(&mut prng, ¶ms.pc_gens, &ar_1, vec![]); + build_blind_asset_record(&mut prng, &pc_gens, &ar_1, vec![]); let (ba_2, _, memo2) = - build_blind_asset_record(&mut prng, ¶ms.pc_gens, &ar_2, vec![]); + build_blind_asset_record(&mut prng, &pc_gens, &ar_2, vec![]); // Attempt to spend too much let mut invalid_outputs_transfer_op = TransferOperationBuilder::new(); @@ -1214,12 +1235,12 @@ mod tests { 25, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let res = invalid_outputs_transfer_op .add_input( TxoRef::Relative(1), - open_blind_asset_record(&ba_1, &memo1, &alice).c(d!())?, + open_blind_asset_record(&ba_1, &memo1, &alice.into_noah()).c(d!())?, None, None, 20, @@ -1237,12 +1258,12 @@ mod tests { 20, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let res = invalid_sig_op .add_input( TxoRef::Relative(1), - open_blind_asset_record(&ba_1, &memo1, &alice).c(d!())?, + open_blind_asset_record(&ba_1, &memo1, &alice.into_noah()).c(d!())?, None, None, 20, @@ -1265,12 +1286,12 @@ mod tests { 20, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let res = missing_sig_op .add_input( TxoRef::Relative(1), - open_blind_asset_record(&ba_1, &memo1, &alice).c(d!())?, + open_blind_asset_record(&ba_1, &memo1, &alice.into_noah()).c(d!())?, None, None, 20, @@ -1291,42 +1312,42 @@ mod tests { 5, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let output_charlie13_code1_template = AssetRecordTemplate::with_no_asset_tracing( 13, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - charlie.get_pk(), + charlie.get_pk().into_noah(), ); let output_ben2_code1_template = AssetRecordTemplate::with_no_asset_tracing( 2, code_1.val, NonConfidentialAmount_NonConfidentialAssetType, - ben.get_pk(), + ben.get_pk().into_noah(), ); let output_bob5_code2_template = AssetRecordTemplate::with_no_asset_tracing( 5, code_2.val, NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let output_charlie13_code2_template = AssetRecordTemplate::with_no_asset_tracing( 13, code_2.val, NonConfidentialAmount_NonConfidentialAssetType, - charlie.get_pk(), + charlie.get_pk().into_noah(), ); let output_ben2_code2_template = AssetRecordTemplate::with_no_asset_tracing( 2, code_2.val, NonConfidentialAmount_NonConfidentialAssetType, - ben.get_pk(), + ben.get_pk().into_noah(), ); let _valid_transfer_op = TransferOperationBuilder::new() .add_input( TxoRef::Relative(1), - open_blind_asset_record(&ba_1, &memo1, &alice).c(d!())?, + open_blind_asset_record(&ba_1, &memo1, &alice.into_noah()).c(d!())?, None, None, 20, @@ -1334,7 +1355,7 @@ mod tests { .c(d!())? .add_input( TxoRef::Relative(2), - open_blind_asset_record(&ba_2, &memo2, &bob).c(d!())?, + open_blind_asset_record(&ba_2, &memo2, &bob.into_noah()).c(d!())?, None, None, 20, @@ -1371,8 +1392,8 @@ mod tests { let fra_owner_kp = XfrKeyPair::generate(&mut ChaChaRng::from_entropy()); let bob_kp = XfrKeyPair::generate(&mut ChaChaRng::from_entropy()); assert_eq!( - bob_kp.get_sk().into_keypair().zei_to_bytes(), - bob_kp.zei_to_bytes() + bob_kp.get_sk().into_keypair().noah_to_bytes(), + bob_kp.noah_to_bytes() ); let mut tx = fra_gen_initial_tx(&fra_owner_kp); @@ -1400,9 +1421,15 @@ mod tests { .add_input( TxoRef::Absolute($txo_sid), open_blind_asset_record( - &ledger.get_utxo_light($txo_sid).unwrap().utxo.0.record, + &ledger + .get_utxo_light($txo_sid) + .unwrap() + .utxo + .0 + .record + .into_noah(), &None, - &fra_owner_kp, + &fra_owner_kp.into_noah(), ) .unwrap(), None, @@ -1424,7 +1451,7 @@ mod tests { } let mut tx2 = TransactionBuilder::from_seq_id(1); - tx2.add_operation(transfer_to_bob!(txo_sid, bob_kp.get_pk())) + tx2.add_operation(transfer_to_bob!(txo_sid, bob_kp.get_pk().into_noah())) .add_fee_relative_auto(&fra_owner_kp) .unwrap(); assert!(tx2.check_fee()); @@ -1454,7 +1481,7 @@ mod tests { ); let mut tx3 = TransactionBuilder::from_seq_id(2); pnk!(tx3 - .add_operation(transfer_to_bob!(txo_sid[2], bob_kp.get_pk())) + .add_operation(transfer_to_bob!(txo_sid[2], bob_kp.get_pk().into_noah())) .add_fee(fi)); assert!(tx3.check_fee()); @@ -1483,7 +1510,7 @@ mod tests { bob_kp.get_sk().into_keypair(), ); let mut tx4 = TransactionBuilder::from_seq_id(3); - tx4.add_operation(transfer_to_bob!(txo_sid[1], bob_kp.get_pk())) + tx4.add_operation(transfer_to_bob!(txo_sid[1], bob_kp.get_pk().into_noah())) .add_fee(fi) .unwrap(); assert!(tx4.check_fee()); diff --git a/src/components/wallet_mobile/Cargo.toml b/src/components/wallet_mobile/Cargo.toml index 46ea6f1cd..e6f4cc228 100644 --- a/src/components/wallet_mobile/Cargo.toml +++ b/src/components/wallet_mobile/Cargo.toml @@ -16,30 +16,30 @@ crate-type = ["cdylib", "staticlib", "rlib"] wasm-opt = false [dependencies] -aes-gcm = "0.9.0" +aes-gcm = "^0.10.1" base64 = "0.13" bech32 = "0.7.2" ffi-support = "0.4" futures = "0.3.16" getrandom = { version = "0.2", features = ["js"] } -hex = "0.4.2" +hex = "0.4.3" js-sys = "0.3.27" rand = { version = "0.7", features = ["wasm-bindgen"] } -rand_chacha = "0.2.0" -rand_core = { version = "0.5", default-features = false, features = ["alloc"] } +rand_chacha = "0.3" +rand_core = { version = "0.6", default-features = false, features = ["alloc"] } ring = "0.16.19" ruc = "1.0" serde = { version = "1.0.124", features = ["derive"] } serde_derive = "1.0" serde_json = "1.0" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } finutils = { path = "../finutils", default-features = false, features = []} fp-types = { path = "../contracts/primitives/types" } fp-utils = { path = "../contracts/primitives/utils" } -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } -credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", tag = "v1.0.0" } -cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", tag = "v1.0.0" } +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } +credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", branch = "develop" } +cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", branch = "develop" } ledger = { path = "../../ledger" } diff --git a/src/components/wallet_mobile/src/android/constructor.rs b/src/components/wallet_mobile/src/android/constructor.rs index 4303b99c2..719501321 100644 --- a/src/components/wallet_mobile/src/android/constructor.rs +++ b/src/components/wallet_mobile/src/android/constructor.rs @@ -4,8 +4,8 @@ use jni::sys::{jbyteArray, jlong}; use jni::JNIEnv; use rand_chacha::ChaChaRng; use rand_core::SeedableRng; -use zei::xfr::sig::XfrKeyPair as RawXfrKeyPair; -use zei::xfr::structs::ASSET_TYPE_LENGTH; +use zei::noah_api::xfr::structs::ASSET_TYPE_LENGTH; +use zei::XfrKeyPair as RawXfrKeyPair; #[no_mangle] pub unsafe extern "system" fn Java_com_findora_JniApi_xfrKeyPairNew( diff --git a/src/components/wallet_mobile/src/android/evm.rs b/src/components/wallet_mobile/src/android/evm.rs index 0271a4903..ed038e5b7 100644 --- a/src/components/wallet_mobile/src/android/evm.rs +++ b/src/components/wallet_mobile/src/android/evm.rs @@ -2,7 +2,7 @@ use crate::rust::account::{get_serialized_address, EVMTransactionBuilder}; use jni::objects::{JClass, JString}; use jni::sys::{jlong, jstring}; use jni::JNIEnv; -use zei::xfr::sig::XfrPublicKey; +use zei::XfrPublicKey; use super::{jStringToString, parseU64}; diff --git a/src/components/wallet_mobile/src/android/mod.rs b/src/components/wallet_mobile/src/android/mod.rs index 5e41115c1..e68ec61f6 100644 --- a/src/components/wallet_mobile/src/android/mod.rs +++ b/src/components/wallet_mobile/src/android/mod.rs @@ -13,7 +13,7 @@ use jni::objects::{JClass, JString}; use jni::sys::{jboolean, jbyteArray, jint, jlong, jstring}; use jni::JNIEnv; use ledger::data_model::AssetTypeCode; -use zei::xfr::structs::ASSET_TYPE_LENGTH; +use zei::noah_api::xfr::structs::ASSET_TYPE_LENGTH; #[no_mangle] /// Returns the git commit hash and commit date of the commit this library was built against. pub extern "system" fn Java_com_findora_JniApi_buildId( diff --git a/src/components/wallet_mobile/src/android/transfer.rs b/src/components/wallet_mobile/src/android/transfer.rs index 05ddd9da9..ecb615882 100644 --- a/src/components/wallet_mobile/src/android/transfer.rs +++ b/src/components/wallet_mobile/src/android/transfer.rs @@ -3,8 +3,8 @@ use jni::objects::{JClass, JString}; use jni::sys::{jboolean, jint, jlong, jstring, jvalue, JNI_TRUE}; use jni::JNIEnv; use ledger::data_model::AssetType as PlatformAssetType; -use zei::xfr::sig::{XfrKeyPair, XfrPublicKey}; -use zei::xfr::structs::OwnerMemo as ZeiOwnerMemo; +use zei::OwnerMemo as NoahOwnerMemo; +use zei::{XfrKeyPair, XfrPublicKey}; use super::{jStringToString, parseU64}; @@ -189,8 +189,8 @@ pub unsafe extern "system" fn Java_com_findora_JniApi_ownerMemoFromJson( .expect("Couldn't get java string!") .into(); - let zei_owner_memo: ZeiOwnerMemo = serde_json::from_str(val.as_str()).unwrap(); - Box::into_raw(Box::new(OwnerMemo::from_json(zei_owner_memo).unwrap())) as jlong + let noah_owner_memo: NoahOwnerMemo = serde_json::from_str(val.as_str()).unwrap(); + Box::into_raw(Box::new(OwnerMemo::from_json(noah_owner_memo).unwrap())) as jlong } #[no_mangle] diff --git a/src/components/wallet_mobile/src/android/tx_builder.rs b/src/components/wallet_mobile/src/android/tx_builder.rs index 264dac2fe..f935b75c5 100644 --- a/src/components/wallet_mobile/src/android/tx_builder.rs +++ b/src/components/wallet_mobile/src/android/tx_builder.rs @@ -4,7 +4,7 @@ use jni::objects::{JClass, JString}; use jni::sys::{jboolean, jint, jlong, jstring, JNI_TRUE}; use jni::JNIEnv; use ledger::data_model::AssetTypeCode; -use zei::xfr::sig::XfrKeyPair; +use zei::XfrKeyPair; #[no_mangle] /// # Safety /// @param kp: owner's XfrKeyPair @@ -285,9 +285,12 @@ pub unsafe extern "system" fn Java_com_findora_JniApi_transactionBuilderAddOpera .expect("Couldn't get java string!") .into(); let addr = td_addr.strip_prefix("0x").unwrap_or(&td_addr); - let td_address = hex::decode(addr) .expect("addr format error!"); + let td_address = hex::decode(addr).expect("addr format error!"); let keypair = &*(keypair as *mut XfrKeyPair); - let builder = builder.clone().add_operation_claim(td_address,keypair).unwrap(); + let builder = builder + .clone() + .add_operation_claim(td_address, keypair) + .unwrap(); Box::into_raw(Box::new(builder)) as jlong } @@ -305,14 +308,14 @@ pub unsafe extern "system" fn Java_com_findora_JniApi_transactionBuilderAddOpera let builder = &*(builder as *mut TransactionBuilder); let keypair = &*(keypair as *mut XfrKeyPair); let td_addr: String = env - .get_string(td_addr) - .expect("Couldn't get java string!") - .into(); + .get_string(td_addr) + .expect("Couldn't get java string!") + .into(); let addr = td_addr.strip_prefix("0x").unwrap_or(&td_addr); - let td_address = hex::decode(addr) .expect("addr format error!"); + let td_address = hex::decode(addr).expect("addr format error!"); let builder = builder .clone() - .add_operation_claim_custom(td_address,keypair, parseU64(env, am)) + .add_operation_claim_custom(td_address, keypair, parseU64(env, am)) .unwrap(); Box::into_raw(Box::new(builder)) as jlong } diff --git a/src/components/wallet_mobile/src/ios/evm.rs b/src/components/wallet_mobile/src/ios/evm.rs index 527c5e11b..f313ab63d 100644 --- a/src/components/wallet_mobile/src/ios/evm.rs +++ b/src/components/wallet_mobile/src/ios/evm.rs @@ -1,5 +1,5 @@ use std::os::raw::c_char; -use zei::xfr::sig::XfrPublicKey; +use zei::XfrPublicKey; use crate::rust::{ self, account::EVMTransactionBuilder, c_char_to_string, string_to_c_char, diff --git a/src/components/wallet_mobile/src/ios/mod.rs b/src/components/wallet_mobile/src/ios/mod.rs index 4212e5e0b..80e80b05a 100644 --- a/src/components/wallet_mobile/src/ios/mod.rs +++ b/src/components/wallet_mobile/src/ios/mod.rs @@ -13,7 +13,7 @@ use rand_core::SeedableRng; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::ptr; -use zei::xfr::structs::ASSET_TYPE_LENGTH; +use zei::noah_api::xfr::structs::ASSET_TYPE_LENGTH; #[no_mangle] /// Returns the git commit hash and commit date of the commit this library was built against. diff --git a/src/components/wallet_mobile/src/ios/tx_builder.rs b/src/components/wallet_mobile/src/ios/tx_builder.rs index 13049fb38..2cba61ae0 100644 --- a/src/components/wallet_mobile/src/ios/tx_builder.rs +++ b/src/components/wallet_mobile/src/ios/tx_builder.rs @@ -5,7 +5,7 @@ use crate::rust::{ }; use ledger::data_model::AssetTypeCode; use std::os::raw::c_char; -use zei::xfr::sig::XfrKeyPair; +use zei::XfrKeyPair; #[no_mangle] /// @param kp: owner's XfrKeyPair @@ -219,7 +219,7 @@ pub extern "C" fn findora_ffi_transaction_builder_add_operation_claim( let td_addr = c_char_to_string(td_addr); let addr = td_addr.strip_prefix("0x").unwrap_or(&td_addr); let td_address = hex::decode(addr).expect("addr format error!"); - if let Ok(info) = builder.clone().add_operation_claim(td_address,keypair) { + if let Ok(info) = builder.clone().add_operation_claim(td_address, keypair) { Box::into_raw(Box::new(info)) } else { std::ptr::null_mut() @@ -237,7 +237,10 @@ pub extern "C" fn findora_ffi_transaction_builder_add_operation_claim_custom( let td_addr = c_char_to_string(td_addr); let addr = td_addr.strip_prefix("0x").unwrap_or(&td_addr); let td_address = hex::decode(addr).expect("addr format error!"); - if let Ok(info) = builder.clone().add_operation_claim_custom(td_address,keypair, am) { + if let Ok(info) = builder + .clone() + .add_operation_claim_custom(td_address, keypair, am) + { Box::into_raw(Box::new(info)) } else { std::ptr::null_mut() diff --git a/src/components/wallet_mobile/src/ios/tx_op_builder.rs b/src/components/wallet_mobile/src/ios/tx_op_builder.rs index 24a6fa28b..9f318d0d3 100644 --- a/src/components/wallet_mobile/src/ios/tx_op_builder.rs +++ b/src/components/wallet_mobile/src/ios/tx_op_builder.rs @@ -1,5 +1,5 @@ use std::os::raw::c_char; -use zei::xfr::sig::{XfrKeyPair, XfrPublicKey}; +use zei::{XfrKeyPair, XfrPublicKey}; use super::parse_u64; use crate::rust::TransferOperationBuilder; diff --git a/src/components/wallet_mobile/src/rust/account.rs b/src/components/wallet_mobile/src/rust/account.rs index 0c6588a54..963921863 100644 --- a/src/components/wallet_mobile/src/rust/account.rs +++ b/src/components/wallet_mobile/src/rust/account.rs @@ -1,7 +1,7 @@ use core::str::FromStr; use ledger::data_model::{AssetTypeCode, ASSET_TYPE_FRA}; use ruc::{d, Result, RucResult}; -use zei::xfr::sig::{XfrKeyPair, XfrPublicKey}; +use zei::{XfrKeyPair, XfrPublicKey}; use super::transaction::TransactionBuilder; @@ -29,7 +29,7 @@ impl Keypair { match self { Keypair::Ecdsa(kp) => MultiSignature::from(kp.sign(data)), Keypair::Ed25519(kp) => { - MultiSignature::from(kp.get_sk_ref().sign(data, kp.get_pk_ref())) + MultiSignature::from(kp.get_sk_ref().sign(data).unwrap()) } } } diff --git a/src/components/wallet_mobile/src/rust/crypto.rs b/src/components/wallet_mobile/src/rust/crypto.rs index 86059b624..390c0a4ea 100644 --- a/src/components/wallet_mobile/src/rust/crypto.rs +++ b/src/components/wallet_mobile/src/rust/crypto.rs @@ -2,7 +2,7 @@ use wasm_bindgen::prelude::*; use super::data_model::*; -use aes_gcm::aead::{generic_array::GenericArray, Aead, NewAead}; +use aes_gcm::aead::{generic_array::GenericArray, Aead, KeyInit}; use aes_gcm::Aes256Gcm; use credentials::{ credential_commit, credential_issuer_key_gen, credential_open_commitment, @@ -11,28 +11,32 @@ use credentials::{ CredUserPublicKey, CredUserSecretKey, Credential as PlatformCredential, }; use cryptohash::sha256; +use getrandom::getrandom; use globutils::wallet; use ledger::{ data_model::{ - AssetTypeCode, ASSET_TYPE_FRA, BLACK_HOLE_PUBKEY, BLACK_HOLE_PUBKEY_STAKING, + AssetTypeCode, ASSET_TYPE_FRA, BLACK_HOLE_PUBKEY_STAKING, TX_FEE_MIN, }, staking::{MAX_DELEGATION_AMOUNT, MIN_DELEGATION_AMOUNT}, }; -use rand::{thread_rng, Rng}; use rand_chacha::ChaChaRng; use rand_core::SeedableRng; use ring::pbkdf2; -use ruc::Result; +use ruc::{ + d, Result, RucResult +}; use std::num::NonZeroU32; use std::str; -use zei::serialization::ZeiFromToBytes; -use zei::xfr::asset_record::open_blind_asset_record as open_bar; -use zei::xfr::lib::trace_assets as zei_trace_assets; -use zei::xfr::sig::{XfrKeyPair, XfrPublicKey, XfrSecretKey}; -use zei::xfr::structs::{ - AssetType as ZeiAssetType, OpenAssetRecord, XfrBody, ASSET_TYPE_LENGTH, +use zei::noah_algebra::serialization::NoahFromToBytes; +use zei::noah_api::{ + xfr::{ + asset_record::open_blind_asset_record as open_bar, + structs::{AssetType as NoahAssetType, OpenAssetRecord, XfrBody, ASSET_TYPE_LENGTH}, + trace_assets as noah_trace_assets, + }, }; +use zei::{XfrKeyPair, XfrPublicKey, XfrSecretKey}; #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] /// Generates random Base64 encoded asset type as a Base64 string. Used in asset definitions. @@ -47,7 +51,7 @@ pub fn random_asset_type() -> String { /// Generates asset type as a Base64 string from given code. pub fn rs_asset_type_from_value(code: [u8; ASSET_TYPE_LENGTH]) -> String { AssetTypeCode { - val: ZeiAssetType(code), + val: NoahAssetType(code), } .to_base64() } @@ -57,7 +61,8 @@ pub fn rs_trace_assets( xfr_body: XfrBody, tracer_keypair: &AssetTracerKeyPair, ) -> Result> { - Ok(zei_trace_assets(&xfr_body, tracer_keypair.get_keys())? + Ok(noah_trace_assets(&xfr_body, tracer_keypair.get_keys()) + .c(d!())? .iter() .map(|(amt, asset_type, _, _)| { let asset_type_code = AssetTypeCode { val: *asset_type }; @@ -71,7 +76,7 @@ pub fn rs_trace_assets( /// Returns an address to use for cancelling debt tokens in a debt swap. /// @ignore pub fn get_null_pk() -> XfrPublicKey { - XfrPublicKey::zei_from_bytes(&[0; 32]).unwrap() + XfrPublicKey::noah_from_bytes(&[0; 32]).unwrap() } /// Returns a JavaScript object containing decrypted owner record information, @@ -82,10 +87,11 @@ pub fn rs_open_client_asset_record( keypair: &XfrKeyPair, ) -> Result { open_bar( - record.get_bar_ref(), + &record.get_bar_ref().into_noah(), &owner_memo.map(|memo| memo.get_memo_ref().clone()), - keypair, + &keypair.into_noah(), ) + .c(d!()) } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] @@ -103,8 +109,8 @@ pub fn get_priv_key_str(key_pair: &XfrKeyPair) -> String { #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] /// Creates a new transfer key pair. pub fn new_keypair() -> XfrKeyPair { - let mut small_rng = rand::thread_rng(); - XfrKeyPair::generate(&mut small_rng) + let mut prng = ChaChaRng::from_entropy(); + XfrKeyPair::generate(&mut prng) } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] @@ -131,14 +137,14 @@ pub fn rs_public_key_from_base64(pk: &str) -> Result { /// Expresses a transfer key pair as a hex-encoded string. /// To decode the string, use `keypair_from_str` function. pub fn keypair_to_str(key_pair: &XfrKeyPair) -> String { - hex::encode(key_pair.zei_to_bytes()) + hex::encode(key_pair.noah_to_bytes()) } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] /// Constructs a transfer key pair from a hex-encoded string. /// The encode a key pair, use `keypair_to_str` function. pub fn keypair_from_str(str: String) -> XfrKeyPair { - XfrKeyPair::zei_from_bytes(&hex::decode(str).unwrap()).unwrap() + XfrKeyPair::noah_from_bytes(&hex::decode(str).unwrap()).unwrap() } /// Generates a new credential issuer key. @@ -167,7 +173,7 @@ pub fn rs_wasm_credential_verify_commitment( issuer_pub_key, commitment.get_ref(), pok.get_ref(), - xfr_pk.as_bytes(), + &xfr_pk.noah_to_bytes(), ) } @@ -248,7 +254,7 @@ pub fn rs_wasm_credential_commit( &mut prng, user_secret_key, credential.get_cred_ref(), - user_public_key.as_bytes(), + &user_public_key.noah_to_bytes(), )?; Ok(CredentialCommitmentData { commitment: CredentialCommitment { commitment }, @@ -319,10 +325,9 @@ pub fn encryption_pbkdf2_aes256gcm(key_pair: String, password: String) -> Vec Vec u64 { /// The destination for fee to be transfered to. #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] pub fn fra_get_dest_pubkey() -> XfrPublicKey { - *BLACK_HOLE_PUBKEY + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING) } /// The system address used to reveive delegation principals. @@ -486,13 +491,13 @@ pub fn get_delegation_target_address() -> String { #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] #[allow(missing_docs)] pub fn get_coinbase_address() -> String { - wallet::public_key_to_base64(&BLACK_HOLE_PUBKEY_STAKING) + wallet::public_key_to_base64(&XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING)) } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] #[allow(missing_docs)] pub fn get_coinbase_principal_address() -> String { - wallet::public_key_to_base64(&BLACK_HOLE_PUBKEY_STAKING) + wallet::public_key_to_base64(&XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING)) } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] diff --git a/src/components/wallet_mobile/src/rust/data_model.rs b/src/components/wallet_mobile/src/rust/data_model.rs index 12733a3f3..967e1fd3f 100644 --- a/src/components/wallet_mobile/src/rust/data_model.rs +++ b/src/components/wallet_mobile/src/rust/data_model.rs @@ -20,39 +20,15 @@ use rand_core::SeedableRng; use ruc::Result as RUCResult; use ruc::{d, err::RucResult}; use serde::{Deserialize, Serialize}; -use zei::setup::PublicParams as ZeiPublicParams; -use zei::xfr::sig::XfrPublicKey; -use zei::xfr::structs::{ - AssetTracerDecKeys, AssetTracerEncKeys, AssetTracerKeyPair as ZeiAssetTracerKeyPair, - BlindAssetRecord, IdentityRevealPolicy, OwnerMemo as ZeiOwnerMemo, - TracingPolicies as ZeiTracingPolicies, TracingPolicy as ZeiTracingPolicy, +use zei::noah_api::xfr::structs::{ + AssetTracerDecKeys, AssetTracerEncKeys, + AssetTracerKeyPair as NoahAssetTracerKeyPair, IdentityRevealPolicy, + OwnerMemo as NoahOwnerMemo, TracingPolicies as NoahTracingPolicies, + TracingPolicy as NoahTracingPolicy, +}; +use zei::{ + BlindAssetRecord, XfrPublicKey }; - -#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] -/// Public parameters necessary for generating asset records. Generating this is expensive and -/// should be done as infrequently as possible. -/// @see {@link module:Findora-Wasm~TransactionBuilder#add_basic_issue_asset|add_basic_issue_asset} -/// for information using public parameters to create issuance asset records. -pub struct PublicParams { - pub(crate) params: ZeiPublicParams, -} - -#[allow(clippy::new_without_default)] -#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] -impl PublicParams { - /// Generates a new set of parameters. - pub fn new() -> PublicParams { - PublicParams { - params: ZeiPublicParams::default(), - } - } -} - -impl PublicParams { - pub fn get_ref(&self) -> &ZeiPublicParams { - &self.params - } -} #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] /// Indicates whether the TXO ref is an absolute or relative value. @@ -238,7 +214,7 @@ impl ClientAssetRecord { /// @see {@link module:Findora-Wasm~AssetRules#add_tracing_policy|add_tracing_policy} for information about how to add a tracing policy to /// an asset definition. pub struct AssetTracerKeyPair { - pub(crate) keypair: ZeiAssetTracerKeyPair, + pub(crate) keypair: NoahAssetTracerKeyPair, } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] @@ -247,7 +223,7 @@ impl AssetTracerKeyPair { pub fn new() -> Self { let mut small_rng = ChaChaRng::from_entropy(); AssetTracerKeyPair { - keypair: ZeiAssetTracerKeyPair::generate(&mut small_rng), + keypair: NoahAssetTracerKeyPair::generate(&mut small_rng), } } } @@ -266,7 +242,7 @@ impl AssetTracerKeyPair { &self.keypair.dec_key } - pub fn get_keys(&self) -> &ZeiAssetTracerKeyPair { + pub fn get_keys(&self) -> &NoahAssetTracerKeyPair { &self.keypair } } @@ -276,7 +252,7 @@ impl AssetTracerKeyPair { /// Asset owner memo. Contains information needed to decrypt an asset record. /// @see {@link module:Findora-Wasm.ClientAssetRecord|ClientAssetRecord} for more details about asset records. pub struct OwnerMemo { - pub(crate) memo: ZeiOwnerMemo, + pub(crate) memo: NoahOwnerMemo, } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] @@ -293,29 +269,30 @@ impl OwnerMemo { /// "lock":{"ciphertext":[119,54,117,136,125,133,112,193],"encoded_rand":"8KDql2JphPB5WLd7-aYE1bxTQAcweFSmrqymLvPDntM="} /// } pub fn from_json(val: &JsValue) -> Result { - let zei_owner_memo: ZeiOwnerMemo = + let noah_owner_memo: NoahOwnerMemo = val.into_serde().c(d!()).map_err(error_to_jsvalue)?; Ok(OwnerMemo { - memo: ZeiOwnerMemo { - blind_share: zei_owner_memo.blind_share, - lock: zei_owner_memo.lock, + memo: NoahOwnerMemo { + blind_share: noah_owner_memo.blind_share, + lock: noah_owner_memo.lock, }, }) } #[cfg(not(target_arch = "wasm32"))] - pub fn from_json(zei_owner_memo: ZeiOwnerMemo) -> RUCResult { + pub fn from_json(noah_owner_memo: NoahOwnerMemo) -> RUCResult { Ok(OwnerMemo { - memo: ZeiOwnerMemo { - blind_share: zei_owner_memo.blind_share, - lock: zei_owner_memo.lock, + memo: NoahOwnerMemo { + key_type: noah_owner_memo.key_type, + blind_share_bytes: noah_owner_memo.blind_share_bytes, + lock_bytes: noah_owner_memo.lock_bytes, }, }) } } impl OwnerMemo { - pub fn get_memo_ref(&self) -> &ZeiOwnerMemo { + pub fn get_memo_ref(&self) -> &NoahOwnerMemo { &self.memo } } @@ -369,7 +346,7 @@ impl CredentialRevealSig { /// credential commitment. pub fn get_commitment(&self) -> CredentialCommitment { CredentialCommitment { - commitment: self.sig.sig_commitment.clone(), + commitment: self.sig.cm.clone(), } } /// Returns the underlying proof of knowledge that the credential is valid. @@ -377,7 +354,7 @@ impl CredentialRevealSig { /// credential commitment. pub fn get_pok(&self) -> CredentialPoK { CredentialPoK { - pok: self.sig.pok.clone(), + pok: self.sig.proof_open.clone(), } } } @@ -669,11 +646,11 @@ impl SignatureRules { /// A collection of tracing policies. Use this object when constructing asset transfers to generate /// the correct tracing proofs for traceable assets. pub struct TracingPolicies { - pub(crate) policies: ZeiTracingPolicies, + pub(crate) policies: NoahTracingPolicies, } impl TracingPolicies { - pub fn get_policies_ref(&self) -> &ZeiTracingPolicies { + pub fn get_policies_ref(&self) -> &NoahTracingPolicies { &self.policies } } @@ -682,13 +659,13 @@ impl TracingPolicies { /// Tracing policy for asset transfers. Can be configured to track credentials, the asset type and /// amount, or both. pub struct TracingPolicy { - pub(crate) policy: ZeiTracingPolicy, + pub(crate) policy: NoahTracingPolicy, } #[cfg_attr(target_arch = "wasm32", wasm_bindgen)] impl TracingPolicy { pub fn new_with_tracing(tracing_key: &AssetTracerKeyPair) -> Self { - let policy = ZeiTracingPolicy { + let policy = NoahTracingPolicy { enc_keys: tracing_key.get_enc_key().clone(), asset_tracing: true, identity_tracing: None, @@ -710,7 +687,7 @@ impl TracingPolicy { cred_issuer_pub_key: cred_issuer_key.get_ref().clone(), reveal_map, }; - let policy = ZeiTracingPolicy { + let policy = NoahTracingPolicy { enc_keys: tracing_key.get_enc_key().clone(), asset_tracing: tracing, identity_tracing: Some(identity_policy), @@ -729,7 +706,7 @@ impl TracingPolicy { cred_issuer_pub_key: cred_issuer_key.get_ref().clone(), reveal_map, }; - let policy = ZeiTracingPolicy { + let policy = NoahTracingPolicy { enc_keys: tracing_key.get_enc_key().clone(), asset_tracing: tracing, identity_tracing: Some(identity_policy), @@ -739,7 +716,7 @@ impl TracingPolicy { } impl TracingPolicy { - pub fn get_ref(&self) -> &ZeiTracingPolicy { + pub fn get_ref(&self) -> &NoahTracingPolicy { &self.policy } } diff --git a/src/components/wallet_mobile/src/rust/transaction.rs b/src/components/wallet_mobile/src/rust/transaction.rs index a7c22f5be..575859c93 100644 --- a/src/components/wallet_mobile/src/rust/transaction.rs +++ b/src/components/wallet_mobile/src/rust/transaction.rs @@ -15,11 +15,13 @@ use ledger::{ }, staking::{td_addr_to_bytes, PartialUnDelegation, TendermintAddr}, }; -use ruc::{eg, Result as RucResult}; +use ruc::{d, eg, Result as RucResult, err::RucResult as NewRucResult}; use serde_json::Result; -use zei::xfr::asset_record::{open_blind_asset_record as open_bar, AssetRecordType}; -use zei::xfr::sig::{XfrKeyPair, XfrPublicKey}; -use zei::xfr::structs::AssetRecordTemplate; +use zei::noah_api::xfr::{ + asset_record::{open_blind_asset_record as open_bar, AssetRecordType}, + structs::AssetRecordTemplate, +}; +use zei::{OwnerMemo as NoahOwnerMemo, XfrKeyPair, XfrPublicKey}; /// Given a serialized state commitment and transaction, returns true if the transaction correctly /// hashes up to the state commitment and false otherwise. @@ -53,7 +55,7 @@ impl From for PlatformFeeInput { am: fi.am, tr: fi.tr.txo_ref, ar: fi.ar.txo, - om: fi.om.map(|om| om.memo), + om: fi.om.map(|om| NoahOwnerMemo::from_noah(&om.memo).unwrap()), kp: fi.kp, } } @@ -225,7 +227,6 @@ impl TransactionBuilder { seq_num: u64, amount: u64, conf_amount: bool, - zei_params: &PublicParams, ) -> RucResult { let asset_token = AssetTypeCode::new_from_base64(&code)?; @@ -239,7 +240,6 @@ impl TransactionBuilder { seq_num, amount, confidentiality_flags, - zei_params.get_ref(), )?; Ok(self) } @@ -362,7 +362,7 @@ impl TransactionBuilder { pub fn get_owner_memo(&self, idx: usize) -> Option { self.get_builder() .get_owner_memo_ref(idx) - .map(|memo| OwnerMemo { memo: memo.clone() }) + .map(|memo| OwnerMemo { memo: memo.into_noah() }) } } @@ -393,10 +393,11 @@ impl TransferOperationBuilder { amount: u64, ) -> RucResult { let oar = open_bar( - asset_record.get_bar_ref(), + &asset_record.get_bar_ref().into_noah(), &owner_memo.map(|memo| memo.get_memo_ref().clone()), - key, - )?; + &key.into_noah(), + ) + .c(d!())?; self.get_builder_mut().add_input( *txo_ref.get_txo(), oar, @@ -425,7 +426,7 @@ impl TransferOperationBuilder { amount, code.val, asset_record_type, - *recipient, + recipient.into_noah(), policies.get_policies_ref().clone(), ) } else { @@ -433,7 +434,7 @@ impl TransferOperationBuilder { amount, code.val, asset_record_type, - *recipient, + recipient.into_noah(), ) }; self.get_builder_mut().add_output( diff --git a/src/components/wallet_mobile/src/rust/types.rs b/src/components/wallet_mobile/src/rust/types.rs index 765072d30..71a26fe15 100644 --- a/src/components/wallet_mobile/src/rust/types.rs +++ b/src/components/wallet_mobile/src/rust/types.rs @@ -5,8 +5,8 @@ use credentials::{ CredUserSecretKey as PlatformCredUserSecretKey, }; use std::ops::{Deref, DerefMut}; -use zei::xfr::sig::{XfrKeyPair as ZeiXfrKeyPair, XfrPublicKey as ZeiXfrPublicKey}; -use zei::xfr::structs::OpenAssetRecord as ZeiOpenAssetRecord; +use zei::noah_api::xfr::structs::OpenAssetRecord as ZeiOpenAssetRecord; +use zei::{XfrKeyPair as ZeiXfrKeyPair, XfrPublicKey as ZeiXfrPublicKey}; //////////////////////////////////////////////////////////////////////////////// diff --git a/src/components/wallet_mobile/src/wasm/mod.rs b/src/components/wallet_mobile/src/wasm/mod.rs index 14a7fdf23..491c621a8 100644 --- a/src/components/wallet_mobile/src/wasm/mod.rs +++ b/src/components/wallet_mobile/src/wasm/mod.rs @@ -6,8 +6,8 @@ use credentials::{ }; use ruc::{d, err::RucResult}; use wasm_bindgen::prelude::*; -use zei::xfr::sig::{XfrKeyPair, XfrPublicKey}; -use zei::xfr::structs::ASSET_TYPE_LENGTH; +use zei::noah_api::xfr::structs::ASSET_TYPE_LENGTH; +use zei::{XfrKeyPair, XfrPublicKey}; #[wasm_bindgen] /// Generates asset type as a Base64 string from a JSON-serialized JavaScript value. diff --git a/src/components/wasm/Cargo.toml b/src/components/wasm/Cargo.toml index de2e9f212..2461fbd16 100644 --- a/src/components/wasm/Cargo.toml +++ b/src/components/wasm/Cargo.toml @@ -14,11 +14,11 @@ license = "" wasm-opt = false [dependencies] -base64 = "0.12" -hex = "0.4.2" +base64 = "0.13" +hex = "0.4.3" js-sys = "0.3.27" -rand_chacha = "0.2" -rand_core = { version = "0.5", default-features = false, features = ["alloc"] } +rand_chacha = "0.3" +rand_core = { version = "0.6", default-features = false, features = ["alloc"] } rand = { version = "0.7", features = ["wasm-bindgen"] } serde = { version = "1.0.124", features = ["derive"] } serde_json = "1.0" @@ -26,21 +26,21 @@ wasm-bindgen = { version = "=0.2.84", features = ["serde-serialize"] } fbnc = { version = "0.2.9", default-features = false} ring = "0.16.19" -aes-gcm = "0.9.0" +aes-gcm = "^0.10.1" bech32 = "0.7.2" # Must enable the "js"-feature, # OR the compiling will fail. getrandom = { version = "0.2", features = ["js"] } -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } ruc = "1.0" finutils = { path = "../finutils", default-features = false } -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } -credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", tag = "v1.0.0" } -cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", tag = "v1.0.0" } +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } +credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", branch = "develop" } +cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", branch = "develop" } ledger = { path = "../../ledger" } diff --git a/src/components/wasm/src/wasm.rs b/src/components/wasm/src/wasm.rs index 4bf909c71..a9bfc7647 100644 --- a/src/components/wasm/src/wasm.rs +++ b/src/components/wasm/src/wasm.rs @@ -20,7 +20,7 @@ use { AttributeDefinition, ClientAssetRecord, Credential, CredentialCommitment, CredentialCommitmentData, CredentialCommitmentKey, CredentialIssuerKeyPair, CredentialPoK, CredentialRevealSig, CredentialSignature, CredentialUserKeyPair, - OwnerMemo, PublicParams, TracingPolicies, TxoRef, + OwnerMemo, TracingPolicies, TxoRef, }, credentials::{ credential_commit, credential_issuer_key_gen, credential_open_commitment, @@ -63,16 +63,19 @@ use { std::str::FromStr, wasm_bindgen::prelude::*, zei::{ - serialization::ZeiFromToBytes, - xfr::{ + noah_algebra::{ + prelude::{NoahFromToBytes, Scalar}, + ristretto::PedersenCommitmentRistretto, + }, + noah_api::xfr::{ asset_record::{open_blind_asset_record as open_bar, AssetRecordType}, - lib::trace_assets as zei_trace_assets, - sig::{XfrKeyPair, XfrPublicKey, XfrSecretKey}, structs::{ - AssetRecordTemplate, AssetType as ZeiAssetType, XfrBody, + AssetRecordTemplate, AssetType as NoahAssetType, ASSET_TYPE_LENGTH, }, + trace_assets as noah_trace_assets, }, + OwnerMemo as NoahOwnerMemo, XfrKeyPair, XfrPublicKey, XfrSecretKey, XfrBody }, }; @@ -99,28 +102,13 @@ pub fn random_asset_type() -> String { AssetTypeCode::gen_random().to_base64() } -#[wasm_bindgen] -/// Creates a new asset code with prefixing-hashing the original code to query the ledger. -pub fn hash_asset_code(asset_code_string: String) -> Result { - let original_asset_code = AssetTypeCode::new_from_base64(&asset_code_string) - .c(d!()) - .map_err(error_to_jsvalue)?; - - let derived_asset_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( - AssetTypePrefix::UserDefined, - &original_asset_code, - ); - - Ok(derived_asset_code.to_base64()) -} - #[wasm_bindgen] /// Generates asset type as a Base64 string from a JSON-serialized JavaScript value. pub fn asset_type_from_jsvalue(val: &JsValue) -> Result { let code: [u8; ASSET_TYPE_LENGTH] = val.into_serde().c(d!()).map_err(error_to_jsvalue)?; Ok(AssetTypeCode { - val: ZeiAssetType(code), + val: NoahAssetType(code), } .to_base64()) } @@ -155,7 +143,7 @@ pub fn verify_authenticated_txn( #[wasm_bindgen] /// ... pub fn get_null_pk() -> XfrPublicKey { - XfrPublicKey::zei_from_bytes(&[0; 32]).unwrap() + XfrPublicKey::noah_from_bytes(&[0; 32]).unwrap() } #[wasm_bindgen] @@ -195,7 +183,7 @@ impl From for PlatformFeeInput { am: fi.am, tr: fi.tr.txo_ref, ar: fi.ar.txo, - om: fi.om.map(|om| om.memo), + om: fi.om.map(|om| NoahOwnerMemo::from_noah(&om.memo).unwrap()), kp: fi.kp, } } @@ -409,7 +397,6 @@ impl TransactionBuilder { seq_num, amount, confidentiality_flags, - PublicParams::new().get_ref(), ) .c(d!()) .map_err(error_to_jsvalue)?; @@ -607,7 +594,7 @@ impl TransactionBuilder { pub fn get_owner_memo(&self, idx: usize) -> Option { self.get_builder() .get_owner_memo_ref(idx) - .map(|memo| OwnerMemo { memo: memo.clone() }) + .map(|memo| OwnerMemo { memo: memo.into_noah() }) } } @@ -721,11 +708,11 @@ impl TransferOperationBuilder { amount: u64, ) -> Result { let oar = open_bar( - asset_record.get_bar_ref(), + &asset_record.get_bar_ref().into_noah(), &owner_memo.map(|memo| memo.get_memo_ref().clone()), - &key, + &key.into_noah(), ) - .c(d!()) + .c(d!()) .map_err(|e| { JsValue::from_str(&format!("Could not open asset record: {}", e)) })?; @@ -763,7 +750,7 @@ impl TransferOperationBuilder { amount, code.val, asset_record_type, - *recipient, + recipient.into_noah(), policies.get_policies_ref().clone(), ) } else { @@ -771,7 +758,7 @@ impl TransferOperationBuilder { amount, code.val, asset_record_type, - *recipient, + recipient.into_noah(), ) }; self.get_builder_mut() @@ -967,9 +954,9 @@ pub fn open_client_asset_record( keypair: &XfrKeyPair, ) -> Result { open_bar( - record.get_bar_ref(), + &record.get_bar_ref().into_noah(), &owner_memo.map(|memo| memo.get_memo_ref().clone()), - &keypair, + &keypair.into_noah(), ) .c(d!()) .map_err(|e| JsValue::from_str(&format!("Could not open asset record: {}", e))) @@ -1021,14 +1008,14 @@ pub fn public_key_from_base64(pk: &str) -> Result { /// Expresses a transfer key pair as a hex-encoded string. /// To decode the string, use `keypair_from_str` function. pub fn keypair_to_str(key_pair: &XfrKeyPair) -> String { - hex::encode(key_pair.zei_to_bytes()) + hex::encode(key_pair.noah_to_bytes()) } #[wasm_bindgen] /// Constructs a transfer key pair from a hex-encoded string. /// The encode a key pair, use `keypair_to_str` function. pub fn keypair_from_str(str: String) -> XfrKeyPair { - XfrKeyPair::zei_from_bytes(&hex::decode(str).unwrap()).unwrap() + XfrKeyPair::noah_from_bytes(&hex::decode(str).unwrap()).unwrap() } #[wasm_bindgen] @@ -1070,7 +1057,7 @@ pub fn wasm_credential_verify_commitment( issuer_pub_key, commitment.get_ref(), pok.get_ref(), - xfr_pk.as_bytes(), + &xfr_pk.to_bytes(), ) .c(d!()) .map_err(error_to_jsvalue) @@ -1182,7 +1169,7 @@ pub fn wasm_credential_commit( &mut prng, &user_secret_key, credential.get_cred_ref(), - &user_public_key.as_bytes(), + &user_public_key.to_bytes(), ) .c(d!()) .map_err(error_to_jsvalue)?; @@ -1262,15 +1249,16 @@ pub fn trace_assets( // let candidate_assets: Vec = // candidate_assets.into_serde().c(d!()).map_err(error_to_jsvalue)?; let xfr_body: XfrBody = xfr_body.into_serde().c(d!()).map_err(error_to_jsvalue)?; - // let candidate_assets: Vec = candidate_assets + // let candidate_assets: Vec = candidate_assets // .iter() // .map(|asset_type_str| { // AssetTypeCode::new_from_str(&asset_type_str.to_string()).val // }) // .collect(); - let record_data = zei_trace_assets(&xfr_body, tracer_keypair.get_keys()) - .c(d!()) - .map_err(error_to_jsvalue)?; + let record_data = + noah_trace_assets(&xfr_body.into_noah(), tracer_keypair.get_keys()) + .c(d!()) + .map_err(error_to_jsvalue)?; let record_data: Vec<(u64, String)> = record_data .iter() .map(|(amt, asset_type, _, _)| { @@ -1288,9 +1276,17 @@ pub fn trace_assets( // Author: Chao Ma, github.com/chaosma. // ////////////////////////////////////////// -use aes_gcm::aead::{generic_array::GenericArray, Aead, NewAead}; -use aes_gcm::Aes256Gcm; -use rand::{thread_rng, Rng}; +use aes_gcm::{ + aead::{generic_array::GenericArray, Aead, KeyInit}, + Aes256Gcm, +}; +use base64::URL_SAFE; +use fp_types::H160; +use getrandom::getrandom; +use js_sys::JsString; +use ledger::staking::Amount; + +use rand_core::{CryptoRng, RngCore}; use ring::pbkdf2; use std::num::NonZeroU32; use std::str; @@ -1329,10 +1325,9 @@ pub fn encryption_pbkdf2_aes256gcm(key_pair: String, password: String) -> Vec Vec u64 { #[wasm_bindgen] /// The destination for fee to be transfered to. pub fn fra_get_dest_pubkey() -> XfrPublicKey { - *BLACK_HOLE_PUBKEY + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY) } #[wasm_bindgen] @@ -1517,13 +1512,13 @@ pub fn get_delegation_target_address() -> String { #[wasm_bindgen] #[allow(missing_docs)] pub fn get_coinbase_address() -> String { - wallet::public_key_to_base64(&BLACK_HOLE_PUBKEY_STAKING) + wallet::public_key_to_base64(&XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING)) } #[wasm_bindgen] #[allow(missing_docs)] pub fn get_coinbase_principal_address() -> String { - wallet::public_key_to_base64(&BLACK_HOLE_PUBKEY_STAKING) + wallet::public_key_to_base64(&XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING)) } #[wasm_bindgen] diff --git a/src/components/wasm/src/wasm_data_model.rs b/src/components/wasm/src/wasm_data_model.rs index 4b9666eb0..13eefd6fa 100644 --- a/src/components/wasm/src/wasm_data_model.rs +++ b/src/components/wasm/src/wasm_data_model.rs @@ -17,46 +17,20 @@ use { serde::{Deserialize, Serialize}, wasm_bindgen::prelude::*, zei::{ - setup::PublicParams as ZeiPublicParams, - xfr::{ - sig::XfrPublicKey, + noah_algebra::ristretto::PedersenCommitmentRistretto, + noah_api::xfr::{ structs::{ AssetTracerDecKeys, AssetTracerEncKeys, - AssetTracerKeyPair as ZeiAssetTracerKeyPair, BlindAssetRecord, - IdentityRevealPolicy, OwnerMemo as ZeiOwnerMemo, - TracingPolicies as ZeiTracingPolicies, - TracingPolicy as ZeiTracingPolicy, + AssetTracerKeyPair as NoahAssetTracerKeyPair, + IdentityRevealPolicy, OwnerMemo as NoahOwnerMemo, + TracingPolicies as NoahTracingPolicies, + TracingPolicy as NoahTracingPolicy, }, }, + XfrPublicKey, BlindAssetRecord, }, }; -#[wasm_bindgen] -/// Public parameters necessary for generating asset records. Generating this is expensive and -/// should be done as infrequently as possible. -/// @see {@link module:Findora-Wasm~TransactionBuilder#add_basic_issue_asset|add_basic_issue_asset} -/// for information using public parameters to create issuance asset records. -pub struct PublicParams { - pub(crate) params: ZeiPublicParams, -} - -#[wasm_bindgen] -#[allow(clippy::new_without_default)] -impl PublicParams { - /// Generates a new set of parameters. - pub fn new() -> PublicParams { - PublicParams { - params: ZeiPublicParams::default(), - } - } -} - -impl PublicParams { - pub fn get_ref(&self) -> &ZeiPublicParams { - &self.params - } -} - #[wasm_bindgen] /// Indicates whether the TXO ref is an absolute or relative value. #[derive(Copy, Clone)] @@ -204,7 +178,7 @@ impl ClientAssetRecord { /// @see {@link module:Findora-Wasm~AssetRules#add_tracing_policy|add_tracing_policy} for information about how to add a tracing policy to /// an asset definition. pub struct AssetTracerKeyPair { - pub(crate) keypair: ZeiAssetTracerKeyPair, + pub(crate) keypair: NoahAssetTracerKeyPair, } #[wasm_bindgen] @@ -213,7 +187,7 @@ impl AssetTracerKeyPair { pub fn new() -> Self { let mut small_rng = ChaChaRng::from_entropy(); AssetTracerKeyPair { - keypair: ZeiAssetTracerKeyPair::generate(&mut small_rng), + keypair: NoahAssetTracerKeyPair::generate(&mut small_rng), } } } @@ -232,7 +206,7 @@ impl AssetTracerKeyPair { &self.keypair.dec_key } - pub fn get_keys(&self) -> &ZeiAssetTracerKeyPair { + pub fn get_keys(&self) -> &NoahAssetTracerKeyPair { &self.keypair } } @@ -242,7 +216,7 @@ impl AssetTracerKeyPair { /// Asset owner memo. Contains information needed to decrypt an asset record. /// @see {@link module:Findora-Wasm.ClientAssetRecord|ClientAssetRecord} for more details about asset records. pub struct OwnerMemo { - pub(crate) memo: ZeiOwnerMemo, + pub(crate) memo: NoahOwnerMemo, } #[wasm_bindgen] @@ -257,12 +231,13 @@ impl OwnerMemo { /// "lock":{"ciphertext":[119,54,117,136,125,133,112,193],"encoded_rand":"8KDql2JphPB5WLd7-aYE1bxTQAcweFSmrqymLvPDntM="} /// } pub fn from_json(val: &JsValue) -> Result { - let zei_owner_memo: ZeiOwnerMemo = + let noah_owner_memo: NoahOwnerMemo = val.into_serde().c(d!()).map_err(error_to_jsvalue)?; Ok(OwnerMemo { - memo: ZeiOwnerMemo { - blind_share: zei_owner_memo.blind_share, - lock: zei_owner_memo.lock, + memo: NoahOwnerMemo { + key_type: noah_owner_memo.key_type, + blind_share_bytes: noah_owner_memo.blind_share_bytes, + lock_bytes: noah_owner_memo.lock_bytes, }, }) } @@ -276,11 +251,12 @@ impl OwnerMemo { } impl OwnerMemo { - pub fn get_memo_ref(&self) -> &ZeiOwnerMemo { + pub fn get_memo_ref(&self) -> &NoahOwnerMemo { &self.memo } } + #[derive(Serialize, Deserialize)] pub(crate) struct AttributeDefinition { pub name: String, @@ -330,7 +306,7 @@ impl CredentialRevealSig { /// credential commitment. pub fn get_commitment(&self) -> CredentialCommitment { CredentialCommitment { - commitment: self.sig.sig_commitment.clone(), + commitment: self.sig.cm.clone(), } } /// Returns the underlying proof of knowledge that the credential is valid. @@ -338,7 +314,7 @@ impl CredentialRevealSig { /// credential commitment. pub fn get_pok(&self) -> CredentialPoK { CredentialPoK { - pok: self.sig.pok.clone(), + pok: self.sig.proof_open.clone(), } } } @@ -576,11 +552,11 @@ impl SignatureRules { /// A collection of tracing policies. Use this object when constructing asset transfers to generate /// the correct tracing proofs for traceable assets. pub struct TracingPolicies { - pub(crate) policies: ZeiTracingPolicies, + pub(crate) policies: NoahTracingPolicies, } impl TracingPolicies { - pub fn get_policies_ref(&self) -> &ZeiTracingPolicies { + pub fn get_policies_ref(&self) -> &NoahTracingPolicies { &self.policies } } @@ -589,13 +565,13 @@ impl TracingPolicies { /// Tracing policy for asset transfers. Can be configured to track credentials, the asset type and /// amount, or both. pub struct TracingPolicy { - pub(crate) policy: ZeiTracingPolicy, + pub(crate) policy: NoahTracingPolicy, } #[wasm_bindgen] impl TracingPolicy { pub fn new_with_tracing(tracing_key: &AssetTracerKeyPair) -> Self { - let policy = ZeiTracingPolicy { + let policy = NoahTracingPolicy { enc_keys: tracing_key.get_enc_key().clone(), asset_tracing: true, identity_tracing: None, @@ -615,7 +591,7 @@ impl TracingPolicy { cred_issuer_pub_key: cred_issuer_key.get_ref().clone(), reveal_map, }; - let policy = ZeiTracingPolicy { + let policy = NoahTracingPolicy { enc_keys: tracing_key.get_enc_key().clone(), asset_tracing: tracing, identity_tracing: Some(identity_policy), @@ -625,7 +601,7 @@ impl TracingPolicy { } impl TracingPolicy { - pub fn get_ref(&self) -> &ZeiTracingPolicy { + pub fn get_ref(&self) -> &NoahTracingPolicy { &self.policy } } diff --git a/src/ledger/Cargo.toml b/src/ledger/Cargo.toml index 9ea5afd6c..5d37a3afb 100644 --- a/src/ledger/Cargo.toml +++ b/src/ledger/Cargo.toml @@ -6,22 +6,22 @@ edition = "2021" build = "build.rs" [dependencies] -base64 = "0.12" +base64 = "0.13" bincode = "1.3.1" byteorder = "1.0.0" -curve25519-dalek = { version = "3.0", features = ["serde"] } -ed25519-dalek = "1.0.0" -hex = "0.4.2" +curve25519-dalek = { package = "noah-curve25519-dalek", version = "4.0.0", default-features = false, features = ['serde'] } +ed25519-dalek = { package = "noah-ed25519-dalek", git = "https://github.com/FindoraNetwork/ed25519-dalek", tag = "v4.0.0" } +hex = "0.4.3" lazy_static = { version = "1.2.0" } tracing = "0.1" -rand = "=0.7.3" -rand_chacha = "0.2" -rand_core = { version = "0.5", default-features = false, features = ["alloc"] } +rand = "0.8" +rand_chacha = "0.3" +rand_core = { version = "0.6", default-features = false, features = ["alloc"] } serde = { version = "1.0.124", features = ["derive"] } serde_derive = "1.0" serde_json = "1.0" serde-strz = "1.1.1" -sha2 = "0.9.5" +sha2 = "0.10" unicode-normalization = "0.1.13" time = "0.3" tendermint = { git = "https://github.com/FindoraNetwork/tendermint-rs", tag = "v0.19.0a-fk" } @@ -30,21 +30,18 @@ config = { path = "../components/config" } fp-types = { path = "../components/contracts/primitives/types" } fp-utils = { path = "../components/contracts/primitives/utils" } ruc = "1.0" -zei = { git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } -zeiutils = { package = "utils", git = "https://github.com/FindoraNetwork/zei", branch = "stable-main" } +zei = { package="platform-lib-noah", git = "https://github.com/FindoraNetwork/platform-lib-noah", branch = "develop" } bulletproofs = { package = "bulletproofs", git = "https://github.com/FindoraNetwork/bp", rev = "57633a", features = ["yoloproofs"] } -noah-algebra = { git = "https://github.com/FindoraNetwork/noah", tag = "v0.4.3-1" } -noah-crypto = { git = "https://github.com/FindoraNetwork/noah", tag = "v0.4.3-1" } fbnc = { version = "0.2.9", default-features = false} once_cell = "1" num-bigint = "0.4.3" -globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", tag = "v1.0.0" } -bitmap = { git = "https://github.com/FindoraNetwork/platform-lib-bitmap", tag = "v1.0.0" } -cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", tag = "v1.0.0" } -credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", tag = "v1.0.0" } -merkle_tree = { git = "https://github.com/FindoraNetwork/platform-lib-merkle", tag = "v1.0.0" } -sliding_set = { git = "https://github.com/FindoraNetwork/platform-lib-slidingset", tag = "v1.0.0" } +globutils = { git = "https://github.com/FindoraNetwork/platform-lib-utils", branch = "develop" } +bitmap = { git = "https://github.com/FindoraNetwork/platform-lib-bitmap", branch = "develop" } +cryptohash = { git = "https://github.com/FindoraNetwork/platform-lib-cryptohash", branch = "develop" } +credentials = { git = "https://github.com/FindoraNetwork/platform-lib-credentials", branch = "develop" } +merkle_tree = { git = "https://github.com/FindoraNetwork/platform-lib-merkle", branch = "develop" } +sliding_set = { git = "https://github.com/FindoraNetwork/platform-lib-slidingset", branch = "develop" } [features] default = [] diff --git a/src/ledger/src/converter/mod.rs b/src/ledger/src/converter/mod.rs index 08526f293..802ecc9d9 100644 --- a/src/ledger/src/converter/mod.rs +++ b/src/ledger/src/converter/mod.rs @@ -13,9 +13,9 @@ use { ruc::*, serde::{Deserialize, Serialize}, std::sync::atomic::{AtomicI64, Ordering}, - zei::xfr::{ - sig::XfrPublicKey, - structs::{AssetType, XfrAmount, XfrAssetType}, + zei::{ + noah_api::xfr::structs::{AssetType, XfrAmount, XfrAssetType}, + XfrPublicKey, }, }; #[allow(missing_docs)] @@ -155,7 +155,8 @@ pub fn check_convert_account( )); } if let XfrAssetType::NonConfidential(ty) = o.record.asset_type { - if o.record.public_key == *BLACK_HOLE_PUBKEY_STAKING + if o.record.public_key + == XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING) && ty == expected_asset { if let XfrAmount::NonConfidential(amount) = o.record.amount { diff --git a/src/ledger/src/data_model/__trash__.rs b/src/ledger/src/data_model/__trash__.rs index 54eb3a04b..ee27a584d 100644 --- a/src/ledger/src/data_model/__trash__.rs +++ b/src/ledger/src/data_model/__trash__.rs @@ -12,8 +12,8 @@ use { crate::data_model::AssetTypeCode, fixed::types::I20F12, serde::{Deserialize, Serialize}, - zei::xfr::sig::XfrPublicKey, - zei::xfr::structs::AssetType, + zei::noah_api::xfr::structs::AssetType, + zei::XfrPublicKey, }; #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)] diff --git a/src/ledger/src/data_model/effects.rs b/src/ledger/src/data_model/effects.rs index 491d0835d..09ccea520 100644 --- a/src/ledger/src/data_model/effects.rs +++ b/src/ledger/src/data_model/effects.rs @@ -1,3 +1,4 @@ +use zei::noah_api::parameters::bulletproofs::BulletproofParams; use { crate::{ data_model::{ @@ -28,21 +29,20 @@ use { sync::Arc, }, zei::{ - serialization::ZeiFromToBytes, - setup::PublicParams, - xfr::{ - lib::verify_xfr_body, - sig::XfrPublicKey, + noah_algebra::serialization::NoahFromToBytes, + noah_api::xfr::{ structs::{XfrAmount, XfrAssetType}, + verify_xfr_body, }, + XfrPublicKey, }, }; lazy_static! { static ref PRNG: Arc> = Arc::new(Mutex::new(ChaChaRng::from_entropy())); - static ref PARAMS: Arc> = - Arc::new(Mutex::new(PublicParams::default())); + static ref PARAMS: Arc> = + Arc::new(Mutex::new(BulletproofParams::default())); } /// Check operations in the context of a tx, partially. @@ -405,12 +405,12 @@ impl TxnEffect { if !trn.body.verify_body_signature(sig) { return Err(eg!()); } - input_keys.insert(sig.address.key.zei_to_bytes()); + input_keys.insert(sig.address.key.noah_to_bytes()); } // (1b) all input record owners have signed for record in trn.body.transfer.inputs.iter() { - if !input_keys.contains(&record.public_key.zei_to_bytes()) { + if !input_keys.contains(&record.public_key.noah_to_bytes()) { return Err(eg!()); } } @@ -418,7 +418,7 @@ impl TxnEffect { verify_xfr_body( prng, params, - &trn.body.transfer, + &trn.body.transfer.into_noah(), &trn.body.policies.to_ref(), ) .c(d!())?; diff --git a/src/ledger/src/data_model/mod.rs b/src/ledger/src/data_model/mod.rs index d3b2a54e7..22542b9fd 100644 --- a/src/ledger/src/data_model/mod.rs +++ b/src/ledger/src/data_model/mod.rs @@ -10,9 +10,6 @@ mod effects; mod test; pub use effects::{BlockEffect, TxnEffect}; -use noah_algebra::bls12_381::BLSScalar; -use noah_algebra::prelude::Scalar; -use noah_crypto::basic::anemoi_jive::{AnemoiJive, AnemoiJive381}; use { crate::converter::ConvertAccount, @@ -28,6 +25,7 @@ use { }, __trash__::{Policy, PolicyGlobals, TxnPolicyData}, bitmap::SparseMap, + config::abci::CheckPointConfig, cryptohash::{sha256::Digest as BitDigest, HashValue}, fbnc::NumKey, globutils::wallet::public_key_to_base64, @@ -49,16 +47,23 @@ use { }, unicode_normalization::UnicodeNormalization, zei::{ - serialization::ZeiFromToBytes, - xfr::{ - lib::{gen_xfr_body, XfrNotePolicies}, - sig::{XfrKeyPair, XfrPublicKey}, - structs::{ - AssetRecord, AssetType as ZeiAssetType, BlindAssetRecord, OwnerMemo, - TracingPolicies, TracingPolicy, XfrAmount, XfrAssetType, XfrBody, - ASSET_TYPE_LENGTH, + noah_algebra::{ + bls12_381::BLSScalar, bn254::BN254Scalar, serialization::NoahFromToBytes, + traits::Scalar, + }, + noah_api::{ + keys::PublicKey as NoahXfrPublicKey, + xfr::{ + gen_xfr_body, + structs::{ + AssetRecord, AssetType as NoahAssetType, TracingPolicies, + TracingPolicy, XfrAmount, XfrAssetType, ASSET_TYPE_LENGTH, + }, + XfrNotePolicies, }, }, + noah_crypto::anemoi_jive::{AnemoiJive, AnemoiJive254}, + BlindAssetRecord, OwnerMemo, XfrBody, XfrKeyPair, XfrPublicKey, }, }; @@ -94,7 +99,7 @@ fn is_default(x: &T) -> bool { /// Findora asset type code pub struct AssetTypeCode { /// Internal asset type - pub val: ZeiAssetType, + pub val: NoahAssetType, } impl NumKey for AssetTypeCode { @@ -105,7 +110,7 @@ impl NumKey for AssetTypeCode { let mut b = b.to_owned(); b.resize(ASSET_TYPE_LENGTH, 0u8); Ok(Self { - val: ZeiAssetType( + val: NoahAssetType( <[u8; ASSET_TYPE_LENGTH]>::try_from(b.as_slice()).c(d!())?, ), }) @@ -119,7 +124,7 @@ impl Default for AssetTypeCode { #[inline(always)] fn default() -> Self { AssetTypeCode { - val: ZeiAssetType([255; ASSET_TYPE_LENGTH]), + val: NoahAssetType([255; ASSET_TYPE_LENGTH]), } } } @@ -147,7 +152,7 @@ impl AssetTypeCode { pub fn gen_random_with_rng(prng: &mut R) -> Self { let val: [u8; ASSET_TYPE_LENGTH] = prng.gen(); Self { - val: ZeiAssetType(val), + val: NoahAssetType(val), } } @@ -162,7 +167,7 @@ impl AssetTypeCode { pub fn new_from_vec(mut bytes: Vec) -> Self { bytes.resize(ASSET_TYPE_LENGTH, 0u8); Self { - val: ZeiAssetType( + val: NoahAssetType( <[u8; ASSET_TYPE_LENGTH]>::try_from(bytes.as_slice()).unwrap(), ), } @@ -226,7 +231,7 @@ impl AssetTypeCode { as_vec.resize(ASSET_TYPE_LENGTH, 0u8); let buf = <[u8; ASSET_TYPE_LENGTH]>::try_from(as_vec.as_slice()).unwrap(); Self { - val: ZeiAssetType(buf), + val: NoahAssetType(buf), } } @@ -240,7 +245,7 @@ impl AssetTypeCode { bin.resize(ASSET_TYPE_LENGTH, 0u8); let buf = <[u8; ASSET_TYPE_LENGTH]>::try_from(bin.as_slice()).c(d!())?; Ok(Self { - val: ZeiAssetType(buf), + val: NoahAssetType(buf), }) } Err(e) => Err(eg!((format!("Failed to deserialize base64 '{b64}': {e}",)))), @@ -261,13 +266,38 @@ impl AssetTypeCode { /// Generates the asset type code from the prefix and the Anemoi hash function #[inline(always)] - pub fn from_prefix_and_raw_asset_type_code( + pub fn from_prefix_and_raw_asset_type_code_2nd_update( prefix: AssetTypePrefix, raw_asset_type_code: &AssetTypeCode, ) -> Self { let mut f = Vec::with_capacity(3); f.push(prefix.to_field_element()); + let mut bytes = vec![0u8; 32]; + bytes[..31].copy_from_slice(&raw_asset_type_code.val.0[..31]); + f.push(BN254Scalar::from_bytes(&bytes).unwrap()); + + let mut bytes = vec![0u8; 32]; + bytes[0] = raw_asset_type_code.val.0[31]; + f.push(BN254Scalar::from_bytes(&bytes).unwrap()); + + let res = AnemoiJive254::eval_variable_length_hash(&f); + Self::new_from_vec(res.to_bytes()) + } + + /// Former version, now deprecated way to derive the asset code. + /// This version uses BLS12-381. + #[inline(always)] + #[deprecated] + pub fn from_prefix_and_raw_asset_type_code_1st_update( + prefix: AssetTypePrefix, + raw_asset_type_code: &AssetTypeCode, + ) -> Self { + let mut f = Vec::with_capacity(3); + + #[allow(deprecated)] + f.push(prefix.to_field_element_old()); + let mut bytes = vec![0u8; 32]; bytes[..31].copy_from_slice(&raw_asset_type_code.val.0[..31]); f.push(BLSScalar::from_bytes(&bytes).unwrap()); @@ -276,8 +306,42 @@ impl AssetTypeCode { bytes[0] = raw_asset_type_code.val.0[31]; f.push(BLSScalar::from_bytes(&bytes).unwrap()); - let res = AnemoiJive381::eval_variable_length_hash(&f); - Self::new_from_vec(res.to_bytes()) + #[allow(deprecated)] + { + use zei::noah_crypto::anemoi_jive::bls12_381_deprecated::AnemoiJive381Deprecated; + let res = AnemoiJive381Deprecated::eval_variable_length_hash(&f); + Self::new_from_vec(res.to_bytes()) + } + } + + /// Select the right asset code based on the global setting. + pub fn from_prefix_and_raw_asset_type_code( + prefix: AssetTypePrefix, + raw_asset_type_code: &AssetTypeCode, + checkpoint: &CheckPointConfig, + cur_height: u64, + ) -> Self { + if raw_asset_type_code.val == ASSET_TYPE_FRA + || core::cmp::min( + checkpoint.utxo_asset_prefix_height, + checkpoint.utxo_asset_prefix_height_2nd_update, + ) > cur_height + { + *raw_asset_type_code + } else if checkpoint.utxo_asset_prefix_height_2nd_update > cur_height + && checkpoint.utxo_asset_prefix_height <= cur_height + { + #[allow(deprecated)] + AssetTypeCode::from_prefix_and_raw_asset_type_code_1st_update( + prefix, + &raw_asset_type_code, + ) + } else { + AssetTypeCode::from_prefix_and_raw_asset_type_code_2nd_update( + prefix, + &raw_asset_type_code, + ) + } } } @@ -417,7 +481,7 @@ pub struct XfrAddress { impl XfrAddress { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_base64(self) -> String { - b64enc(&self.key.as_bytes()) + b64enc(&self.key.to_bytes()) } // pub(crate) fn to_bytes(self) -> Vec { @@ -428,7 +492,7 @@ impl XfrAddress { impl Hash for XfrAddress { #[inline(always)] fn hash(&self, state: &mut H) { - self.key.as_bytes().hash(state); + self.key.to_bytes().hash(state); } } @@ -443,7 +507,7 @@ pub struct IssuerPublicKey { impl IssuerPublicKey { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_base64(self) -> String { - b64enc(self.key.as_bytes()) + b64enc(&self.key.noah_to_bytes().as_slice()) } // pub(crate) fn to_bytes(&self) -> Vec { @@ -454,7 +518,7 @@ impl IssuerPublicKey { impl Hash for IssuerPublicKey { #[inline(always)] fn hash(&self, state: &mut H) { - self.key.as_bytes().hash(state); + self.key.to_bytes().hash(state); } } @@ -517,7 +581,7 @@ impl SignatureRules { let mut weight_map = HashMap::new(); // Convert to map for (key, weight) in self.weights.iter() { - weight_map.insert(key.as_bytes(), *weight); + weight_map.insert(key.to_bytes(), *weight); } // Calculate weighted sum for key in keyset.iter() { @@ -920,8 +984,9 @@ impl TransferAssetBody { return Err(eg!()); } - let transfer = - Box::new(gen_xfr_body(prng, input_records, output_records).c(d!())?); + let transfer = Box::new(XfrBody::from_noah( + &gen_xfr_body(prng, input_records, output_records).c(d!())?, + )); let outputs = transfer .outputs .iter() @@ -1083,7 +1148,13 @@ impl AssetTypePrefix { } #[allow(missing_docs)] - pub fn to_field_element(&self) -> BLSScalar { + pub fn to_field_element(&self) -> BN254Scalar { + BN254Scalar::from_bytes(&self.bytes()).unwrap() + } + + #[allow(missing_docs)] + #[deprecated] + pub fn to_field_element_old(&self) -> BLSScalar { BLSScalar::from_bytes(&self.bytes()).unwrap() } } @@ -1658,7 +1729,7 @@ impl FinalizedTransaction { } /// Use pure zero bytes(aka [0, 0, ... , 0]) to express FRA. -pub const ASSET_TYPE_FRA: ZeiAssetType = ZeiAssetType([0; ASSET_TYPE_LENGTH]); +pub const ASSET_TYPE_FRA: NoahAssetType = NoahAssetType([0; ASSET_TYPE_LENGTH]); /// FRA decimals pub const FRA_DECIMALS: u8 = 6; @@ -1666,9 +1737,9 @@ pub const FRA_DECIMALS: u8 = 6; lazy_static! { /// The destination of Fee is an black hole, /// all token transfered to it will be burned. - pub static ref BLACK_HOLE_PUBKEY: XfrPublicKey = pnk!(XfrPublicKey::zei_from_bytes(&[0; ed25519_dalek::PUBLIC_KEY_LENGTH][..])); + pub static ref BLACK_HOLE_PUBKEY: NoahXfrPublicKey = pnk!(NoahXfrPublicKey::noah_from_bytes(&[0; ed25519_dalek::PUBLIC_KEY_LENGTH][..])); /// BlackHole of Staking - pub static ref BLACK_HOLE_PUBKEY_STAKING: XfrPublicKey = pnk!(XfrPublicKey::zei_from_bytes(&[1; ed25519_dalek::PUBLIC_KEY_LENGTH][..])); + pub static ref BLACK_HOLE_PUBKEY_STAKING: NoahXfrPublicKey = pnk!(NoahXfrPublicKey::noah_from_bytes(&[1; ed25519_dalek::PUBLIC_KEY_LENGTH][..])); } /// see [**mainnet-v0.1 defination**](https://www.notion.so/findora/Transaction-Fees-Analysis-d657247b70f44a699d50e1b01b8a2287) @@ -1710,7 +1781,8 @@ impl Transaction { return x.body.outputs.iter().any(|o| { if let XfrAssetType::NonConfidential(ty) = o.record.asset_type { if ty == ASSET_TYPE_FRA - && *BLACK_HOLE_PUBKEY == o.record.public_key + && XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY) + == o.record.public_key { if let XfrAmount::NonConfidential(am) = o.record.amount { if am > (TX_FEE_MIN - 1) { diff --git a/src/ledger/src/data_model/test.rs b/src/ledger/src/data_model/test.rs index e08bf051a..6476bba6c 100644 --- a/src/ledger/src/data_model/test.rs +++ b/src/ledger/src/data_model/test.rs @@ -6,12 +6,28 @@ use { rand_core::SeedableRng, std::cmp::min, zei::{ - ristretto, - xfr::structs::{AssetTypeAndAmountProof, XfrBody, XfrProofs}, + noah_api::{ + ristretto, + xfr::structs::{AssetTypeAndAmountProof, XfrProofs}, + }, + XfrBody }, - zeiutils::msg_eq, }; +#[macro_export] +macro_rules! msg_eq { + ($noah_err: expr, $ruc_err: expr $(,)?) => { + assert!($ruc_err.msg_has_overloop(ruc::eg!($noah_err).as_ref())); + }; + ($noah_err: expr, $ruc_err: expr, $msg: expr $(,)?) => { + assert!( + $ruc_err.msg_has_overloop(ruc::eg!($noah_err).as_ref()), + $msg + ); + }; +} + + const UTF8_ASSET_TYPES_WORK: bool = false; // This test may fail as it is a statistical test that sometimes fails (but very rarely) @@ -260,7 +276,7 @@ fn test_add_operation() { fn gen_fee_operation( amount: Option, - asset_type: Option, + asset_type: Option, dest_pubkey: XfrPublicKey, ) -> Operation { Operation::TransferAsset(TransferAsset { @@ -307,38 +323,41 @@ fn test_check_fee() { let mut tx = gen_sample_tx(); assert!(!tx.check_fee()); - let invalid_confidential_type = - gen_fee_operation(Some(TX_FEE_MIN), None, *BLACK_HOLE_PUBKEY); + let invalid_confidential_type = gen_fee_operation( + Some(TX_FEE_MIN), + None, + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), + ); let invalid_confidential_amount = gen_fee_operation( None, - Some(ZeiAssetType([0; ASSET_TYPE_LENGTH])), - *BLACK_HOLE_PUBKEY, + Some(NoahAssetType([0; ASSET_TYPE_LENGTH])), + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), ); let invalid_nonconfidential_not_fra_code = gen_fee_operation( Some(TX_FEE_MIN), - Some(ZeiAssetType([9; ASSET_TYPE_LENGTH])), - *BLACK_HOLE_PUBKEY, + Some(NoahAssetType([9; ASSET_TYPE_LENGTH])), + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), ); let invalid_nonconfidential_fee_too_little = gen_fee_operation( Some(TX_FEE_MIN - 1), - Some(ZeiAssetType([0; ASSET_TYPE_LENGTH])), - *BLACK_HOLE_PUBKEY, + Some(NoahAssetType([0; ASSET_TYPE_LENGTH])), + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), ); let invalid_destination_not_black_hole = gen_fee_operation( Some(TX_FEE_MIN), - Some(ZeiAssetType([0; ASSET_TYPE_LENGTH])), - XfrPublicKey::zei_from_bytes(&[9; ed25519_dalek::PUBLIC_KEY_LENGTH][..]) + Some(NoahAssetType([0; ASSET_TYPE_LENGTH])), + XfrPublicKey::noah_from_bytes(&[9; ed25519_dalek::PUBLIC_KEY_LENGTH][..]) .unwrap(), ); let valid = gen_fee_operation( Some(TX_FEE_MIN), - Some(ZeiAssetType([0; ASSET_TYPE_LENGTH])), - *BLACK_HOLE_PUBKEY, + Some(NoahAssetType([0; ASSET_TYPE_LENGTH])), + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), ); let valid2 = gen_fee_operation( Some(TX_FEE_MIN + 999), - Some(ZeiAssetType([0; ASSET_TYPE_LENGTH])), - *BLACK_HOLE_PUBKEY, + Some(NoahAssetType([0; ASSET_TYPE_LENGTH])), + XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY), ); // tx.add_operation(invalid_confidential_type.clone()); diff --git a/src/ledger/src/staking/cosig.rs b/src/ledger/src/staking/cosig.rs index f96b8c4d9..1d2cc50eb 100644 --- a/src/ledger/src/staking/cosig.rs +++ b/src/ledger/src/staking/cosig.rs @@ -17,7 +17,7 @@ use { collections::BTreeMap, fmt::{self, Debug}, }, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey, XfrSignature}, + zei::{XfrKeyPair, XfrPublicKey, XfrSignature}, }; /// A common structure for data with co-signatures. @@ -53,7 +53,7 @@ where .c(d!()) .map(|msg| { let k = kp.get_pk(); - let v = CoSig::new(kp.get_pk(), kp.sign(&msg)); + let v = CoSig::new(kp.get_pk(), kp.sign(&msg).unwrap()); self.cosigs.insert(k, v); }) } @@ -64,7 +64,7 @@ where let msg = bincode::serialize(&(self.nonce, &self.data)).c(d!())?; kps.iter().for_each(|kp| { let k = kp.get_pk(); - let v = CoSig::new(kp.get_pk(), kp.sign(&msg)); + let v = CoSig::new(kp.get_pk(), kp.sign(&msg).unwrap()); self.cosigs.insert(k, v); }); Ok(()) diff --git a/src/ledger/src/staking/evm.rs b/src/ledger/src/staking/evm.rs index dd048d4fa..f6d5e8560 100644 --- a/src/ledger/src/staking/evm.rs +++ b/src/ledger/src/staking/evm.rs @@ -6,7 +6,7 @@ use once_cell::sync::{Lazy, OnceCell}; use parking_lot::{Mutex, RwLock}; use ruc::Result; use std::{collections::BTreeMap, sync::Arc}; -use zei::xfr::sig::XfrPublicKey; +use zei::XfrPublicKey; ///EVM staking interface pub static EVM_STAKING: OnceCell>> = OnceCell::new(); diff --git a/src/ledger/src/staking/mod.rs b/src/ledger/src/staking/mod.rs index 3ec4585d3..60633a796 100644 --- a/src/ledger/src/staking/mod.rs +++ b/src/ledger/src/staking/mod.rs @@ -51,7 +51,8 @@ use { Arc, }, }, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey}, + zei::noah_api::keys::PublicKey as NoahXfrPublicKey, + zei::{XfrKeyPair, XfrPublicKey}, }; // height, reward rate @@ -80,14 +81,14 @@ lazy_static! { pub static ref KEEP_HIST: bool = env::var("FINDORAD_KEEP_HIST").is_ok(); /// Reserved accounts of EcoSystem. - pub static ref FF_PK_LIST: Vec = FF_ADDR_LIST + pub static ref FF_PK_LIST: Vec = FF_ADDR_LIST .iter() - .map(|addr| pnk!(wallet::public_key_from_bech32(addr))) + .map(|addr| pnk!(wallet::public_key_from_bech32(addr)).into_noah()) .collect(); /// Reserved accounts of Findora Foundation. - pub static ref FF_PK_EXTRA_120_0000: XfrPublicKey = - pnk!(wallet::public_key_from_bech32(FF_ADDR_EXTRA_120_0000)); + pub static ref FF_PK_EXTRA_120_0000: NoahXfrPublicKey = + pnk!(wallet::public_key_from_bech32(FF_ADDR_EXTRA_120_0000)).into_noah(); #[allow(missing_docs)] pub static ref CHAN_GLOB_RATE_HIST: GRHCP = chan!(); diff --git a/src/ledger/src/staking/ops/claim.rs b/src/ledger/src/staking/ops/claim.rs index bbdd9ce71..5a889b51a 100644 --- a/src/ledger/src/staking/ops/claim.rs +++ b/src/ledger/src/staking/ops/claim.rs @@ -12,7 +12,7 @@ use { config::abci::global_cfg::CFG, ruc::*, serde::{Deserialize, Serialize}, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey, XfrSignature}, + zei::{XfrKeyPair, XfrPublicKey, XfrSignature}, }; /// Used as the inner object of a `Claim Operation`. @@ -81,7 +81,7 @@ impl ClaimOps { nonce: NoReplayToken, ) -> Self { let body = Data::new(amount, nonce); - let signature = keypair.sign(&body.to_bytes()); + let signature = keypair.sign(&body.to_bytes()).unwrap(); ClaimOps { body, pubkey: keypair.get_pk(), diff --git a/src/ledger/src/staking/ops/delegation.rs b/src/ledger/src/staking/ops/delegation.rs index 528a5eaaf..c0af11244 100644 --- a/src/ledger/src/staking/ops/delegation.rs +++ b/src/ledger/src/staking/ops/delegation.rs @@ -21,9 +21,9 @@ use { serde::{Deserialize, Serialize}, std::collections::HashSet, tendermint::{signature::Ed25519Signature, PrivateKey, PublicKey, Signature}, - zei::xfr::{ - sig::{XfrKeyPair, XfrPublicKey, XfrSignature}, - structs::{XfrAmount, XfrAssetType}, + zei::{ + noah_api::xfr::structs::{XfrAmount, XfrAssetType}, + {XfrKeyPair, XfrPublicKey, XfrSignature}, }, }; @@ -148,7 +148,7 @@ impl DelegationOps { nonce: NoReplayToken, ) -> Self { let body = Box::new(Data::new(validator, new_validator, amount, nonce)); - let signature = keypair.sign(&body.to_bytes()); + let signature = keypair.sign(&body.to_bytes()).unwrap(); let v_signature: Option = vltor_key .and_then(|pk| pk.ed25519_keypair().map(|k| k.sign(&body.to_bytes()))); DelegationOps { @@ -243,7 +243,7 @@ fn check_delegation_context_principal( tx: &Transaction, owner: (XfrPublicKey, Amount), ) -> Result { - let target_pk = *BLACK_HOLE_PUBKEY_STAKING; + let target_pk = XfrPublicKey::from_noah(&BLACK_HOLE_PUBKEY_STAKING); let am = tx .body diff --git a/src/ledger/src/staking/ops/fra_distribution.rs b/src/ledger/src/staking/ops/fra_distribution.rs index e82d401c9..2e517222f 100644 --- a/src/ledger/src/staking/ops/fra_distribution.rs +++ b/src/ledger/src/staking/ops/fra_distribution.rs @@ -14,7 +14,7 @@ use { ruc::*, serde::{Deserialize, Serialize}, std::collections::BTreeMap, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey}, + zei::{XfrKeyPair, XfrPublicKey}, }; /// Used as the inner object of a `FraDistribution Operation`. diff --git a/src/ledger/src/staking/ops/governance.rs b/src/ledger/src/staking/ops/governance.rs index e5967586d..9b301aed7 100644 --- a/src/ledger/src/staking/ops/governance.rs +++ b/src/ledger/src/staking/ops/governance.rs @@ -16,7 +16,7 @@ use { ruc::*, serde::{Deserialize, Serialize}, std::collections::BTreeMap, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey}, + zei::{XfrKeyPair, XfrPublicKey}, }; lazy_static! { diff --git a/src/ledger/src/staking/ops/mint_fra.rs b/src/ledger/src/staking/ops/mint_fra.rs index 2738f3ff1..33c86e2a3 100644 --- a/src/ledger/src/staking/ops/mint_fra.rs +++ b/src/ledger/src/staking/ops/mint_fra.rs @@ -14,12 +14,12 @@ use { rand_core::SeedableRng, serde::{Deserialize, Serialize}, zei::{ - setup::PublicParams, - xfr::{ + noah_algebra::ristretto::PedersenCommitmentRistretto, + noah_api::xfr::{ asset_record::{build_blind_asset_record, AssetRecordType}, - sig::XfrPublicKey, - structs::{AssetRecordTemplate, AssetType, OwnerMemo}, + structs::{AssetRecordTemplate, AssetType}, }, + BlindAssetRecord, OwnerMemo, XfrPublicKey, }, }; @@ -78,14 +78,14 @@ impl MintEntry { amount, asset_type, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - receiver_pk.unwrap_or(target_pk), + receiver_pk.unwrap_or(target_pk).into_noah(), ); - let pc_gens = PublicParams::default().pc_gens; + let pc_gens = PedersenCommitmentRistretto::default(); let (ba, _, _) = build_blind_asset_record(&mut prng, &pc_gens, &ar, vec![]); let utxo = TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }; diff --git a/src/ledger/src/staking/ops/replace_staker.rs b/src/ledger/src/staking/ops/replace_staker.rs index b88b3b44b..b668074f5 100644 --- a/src/ledger/src/staking/ops/replace_staker.rs +++ b/src/ledger/src/staking/ops/replace_staker.rs @@ -12,7 +12,7 @@ use { fp_types::H160, ruc::*, serde::{Deserialize, Serialize}, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey, XfrSignature}, + zei::{XfrKeyPair, XfrPublicKey, XfrSignature}, }; /// Used for `Staker Replace Operation`. @@ -39,7 +39,7 @@ impl ReplaceStakerOps { nonce, }; - let signature = keypair.sign(&body.to_bytes()); + let signature = keypair.sign(&body.to_bytes()).unwrap(); ReplaceStakerOps { body, diff --git a/src/ledger/src/staking/ops/undelegation.rs b/src/ledger/src/staking/ops/undelegation.rs index 9ccd6c1ea..414dee9fd 100644 --- a/src/ledger/src/staking/ops/undelegation.rs +++ b/src/ledger/src/staking/ops/undelegation.rs @@ -12,7 +12,7 @@ use { config::abci::global_cfg::CFG, ruc::*, serde::{Deserialize, Serialize}, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey, XfrSignature}, + zei::{XfrKeyPair, XfrPublicKey, XfrSignature}, }; /// Used as the inner object of a `UnDelegation Operation`. @@ -82,7 +82,7 @@ impl UnDelegationOps { pu: Option, ) -> Self { let body = Data::new(nonce, pu); - let signature = keypair.sign(&body.to_bytes()); + let signature = keypair.sign(&body.to_bytes()).unwrap(); UnDelegationOps { body, pubkey: keypair.get_pk(), diff --git a/src/ledger/src/staking/ops/update_staker.rs b/src/ledger/src/staking/ops/update_staker.rs index b64d7a1d5..f5ab2798e 100644 --- a/src/ledger/src/staking/ops/update_staker.rs +++ b/src/ledger/src/staking/ops/update_staker.rs @@ -16,7 +16,7 @@ use { ruc::*, serde::{Deserialize, Serialize}, tendermint::{signature::Ed25519Signature, PrivateKey, PublicKey, Signature}, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey, XfrSignature}, + zei::{XfrKeyPair, XfrPublicKey, XfrSignature}, }; /// Used as the inner object of a `Staker Update Operation`. @@ -105,7 +105,7 @@ impl UpdateStakerOps { nonce: NoReplayToken, ) -> Self { let body = Box::new(Data::new(validator, new_validator, nonce)); - let signature = keypair.sign(&body.to_bytes()); + let signature = keypair.sign(&body.to_bytes()).unwrap(); let v_signature: Option = vltor_key .ed25519_keypair() .map(|k| k.sign(&body.to_bytes())); diff --git a/src/ledger/src/staking/ops/update_validator.rs b/src/ledger/src/staking/ops/update_validator.rs index ddac83a82..576ef22c7 100644 --- a/src/ledger/src/staking/ops/update_validator.rs +++ b/src/ledger/src/staking/ops/update_validator.rs @@ -14,7 +14,7 @@ use { }, }, ruc::*, - zei::xfr::sig::{XfrKeyPair, XfrPublicKey}, + zei::{XfrKeyPair, XfrPublicKey}, }; /// Used as the inner object of a `UpdateValidator Operation`. diff --git a/src/ledger/src/store/api_cache.rs b/src/ledger/src/store/api_cache.rs index 465613efd..2479cbb59 100644 --- a/src/ledger/src/store/api_cache.rs +++ b/src/ledger/src/store/api_cache.rs @@ -6,7 +6,6 @@ use { data_model::{ AssetTypeCode, AssetTypePrefix, DefineAsset, IssueAsset, IssuerPublicKey, Operation, Transaction, TxOutput, TxnIDHash, TxnSID, TxoSID, XfrAddress, - ASSET_TYPE_FRA, }, staking::{ ops::mint_fra::MintEntry, Amount, BlockHeight, DelegationRwdDetail, @@ -20,7 +19,7 @@ use { ruc::*, serde::{Deserialize, Serialize}, std::collections::HashSet, - zei::xfr::{sig::XfrPublicKey, structs::OwnerMemo}, + zei::{OwnerMemo, XfrPublicKey}, }; type Issuances = Vec<(TxOutput, Option)>; @@ -115,16 +114,14 @@ impl ApiCache { #[inline(always)] pub fn add_created_asset(&mut self, creation: &DefineAsset, cur_height: u64) { let asset_code = creation.body.asset.code; - let code = if asset_code.val == ASSET_TYPE_FRA - || CFG.checkpoint.utxo_asset_prefix_height > cur_height - { - creation.body.asset.code - } else { - AssetTypeCode::from_prefix_and_raw_asset_type_code( - AssetTypePrefix::UserDefined, - &creation.body.asset.code, - ) - }; + + let code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &asset_code, + &CFG.checkpoint, + cur_height, + ); + let prefix = self.prefix.clone(); let issuer = creation.pubkey; let mut tmp = creation.clone(); diff --git a/src/ledger/src/store/helpers.rs b/src/ledger/src/store/helpers.rs index 8f6a3cf6b..0ba1d196f 100644 --- a/src/ledger/src/store/helpers.rs +++ b/src/ledger/src/store/helpers.rs @@ -8,23 +8,22 @@ use { TransferType, XfrNotePolicies, }, crate::data_model::{ - Asset, AssetRules, AssetTypeCode, AssetTypePrefix, ConfidentialMemo, - DefineAsset, DefineAssetBody, IssueAsset, IssueAssetBody, Memo, Operation, - Transaction, TransferAsset, TransferAssetBody, TxOutput, TxnEffect, TxnSID, - TxoRef, TxoSID, ASSET_TYPE_FRA, + Asset, AssetRules, AssetTypeCode, ConfidentialMemo, DefineAsset, + DefineAssetBody, IssueAsset, IssueAssetBody, Memo, Operation, Transaction, + TransferAsset, TransferAssetBody, TxOutput, TxnEffect, TxnSID, TxoRef, TxoSID, }, globutils::SignatureOf, rand_core::{CryptoRng, RngCore}, ruc::*, std::fmt::Debug, zei::{ - setup::PublicParams, - xfr::{ + noah_algebra::ristretto::PedersenCommitmentRistretto, + noah_api::xfr::{ asset_record::AssetRecordType, asset_record::{build_blind_asset_record, open_blind_asset_record}, - sig::{XfrKeyPair, XfrPublicKey}, structs::{AssetRecord, AssetRecordTemplate}, }, + BlindAssetRecord, XfrKeyPair, XfrPublicKey, }, }; @@ -35,7 +34,7 @@ pub fn create_definition_transaction( asset_rules: AssetRules, memo: Option, seq_id: u64, -) -> Result<(Transaction, AssetTypeCode)> { +) -> Result { let issuer_key = IssuerPublicKey { key: *keypair.get_pk_ref(), }; @@ -44,18 +43,9 @@ pub fn create_definition_transaction( let asset_create = DefineAsset::new(asset_body, &IssuerKeyPair { keypair: &keypair }).c(d!())?; - let code = if code.val == ASSET_TYPE_FRA { - *code - } else { - AssetTypeCode::from_prefix_and_raw_asset_type_code( - AssetTypePrefix::UserDefined, - &code, - ) - }; - - Ok(( - Transaction::from_operation(Operation::DefineAsset(asset_create), seq_id), - code, + Ok(Transaction::from_operation( + Operation::DefineAsset(asset_create), + seq_id, )) } @@ -72,12 +62,7 @@ pub fn asset_creation_body( asset_rules: AssetRules, memo: Option, confidential_memo: Option, -) -> (DefineAssetBody, AssetTypeCode) { - let new_token_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( - AssetTypePrefix::UserDefined, - token_code, - ); - +) -> DefineAssetBody { let mut token = Asset { code: *token_code, issuer: IssuerPublicKey { key: *issuer_key }, @@ -97,12 +82,9 @@ pub fn asset_creation_body( token.confidential_memo = ConfidentialMemo {}; } - ( - DefineAssetBody { - asset: Box::new(token), - }, - new_token_code, - ) + DefineAssetBody { + asset: Box::new(token), + } } #[allow(missing_docs)] @@ -148,7 +130,6 @@ pub fn apply_transaction( #[allow(missing_docs)] pub fn create_issue_and_transfer_txn( ledger: &mut LedgerState, - params: &PublicParams, code: &AssetTypeCode, amount: u64, issuer_keys: &XfrKeyPair, @@ -160,14 +141,11 @@ pub fn create_issue_and_transfer_txn( amount, code.val, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - issuer_keys.get_pk(), - ); - let (ba, _tracer_memo, owner_memo) = build_blind_asset_record( - &mut ledger.get_prng(), - ¶ms.pc_gens, - &ar_template, - vec![], + issuer_keys.get_pk().into_noah(), ); + let pc_gens = PedersenCommitmentRistretto::default(); + let (ba, _tracer_memo, owner_memo) = + build_blind_asset_record(&mut ledger.get_prng(), &pc_gens, &ar_template, vec![]); let asset_issuance_body = IssueAssetBody::new( &code, @@ -175,7 +153,7 @@ pub fn create_issue_and_transfer_txn( &[( TxOutput { id: None, - record: ba.clone(), + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None, @@ -197,7 +175,7 @@ pub fn create_issue_and_transfer_txn( amount, code.val, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - *recipient_pk, + recipient_pk.into_noah(), ); let ar = AssetRecord::from_template_no_identity_tracing( &mut ledger.get_prng(), @@ -208,7 +186,7 @@ pub fn create_issue_and_transfer_txn( &mut ledger.get_prng(), vec![TxoRef::Relative(0)], &[AssetRecord::from_open_asset_record_no_asset_tracing( - open_blind_asset_record(&ba, &owner_memo, &issuer_keys).unwrap() + open_blind_asset_record(&ba, &owner_memo, &issuer_keys.into_noah()).unwrap() )], &[ar.clone()], None, @@ -227,7 +205,6 @@ pub fn create_issue_and_transfer_txn( #[allow(missing_docs)] pub fn create_issue_and_transfer_txn_with_asset_tracing( ledger: &mut LedgerState, - params: &PublicParams, code: &AssetTypeCode, amount: u64, issuer_keys: &XfrKeyPair, @@ -247,12 +224,13 @@ pub fn create_issue_and_transfer_txn_with_asset_tracing( amount, code.val, AssetRecordType::ConfidentialAmount_NonConfidentialAssetType, - issuer_keys.get_pk(), + issuer_keys.get_pk().into_noah(), tracing_policies.clone(), ); + let pc_gens = PedersenCommitmentRistretto::default(); let (ba, _tracer_memo, owner_memo) = build_blind_asset_record( &mut ledger.get_prng(), - ¶ms.pc_gens, + &pc_gens, &ar_template, vec![vec![]], ); @@ -263,7 +241,7 @@ pub fn create_issue_and_transfer_txn_with_asset_tracing( &[( TxOutput { id: None, - record: ba.clone(), + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None, @@ -285,7 +263,7 @@ pub fn create_issue_and_transfer_txn_with_asset_tracing( amount, code.val, AssetRecordType::ConfidentialAmount_NonConfidentialAssetType, - *recipient_pk, + recipient_pk.into_noah(), tracing_policies.clone(), ); let ar = AssetRecord::from_template_no_identity_tracing( @@ -295,7 +273,7 @@ pub fn create_issue_and_transfer_txn_with_asset_tracing( .unwrap(); let tar = AssetRecord::from_open_asset_record_with_asset_tracing_but_no_identity( &mut ledger.get_prng(), - open_blind_asset_record(&ba, &owner_memo, &issuer_keys).unwrap(), + open_blind_asset_record(&ba, &owner_memo, &issuer_keys.into_noah()).unwrap(), tracing_policies, ) .unwrap(); @@ -324,7 +302,6 @@ pub fn create_issue_and_transfer_txn_with_asset_tracing( #[allow(missing_docs)] pub fn create_issuance_txn( ledger: &mut LedgerState, - params: &PublicParams, code: &AssetTypeCode, amount: u64, seq_num: u64, @@ -336,14 +313,11 @@ pub fn create_issuance_txn( amount, code.val, record_type, - issuer_keys.get_pk(), - ); - let (ba, _tracer_memo, _owner_memo) = build_blind_asset_record( - &mut ledger.get_prng(), - ¶ms.pc_gens, - &ar_template, - vec![], + issuer_keys.get_pk().into_noah(), ); + let pc_gens = PedersenCommitmentRistretto::default(); + let (ba, _tracer_memo, _owner_memo) = + build_blind_asset_record(&mut ledger.get_prng(), &pc_gens, &ar_template, vec![]); let asset_issuance_body = IssueAssetBody::new( &code, @@ -351,7 +325,7 @@ pub fn create_issuance_txn( &[( TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None, diff --git a/src/ledger/src/store/mod.rs b/src/ledger/src/store/mod.rs index df4ffae74..c9ccf6660 100644 --- a/src/ledger/src/store/mod.rs +++ b/src/ledger/src/store/mod.rs @@ -17,7 +17,7 @@ use { BlockEffect, BlockSID, FinalizedBlock, FinalizedTransaction, IssuerKeyPair, IssuerPublicKey, OutputPosition, StateCommitmentData, Transaction, TransferType, TxnEffect, TxnSID, TxnTempSID, TxoSID, UnAuthenticatedUtxo, - Utxo, UtxoStatus, ASSET_TYPE_FRA, BLACK_HOLE_PUBKEY, + Utxo, UtxoStatus, BLACK_HOLE_PUBKEY, }, staking::{ Amount, Power, Staking, TendermintAddrRef, FF_PK_EXTRA_120_0000, FF_PK_LIST, @@ -47,10 +47,12 @@ use { ops::{Deref, DerefMut}, sync::Arc, }, - zei::xfr::{ - lib::XfrNotePolicies, - sig::XfrPublicKey, - structs::{OwnerMemo, TracingPolicies, TracingPolicy}, + zei::{ + noah_api::xfr::{ + structs::{TracingPolicies, TracingPolicy}, + XfrNotePolicies, + }, + OwnerMemo, XfrPublicKey, }, }; @@ -617,7 +619,12 @@ impl LedgerState { - FF_PK_LIST .iter() .chain(extras.iter()) - .map(|pk| self.staking_get_nonconfidential_balance(pk).unwrap_or(0)) + .map(|pk| { + self.staking_get_nonconfidential_balance(&XfrPublicKey::from_noah( + &pk, + )) + .unwrap_or(0) + }) .sum::() - s.coinbase_balance() } @@ -1330,17 +1337,13 @@ impl LedgerStatus { // This drains every field of `block` except `txns` and `temp_sids`. fn apply_block_effects(&mut self, block: &mut BlockEffect) -> (TmpSidMap, u64, u64) { let base_sid = self.next_txo.0; - let handle_asset_type_code = |code: AssetTypeCode| -> AssetTypeCode { - if CFG.checkpoint.utxo_asset_prefix_height > self.td_commit_height - || code.val == ASSET_TYPE_FRA - { - code - } else { - AssetTypeCode::from_prefix_and_raw_asset_type_code( - AssetTypePrefix::UserDefined, - &code, - ) - } + let handle_asset_type_code = |code: AssetTypeCode| { + AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &code, + &CFG.checkpoint, + self.td_commit_height, + ) }; for no_replay_token in block.no_replay_tokens.iter() { let (rand, seq_id) = ( diff --git a/src/ledger/src/store/test.rs b/src/ledger/src/store/test.rs index b6cb5cb56..064b322ac 100644 --- a/src/ledger/src/store/test.rs +++ b/src/ledger/src/store/test.rs @@ -10,14 +10,14 @@ use { }, rand_core::SeedableRng, zei::{ - setup::PublicParams, - xfr::{ + noah_algebra::ristretto::PedersenCommitmentRistretto, + noah_api::xfr::{ asset_record::{ build_blind_asset_record, open_blind_asset_record, AssetRecordType, }, - sig::XfrKeyPair, structs::{AssetRecord, AssetRecordTemplate}, }, + BlindAssetRecord, XfrKeyPair, }, }; @@ -85,16 +85,19 @@ fn test_asset_creation_valid() { let keypair = build_keys(&mut prng); let code = AssetTypeCode::gen_random(); - let (asset_body, mut token_code) = asset_creation_body( + let asset_body = asset_creation_body( &code, keypair.get_pk_ref(), AssetRules::default(), None, None, ); - if CFG.checkpoint.utxo_asset_prefix_height > state.get_tendermint_height() { - token_code = code; - } + let token_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &code, + &CFG.checkpoint, + state.get_tendermint_height(), + ); let asset_create = asset_creation_operation(&asset_body, &keypair); let seq_id = state.get_block_commit_count(); let tx = Transaction::from_operation(Operation::DefineAsset(asset_create), seq_id); @@ -121,7 +124,7 @@ fn test_asset_creation_invalid_public_key() { // Create a valid asset creation operation. let mut prng = ChaChaRng::from_entropy(); let keypair = build_keys(&mut prng); - let (asset_body, _) = asset_creation_body( + let asset_body = asset_creation_body( &AssetTypeCode::gen_random(), keypair.get_pk_ref(), AssetRules::default(), @@ -143,14 +146,13 @@ fn test_asset_creation_invalid_public_key() { #[test] fn test_asset_transfer() { let mut ledger = LedgerState::tmp_ledger(); - let params = PublicParams::default(); let code = AssetTypeCode::gen_random(); let mut prng = ChaChaRng::from_entropy(); let key_pair = XfrKeyPair::generate(&mut prng); let key_pair_adversary = XfrKeyPair::generate(&mut ledger.get_prng()); - let (tx, mut new_code) = create_definition_transaction( + let tx = create_definition_transaction( &code, &key_pair, AssetRules::default(), @@ -158,9 +160,12 @@ fn test_asset_transfer() { ledger.get_block_commit_count(), ) .unwrap(); - if CFG.checkpoint.utxo_asset_prefix_height > ledger.get_tendermint_height() { - new_code = code; - } + let new_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &code, + &CFG.checkpoint, + ledger.get_tendermint_height(), + ); let effect = TxnEffect::compute_effect(tx).unwrap(); { let mut block = ledger.start_block().unwrap(); @@ -174,15 +179,15 @@ fn test_asset_transfer() { 100, new_code.val, art, - key_pair.get_pk(), + key_pair.get_pk().into_noah(), ); + let pc_gens = PedersenCommitmentRistretto::default(); let (ba, _, _) = build_blind_asset_record( &mut ledger.get_prng(), - ¶ms.pc_gens, + &pc_gens, &template, vec![], ); - let second_ba = ba.clone(); let asset_issuance_body = IssueAssetBody::new( &new_code, @@ -191,7 +196,7 @@ fn test_asset_transfer() { ( TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None, @@ -199,7 +204,7 @@ fn test_asset_transfer() { ( TxOutput { id: None, - record: second_ba, + record: BlindAssetRecord::from_noah(&ba.clone()), lien: None, }, None, @@ -242,14 +247,16 @@ fn test_asset_transfer() { // Construct transfer operation let input_bar_proof = ledger.get_utxo(txo_sid).unwrap(); let input_bar = (input_bar_proof.clone().utxo.0).record; - let input_oar = open_blind_asset_record(&input_bar, &None, &key_pair).unwrap(); + let input_oar = + open_blind_asset_record(&input_bar.into_noah(), &None, &key_pair.into_noah()) + .unwrap(); assert!(input_bar_proof.is_valid(state_commitment)); let output_template = AssetRecordTemplate::with_no_asset_tracing( 100, new_code.val, art, - key_pair_adversary.get_pk(), + key_pair_adversary.get_pk().into_noah(), ); let output_ar = AssetRecord::from_template_no_identity_tracing( &mut ledger.get_prng(), @@ -317,7 +324,7 @@ fn test_asset_creation_invalid_signature() { let mut prng = ChaChaRng::from_entropy(); let keypair1 = build_keys(&mut prng); - let (asset_body, _) = asset_creation_body( + let asset_body = asset_creation_body( &AssetTypeCode::gen_random(), keypair1.get_pk_ref(), AssetRules::default(), @@ -340,13 +347,11 @@ fn test_asset_creation_invalid_signature() { fn asset_issued() { let mut ledger = LedgerState::tmp_ledger(); - let params = PublicParams::default(); - assert!(ledger.get_state_commitment() == (HashOf::new(&None), 0)); let token_code = AssetTypeCode::gen_random(); let keypair = build_keys(&mut ledger.get_prng()); let seq_id = ledger.get_block_commit_count(); - let (tx, mut new_token_code) = create_definition_transaction( + let tx = create_definition_transaction( &token_code, &keypair, AssetRules::default(), @@ -355,9 +360,12 @@ fn asset_issued() { ) .unwrap(); - if CFG.checkpoint.utxo_asset_prefix_height > ledger.get_tendermint_height() { - new_token_code = token_code; - } + let new_token_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &token_code, + &CFG.checkpoint, + ledger.get_tendermint_height(), + ); let effect = TxnEffect::compute_effect(tx).unwrap(); { @@ -371,18 +379,19 @@ fn asset_issued() { 100, new_token_code.val, art, - *keypair.get_pk_ref(), + keypair.get_pk_ref().into_noah(), ); + let pc_gens = PedersenCommitmentRistretto::default(); let (ba, _, _) = - build_blind_asset_record(&mut ledger.get_prng(), ¶ms.pc_gens, &ar, vec![]); + build_blind_asset_record(&mut ledger.get_prng(), &pc_gens, &ar, vec![]); let asset_issuance_body = IssueAssetBody::new( &new_token_code, 0, &[( TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None, @@ -476,7 +485,6 @@ fn asset_issued() { #[test] pub fn test_transferable() { let mut ledger = LedgerState::tmp_ledger(); - let params = PublicParams::default(); let issuer = XfrKeyPair::generate(&mut ledger.get_prng()); let alice = XfrKeyPair::generate(&mut ledger.get_prng()); let bob = XfrKeyPair::generate(&mut ledger.get_prng()); @@ -484,7 +492,7 @@ pub fn test_transferable() { // Define fiat token let code = AssetTypeCode::gen_random(); let seq_id = ledger.get_block_commit_count(); - let (tx, mut new_code) = create_definition_transaction( + let tx = create_definition_transaction( &code, &issuer, AssetRules::default().set_transferable(false).clone(), @@ -492,13 +500,16 @@ pub fn test_transferable() { seq_id, ) .unwrap(); - if CFG.checkpoint.utxo_asset_prefix_height > ledger.get_tendermint_height() { - new_code = code; - } + let new_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &code, + &CFG.checkpoint, + ledger.get_tendermint_height(), + ); + apply_transaction(&mut ledger, tx); let (tx, _) = create_issue_and_transfer_txn( &mut ledger, - ¶ms, &new_code, 100, &issuer, @@ -514,7 +525,7 @@ pub fn test_transferable() { 100, new_code.val, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let record = AssetRecord::from_template_no_identity_tracing( &mut ledger.get_prng(), @@ -528,7 +539,8 @@ pub fn test_transferable() { &mut ledger.get_prng(), vec![TxoRef::Absolute(sid)], &[AssetRecord::from_open_asset_record_no_asset_tracing( - open_blind_asset_record(&bar, &None, &alice).unwrap(), + open_blind_asset_record(&bar.into_noah(), &None, &alice.into_noah()) + .unwrap(), )], &[record], None, @@ -551,7 +563,7 @@ pub fn test_transferable() { 100, new_code.val, AssetRecordType::ConfidentialAmount_ConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let record = AssetRecord::from_template_no_identity_tracing( &mut ledger.get_prng(), @@ -565,7 +577,8 @@ pub fn test_transferable() { &mut ledger.get_prng(), vec![TxoRef::Absolute(sid)], &[AssetRecord::from_open_asset_record_no_asset_tracing( - open_blind_asset_record(&bar, &None, &alice).unwrap(), + open_blind_asset_record(&bar.into_noah(), &None, &alice.into_noah()) + .unwrap(), )], &[record], None, @@ -589,7 +602,7 @@ pub fn test_transferable() { 100, new_code.val, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - bob.get_pk(), + bob.get_pk().into_noah(), ); let second_record = AssetRecord::from_template_no_identity_tracing( &mut ledger.get_prng(), @@ -598,7 +611,6 @@ pub fn test_transferable() { .unwrap(); let (mut tx, ar) = create_issue_and_transfer_txn( &mut ledger, - ¶ms, &new_code, 100, &issuer, @@ -630,14 +642,13 @@ pub fn test_transferable() { #[test] pub fn test_max_units() { let mut ledger = LedgerState::tmp_ledger(); - let params = PublicParams::default(); let issuer = XfrKeyPair::generate(&mut ledger.get_prng()); // Define fiat token let code = AssetTypeCode::gen_random(); let seq_id = ledger.get_block_commit_count(); - let (tx, mut new_code) = create_definition_transaction( + let tx = create_definition_transaction( &code, &issuer, AssetRules::default().set_max_units(Some(100)).clone(), @@ -645,13 +656,16 @@ pub fn test_max_units() { seq_id, ) .unwrap(); - if CFG.checkpoint.utxo_asset_prefix_height > ledger.get_tendermint_height() { - new_code = code; - } + let new_code = AssetTypeCode::from_prefix_and_raw_asset_type_code( + AssetTypePrefix::UserDefined, + &code, + &CFG.checkpoint, + ledger.get_tendermint_height(), + ); + apply_transaction(&mut ledger, tx); let tx = create_issuance_txn( &mut ledger, - ¶ms, &new_code, 50, 0, @@ -663,7 +677,6 @@ pub fn test_max_units() { // Ensure that a single overlfowing transaction fails let tx = create_issuance_txn( &mut ledger, - ¶ms, &new_code, 51, 1, @@ -679,7 +692,6 @@ pub fn test_max_units() { // Ensure that cap can be reached let tx = create_issuance_txn( &mut ledger, - ¶ms, &new_code, 50, 1, @@ -693,7 +705,6 @@ pub fn test_max_units() { // Cant try to exceed asset cap by issuing confidentially let tx = create_issuance_txn( &mut ledger, - ¶ms, &new_code, 1, 2, @@ -718,13 +729,18 @@ fn gen_fee_operation( let input_bar_proof = l.get_utxo_light(txo_sid).unwrap(); let input_bar = (input_bar_proof.utxo.0).record; - let input_oar = open_blind_asset_record(&input_bar, &None, &fra_owner_kp).unwrap(); + let input_oar = open_blind_asset_record( + &input_bar.into_noah(), + &None, + &fra_owner_kp.into_noah(), + ) + .unwrap(); let output_template = AssetRecordTemplate::with_no_asset_tracing( input_oar.amount - TX_FEE_MIN, fra_code.val, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - fra_owner_kp.get_pk(), + fra_owner_kp.get_pk().into_noah(), ); let output_ar = AssetRecord::from_template_no_identity_tracing( &mut l.get_prng(), diff --git a/src/ledger/src/store/utils.rs b/src/ledger/src/store/utils.rs index a7a1ed4ef..d1496c472 100644 --- a/src/ledger/src/store/utils.rs +++ b/src/ledger/src/store/utils.rs @@ -15,12 +15,12 @@ use { rand_core::SeedableRng, ruc::*, zei::{ - setup::PublicParams, - xfr::{ + noah_algebra::ristretto::PedersenCommitmentRistretto, + noah_api::xfr::{ asset_record::{build_blind_asset_record, AssetRecordType}, - sig::XfrKeyPair, structs::AssetRecordTemplate, }, + BlindAssetRecord, XfrKeyPair, }, }; @@ -35,7 +35,7 @@ pub fn fra_gen_initial_tx(fra_owner_kp: &XfrKeyPair) -> Transaction { val: ASSET_TYPE_FRA, }; - let (mut tx, _) = pnk!(helpers::create_definition_transaction( + let mut tx = pnk!(helpers::create_definition_transaction( &fra_code, fra_owner_kp, AssetRules { @@ -55,23 +55,23 @@ pub fn fra_gen_initial_tx(fra_owner_kp: &XfrKeyPair) -> Transaction { FRA_PRE_ISSUE_AMOUNT / 2, fra_code.val, AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType, - fra_owner_kp.get_pk(), + fra_owner_kp.get_pk().into_noah(), ); - let params = PublicParams::default(); + let pc_gens = PedersenCommitmentRistretto::default(); let outputs = (0..2) .map(|_| { let (ba, _, _) = build_blind_asset_record( &mut ChaChaRng::from_entropy(), - ¶ms.pc_gens, + &pc_gens, &template, vec![], ); ( TxOutput { id: None, - record: ba, + record: BlindAssetRecord::from_noah(&ba), lien: None, }, None,