Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Abar to bar integration #213

Merged
merged 10 commits into from
Mar 2, 2022
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,7 @@ ark-ff = { git = "https://github.com/FindoraNetwork/ark-algebra" }
ark-serialize = { git = "https://github.com/FindoraNetwork/ark-algebra" }
ark-std = { git = "https://github.com/FindoraNetwork/ark-std" }
ark-bls12-381 = { git = "https://github.com/FindoraNetwork/ark-curves" }
ark-ed-on-bls12-381 = { git = "https://github.com/FindoraNetwork/ark-curves" }
ark-ed-on-bls12-381 = { git = "https://github.com/FindoraNetwork/ark-curves" }
# Stopgap, remove when https://github.com/rust-rocksdb/rust-rocksdb/issues/602 is fixed
rocksdb = { git = "https://github.com/rust-rocksdb/rust-rocksdb/", rev="626ff7e79dca107f76e347c3e1ea9cdabbd9d679" }
librocksdb-sys = { git = "https://github.com/rust-rocksdb/rust-rocksdb/", rev="626ff7e79dca107f76e347c3e1ea9cdabbd9d679" }
1 change: 1 addition & 0 deletions src/components/finutils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ build = "build.rs"
edition = "2021"

[dependencies]
bincode = "1.3.1"
tendermint = "0.19.0"
tokio = "1.10.1"
hex = "0.4.2"
Expand Down
35 changes: 35 additions & 0 deletions src/components/finutils/src/bins/fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,41 @@ fn run() -> Result<()> {
)
.expect("randomizer write failed");
}
} else if let Some(m) = matches.subcommand_matches("convert-abar-to-bar") {
let anon_keys = match m.value_of("anon-keys") {
Some(path) => {
let f =
fs::read_to_string(path).c(d!("Failed to read anon-keys file"))?;
let keys = serde_json::from_str::<AnonKeys>(f.as_str()).c(d!())?;
keys
}
None => return Err(eg!("path for anon-keys file not found")),
};
let axfr_secret_key = anon_keys.axfr_secret_key;
let randomizer = m.value_of("randomizer");
let dec_key = anon_keys.dec_key;
let to_xfr_public_key = m.value_of("to-xfr-public-key");
let fee_xfr_seckey = match m.value_of("fee-xfr-seckey") {
Some(path) => {
Some(fs::read_to_string(path).c(d!("Failed to read seckey file"))?)
}
None => None,
};

if randomizer.is_none() || to_xfr_public_key.is_none() {
println!("{}", m.usage());
} else {
common::convert_abar2bar(
axfr_secret_key,
randomizer.unwrap(),
dec_key,
to_xfr_public_key.unwrap(),
fee_xfr_seckey.as_deref(),
m.is_present("confidential-amount"),
m.is_present("confidential-type"),
)
.c(d!())?;
}
} else if let Some(m) = matches.subcommand_matches("gen-anon-keys") {
let mut prng = ChaChaRng::from_entropy();
let keypair = AXfrKeyPair::generate(&mut prng);
Expand Down
37 changes: 37 additions & 0 deletions src/components/finutils/src/bins/fn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,43 @@ subcommands:
takes_value: true
value_name: TXO SID
required: true
- convert-abar-to-bar:
about: Convert a ABAR to BAR
args:
- anon-keys:
help: Anon keys file path of the sender
short: a
long: anon-keys
takes_value: true
value_name: ANON KEYS PATH
required: true
- randomizer:
help: Randomizer for the input Anon BAR
short: r
long: randomizer
takes_value: true
value_name: RANDOMIZER
required: true
- to-xfr-public-key:
help: Xfr public key of the receiver
short: tp
harshadptl marked this conversation as resolved.
Show resolved Hide resolved
long: to-xfr-public-key
takes_value: true
value_name: XFR PUBLIC KEY
required: true
- fee-xfr-seckey:
help: Xfr secret key for fee payment
short: fxs
long: fee-xfr-seckey
takes_value: true
value_name: XFR SECRET KEY
required: false
- confidential-amount:
help: mask the amount sent on the transaction log
long: confidential-amount
- confidential-type:
help: mask the asset type sent on the transaction log
long: confidential-type
- anon-transfer:
about: Perform Anonymous Transfer
args:
Expand Down
50 changes: 48 additions & 2 deletions src/components/finutils/src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,52 @@ pub fn convert_bar2abar(
Ok(r)
}

/// Convert an ABAR to a BLind Asset Record
pub fn convert_abar2bar(
axfr_secret_key: String,
r: &str,
dec_key: String,
to_xfr_public_key: &str,
fee_xfr_seckey: Option<&str>,
confidential_am: bool,
confidential_ty: bool,
) -> Result<()> {
let from = wallet::anon_secret_key_from_base64(axfr_secret_key.as_str())
.c(d!("invalid 'from-axfr-secret-key'"))?;
let from_secret_key =
wallet::x_secret_key_from_base64(dec_key.as_str()).c(d!("invalid dec_key"))?;
let to = wallet::public_key_from_bech32(to_xfr_public_key)
harshadptl marked this conversation as resolved.
Show resolved Hide resolved
.c(d!("invalid 'to-xfr-public-key'"))?;
let fee_secret_key = restore_keypair_from_str_with_default(fee_xfr_seckey)?;

let r = wallet::randomizer_from_base58(r).c(d!())?;
let randomized_from_pub_key = from.pub_key().randomize(&r);
let axtxo_abar = utils::get_owned_abars(&randomized_from_pub_key).c(d!())?;
let owner_memo = utils::get_abar_memo(&axtxo_abar[0].0).c(d!())?.unwrap();
let mt_leaf_info = utils::get_abar_proof(&axtxo_abar[0].0).c(d!())?.unwrap();

let oabar_in = OpenAnonBlindAssetRecordBuilder::from_abar(
&axtxo_abar[0].1,
owner_memo,
&from,
&from_secret_key,
)
.unwrap()
.mt_leaf_info(mt_leaf_info)
.build()
.unwrap();

let art = match (confidential_am, confidential_ty) {
(true, true) => AssetRecordType::ConfidentialAmount_ConfidentialAssetType,
(true, false) => AssetRecordType::ConfidentialAmount_NonConfidentialAssetType,
(false, true) => AssetRecordType::NonConfidentialAmount_ConfidentialAssetType,
_ => AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType,
};

utils::generate_abar2bar_op(&oabar_in, &from, &to, art, &fee_secret_key).c(d!())?;
Ok(())
}

/// Generate OABAR and add anonymous transfer operation
pub fn gen_oabar_add_op(
axfr_secret_key: String,
Expand All @@ -828,8 +874,8 @@ pub fn gen_oabar_add_op(
wallet::x_public_key_from_base64(to_enc_key).c(d!("invalid to_enc_key"))?;

let r = wallet::randomizer_from_base58(r).c(d!())?;
let diversified_from_pub_key = from.pub_key().randomize(&r);
let axtxo_abar = utils::get_owned_abars(&diversified_from_pub_key).c(d!())?;
let randomized_from_pub_key = from.pub_key().randomize(&r);
let axtxo_abar = utils::get_owned_abars(&randomized_from_pub_key).c(d!())?;
let owner_memo = utils::get_abar_memo(&axtxo_abar[0].0).c(d!())?.unwrap();
let mt_leaf_info = utils::get_abar_proof(&axtxo_abar[0].0).c(d!())?.unwrap();

Expand Down
40 changes: 29 additions & 11 deletions src/components/finutils/src/common/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ use {
serde::{self, Deserialize, Serialize},
std::collections::HashMap,
tendermint::{PrivateKey, PublicKey},
zei::anon_xfr::structs::AnonBlindAssetRecord,
zei::anon_xfr::{keys::AXfrPubKey, structs::MTLeafInfo},
zei::xfr::asset_record::AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType,
zei::xfr::structs::OpenAssetRecord,
zei::anon_xfr::{
keys::{AXfrKeyPair, AXfrPubKey},
structs::{AnonBlindAssetRecord, MTLeafInfo, OpenAnonBlindAssetRecord},
},
zei::xfr::{
asset_record::{open_blind_asset_record, AssetRecordType},
sig::{XfrKeyPair, XfrPublicKey},
structs::{AssetRecordTemplate, OwnerMemo},
structs::{AssetRecordTemplate, OpenAssetRecord, OwnerMemo},
},
zeialgebra::jubjub::JubjubScalar,
};
Expand Down Expand Up @@ -545,6 +545,7 @@ pub(crate) fn get_owned_abars(
get_serv_addr().c(d!())?,
wallet::anon_public_key_to_base64(addr)
);
println!("URL: {:?}", url);

attohttpc::get(&url)
.send()
Expand Down Expand Up @@ -727,17 +728,34 @@ pub fn generate_bar2abar_op(
)
.c(d!())?;

if input_record.get_record_type() != NonConfidentialAmount_NonConfidentialAssetType
|| input_record.asset_type != ASSET_TYPE_FRA
{
let feeop = gen_fee_bar_to_abar(auth_key_pair, txo_sid).c(d!())?;
builder.add_operation(feeop);
}
let feeop = gen_fee_bar_to_abar(auth_key_pair, txo_sid).c(d!())?;
builder.add_operation(feeop);

send_tx(&builder.take_transaction()).c(d!())?;
Ok(r)
}

#[inline(always)]
#[allow(missing_docs)]
pub fn generate_abar2bar_op(
oabar_in: &OpenAnonBlindAssetRecord,
from: &AXfrKeyPair,
to: &XfrPublicKey,
art: AssetRecordType,
fee_keypair: &XfrKeyPair,
) -> Result<()> {
let mut builder: TransactionBuilder = new_tx_builder().c(d!())?;
builder
.add_operation_abar_to_bar(oabar_in, from, to, art)
.c(d!())?;

let feeop = gen_fee_op(fee_keypair).c(d!())?;
builder.add_operation(feeop);

send_tx(&builder.take_transaction()).c(d!())?;
Ok(())
}

#[inline(always)]
#[allow(missing_docs)]
pub fn get_oar(owner_kp: &XfrKeyPair, txo_sid: TxoSID) -> Result<OpenAssetRecord> {
Expand Down
35 changes: 33 additions & 2 deletions src/components/finutils/src/txn_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

mod amount;

use ledger::data_model::AbarToBarOps;
use {
credentials::CredUserSecretKey,
crypto::basics::hybrid_encryption::XPublicKey,
Expand Down Expand Up @@ -50,6 +51,7 @@ use {
zei::anon_xfr::structs::AXfrBody,
zei::{
anon_xfr::{
abar_to_bar::gen_abar_to_bar_note,
bar_to_abar::gen_bar_to_abar_body,
gen_anon_xfr_body,
keys::{AXfrKeyPair, AXfrPubKey},
Expand Down Expand Up @@ -521,6 +523,35 @@ impl TransactionBuilder {
Ok((self, r))
}

/// Create a new operation to convert from Anonymous record to Blind Asset Record
#[allow(dead_code)]
pub fn add_operation_abar_to_bar(
&mut self,
input: &OpenAnonBlindAssetRecord,
input_keypair: &AXfrKeyPair,
bar_pub_key: &XfrPublicKey,
asset_record_type: AssetRecordType,
) -> Result<&mut Self> {
let mut prng = ChaChaRng::from_entropy();
let user_params = UserParams::abar_to_bar_params(41);

let note = gen_abar_to_bar_note(
&mut prng,
&user_params,
&input,
&input_keypair,
bar_pub_key,
asset_record_type,
)
.c(d!())?;

let abar_to_bar = AbarToBarOps::new(&note, self.no_replay_token).c(d!())?;

let op = Operation::AbarToBar(Box::from(abar_to_bar));
self.txn.add_operation(op);
Ok(self)
}

/// Add an operation to transfer assets held in Anonymous Blind Asset Record.
#[allow(dead_code)]
pub fn add_operation_anon_transfer(
Expand Down Expand Up @@ -1307,7 +1338,7 @@ mod tests {
rand_chacha::ChaChaRng,
rand_core::SeedableRng,
std::ops::Neg,
zei::anon_xfr::bar_to_from_abar::verify_bar_to_abar_note,
zei::anon_xfr::bar_to_abar::verify_bar_to_abar_note,
zei::anon_xfr::config::FEE_CALCULATING_FUNC,
zei::anon_xfr::structs::{
AnonBlindAssetRecord, OpenAnonBlindAssetRecordBuilder,
Expand Down Expand Up @@ -1700,7 +1731,7 @@ mod tests {
let user_params = UserParams::eq_committed_vals_params();
let node_params = NodeParams::from(user_params);
let result =
verify_bar_to_abar_note(&node_params, &note.note, from.get_pk_ref(), 0);
verify_bar_to_abar_note(&node_params, &note.note, from.get_pk_ref());
assert!(result.is_ok());
}
}
Expand Down
55 changes: 55 additions & 0 deletions src/components/wasm/src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,61 @@ impl TransactionBuilder {
Ok(self)
}

/// Adds an operation to transaction builder which converts an abar to a bar.
///
/// @param {AnonBlindAssetRecord} input - the ABAR to be converted
/// @param {OwnerMemo} owner_memo - the corresponding owner_memo of the ABAR to be converted
/// @param {MTLeafInfo} mt_leaf_info - the Merkle Proof of the ABAR
/// @param {AXfrKeyPair} from_keypair - the owners Anon Key pair
/// @param {XSecretKey} from_dec_key - the owners decryption key
/// @param {XfrPublic} recipient - the BAR owner public key
/// @param {bool} conf_amount - whether the BAR amount should be confidential
/// @param {bool} conf_type - whether the BAR asset type should be confidential
pub fn add_operation_abar_to_bar(
mut self,
input: AnonBlindAssetRecord,
owner_memo: OwnerMemo,
mt_leaf_info: MTLeafInfo,
from_keypair: AXfrKeyPair,
from_dec_key: XSecretKey,
recipient: XfrPublicKey,
conf_amount: bool,
conf_type: bool,
) -> Result<TransactionBuilder, JsValue> {
let oabar = OpenAnonBlindAssetRecordBuilder::from_abar(
&input,
owner_memo.memo,
&from_keypair,
&from_dec_key,
)
.c(d!())
.map_err(|e| JsValue::from_str(&format!("Could not add operation: {}", e)))?
.mt_leaf_info(mt_leaf_info.get_zei_mt_leaf_info().clone())
.build()
.c(d!())
.map_err(|e| JsValue::from_str(&format!("Could not add operation: {}", e)))?;

let art = match (conf_amount, conf_type) {
(true, true) => AssetRecordType::ConfidentialAmount_ConfidentialAssetType,
(true, false) => {
AssetRecordType::ConfidentialAmount_NonConfidentialAssetType
}
(false, true) => {
AssetRecordType::NonConfidentialAmount_ConfidentialAssetType
}
_ => AssetRecordType::NonConfidentialAmount_NonConfidentialAssetType,
};

self.get_builder_mut()
.add_operation_abar_to_bar(&oabar, &from_keypair, &recipient, art)
.c(d!())
.map_err(|e| {
JsValue::from_str(&format!("Could not add operation: {}", e))
})?;

Ok(self)
}

/// Returns a list of randomizer base58 strings as json
pub fn get_randomizers(&self) -> JsValue {
let r = RandomizerStringArray {
Expand Down
Loading