H/W Ledger Build Tx z2z

This commit is contained in:
Hanh 2023-04-15 18:53:16 +10:00
parent 9b94a6a2b3
commit e2c4902df4
7 changed files with 53 additions and 75 deletions

View File

@ -413,6 +413,8 @@ struct CResult_____c_char get_property(uint8_t coin, char *name);
struct CResult_u8 set_property(uint8_t coin, char *name, char *value);
struct CResult_____c_char ledger_send(uint8_t coin, char *tx_plan);
bool has_cuda(void);
bool has_metal(void);

View File

@ -1,8 +1,8 @@
use crate::coinconfig::{init_coin, CoinConfig, MEMPOOL, MEMPOOL_RUNNER};
use crate::coinconfig::{init_coin, CoinConfig, MEMPOOL, MEMPOOL_RUNNER, self};
use crate::db::data_generated::fb::{ProgressT, Recipients, SendTemplate, Servers};
use crate::db::FullEncryptedBackup;
use crate::note_selection::TransactionReport;
use crate::{ChainError, TransactionPlan, Tx};
use crate::{ChainError, TransactionPlan, Tx, build_broadcast_tx};
use allo_isolate::{ffi, IntoDart};
use android_logger::Config;
use flatbuffers::FlatBufferBuilder;
@ -1219,6 +1219,21 @@ pub unsafe extern "C" fn set_property(
to_cresult(with_coin(coin, res))
}
#[no_mangle]
#[tokio::main]
pub async unsafe extern "C" fn ledger_send(coin: u8, tx_plan: *mut c_char) -> CResult<*mut c_char> {
from_c_str!(tx_plan);
let res = async {
let tx_plan: TransactionPlan = serde_json::from_str(&tx_plan)?;
let c = CoinConfig::get(coin);
let mut client = c.connect_lwd().await?;
let prover = coinconfig::get_prover();
let response = build_broadcast_tx(&mut client, &tx_plan, prover).await?;
Ok::<_, anyhow::Error>(response)
};
to_cresult_str(res.await)
}
#[no_mangle]
pub unsafe extern "C" fn has_cuda() -> bool {
crate::gpu::has_cuda()

View File

@ -5,3 +5,5 @@ mod builder;
mod tests;
pub use builder::build_broadcast_tx;
pub use transport::ledger_get_taddr;

View File

@ -1,52 +1,36 @@
use std::{
fs::File,
io::Read,
path::{Path, PathBuf}, vec,
io::Read, vec,
};
use std::io::Write;
use blake2b_simd::Params;
use bls12_381::Scalar;
use byteorder::WriteBytesExt;
use byteorder::LE;
use ff::{PrimeField, Field};
use group::GroupEncoding;
use hex_literal::hex;
use jubjub::{Fr, SubgroupPoint, Fq};
use ledger_apdu::APDUCommand;
use ledger_transport_hid::{TransportNativeHID, hidapi::HidApi};
use orchard::keys::FullViewingKey;
use jubjub::{Fr, Fq};
use rand::{rngs::OsRng, RngCore, SeedableRng};
use rand_chacha::ChaChaRng;
use reqwest::Client;
use ripemd::{Digest, Ripemd160};
use secp256k1::{All, PublicKey, Secp256k1, SecretKey};
use serde_json::Value;
use sha2::Sha256;
use tonic::{Request, transport::Channel};
use crate::{Destination, Source, TransactionPlan, connect_lightwalletd, RawTransaction, CompactTxStreamerClient};
use zcash_client_backend::encoding::{decode_extended_spending_key, encode_extended_full_viewing_key, encode_payment_address};
use zcash_note_encryption::EphemeralKeyBytes;
use zcash_params::tx;
use crate::{Destination, Source, TransactionPlan, RawTransaction, CompactTxStreamerClient};
use crate::ledger::transport::*;
use anyhow::{anyhow, Result};
use zcash_primitives::{
consensus::{BlockHeight, BranchId, MainNetwork, Parameters},
merkle_tree::IncrementalWitness,
consensus::{BlockHeight, BranchId, MainNetwork},
merkle_tree::{Hashable, IncrementalWitness},
sapling::{
note_encryption::sapling_note_encryption, value::{NoteValue, ValueCommitment, ValueSum}, Diversifier, Node, Note,
PaymentAddress, Rseed, ProofGenerationKey, Nullifier, prover::TxProver, redjubjub::Signature,
PaymentAddress, Rseed, Nullifier, prover::TxProver, redjubjub::Signature,
},
transaction::{
components::{sapling::{OutputDescriptionV5, Bundle, Authorized as SapAuthorized}, Amount, OutputDescription, SpendDescription},
components::{sapling::{Bundle, Authorized as SapAuthorized}, GROTH_PROOF_SIZE, Amount, OutputDescription, SpendDescription},
TransactionData, TxVersion, Authorized,
},
zip32::{DiversifiableFullViewingKey, ExtendedFullViewingKey, ExtendedSpendingKey}, constants::PROOF_GENERATION_KEY_GENERATOR,
}, constants::PROOF_GENERATION_KEY_GENERATOR,
};
use zcash_primitives::merkle_tree::Hashable;
use zcash_primitives::transaction::components::GROTH_PROOF_SIZE;
use zcash_proofs::{prover::LocalTxProver, sapling::SaplingProvingContext};
struct SpendDescriptionUnAuthorized {
@ -57,7 +41,7 @@ struct SpendDescriptionUnAuthorized {
zkproof: [u8; GROTH_PROOF_SIZE],
}
pub async fn build_broadcast_tx(client: &mut CompactTxStreamerClient<Channel>, tx_plan: &TransactionPlan, prover: &LocalTxProver) -> Result<()> {
pub async fn build_broadcast_tx(client: &mut CompactTxStreamerClient<Channel>, tx_plan: &TransactionPlan, prover: &LocalTxProver) -> Result<String> {
ledger_init().await?;
let address = ledger_get_address().await?;
println!("address {}", address);
@ -342,5 +326,5 @@ pub async fn build_broadcast_tx(client: &mut CompactTxStreamerClient<Channel>, t
})).await?.into_inner();
println!("{}", response.error_message);
Ok(())
Ok(response.error_message)
}

View File

@ -13,7 +13,7 @@ use zcash_primitives::zip32::DiversifiableFullViewingKey;
use std::io::Write;
use hex_literal::hex;
async fn apdu(data: &[u8]) -> Vec<u8> {
async fn apdu_usb(data: &[u8]) -> Vec<u8> {
let api = HidApi::new().unwrap();
let transport = TransportNativeHID::new(&api).unwrap();
let command = APDUCommand {
@ -31,7 +31,7 @@ async fn apdu(data: &[u8]) -> Vec<u8> {
const TEST_SERVER_IP: &str = "127.0.0.1";
async fn apdu2(data: &[u8]) -> Vec<u8> {
async fn apdu(data: &[u8]) -> Vec<u8> {
let client = Client::new();
let response = client.post(&format!("http://{}:5000/apdu", TEST_SERVER_IP))
.body(format!("{{\"data\": \"{}\"}}", hex::encode(data)))
@ -198,3 +198,10 @@ pub async fn ledger_pedersen_hash(data: &[u8]) -> Result<Vec<u8>> {
let cmu = apdu(&bb).await;
Ok(cmu)
}
pub async fn ledger_get_taddr() -> Result<Vec<u8>> {
let mut bb: Vec<u8> = vec![];
bb.write_all(&hex!("E013000000"))?;
let pkh = apdu(&bb).await;
Ok(pkh)
}

View File

@ -135,4 +135,6 @@ pub fn init_test() {
}
#[cfg(feature = "ledger")]
pub use ledger::build_broadcast_tx;
pub use ledger::{build_broadcast_tx, ledger_get_taddr};
pub use taddr::derive_from_secretkey;

View File

@ -1,54 +1,20 @@
use std::{
fs::File,
io::Read,
path::{Path, PathBuf}, vec,
path::Path,
};
use std::io::Write;
use blake2b_simd::Params;
use bls12_381::Scalar;
use byteorder::WriteBytesExt;
use byteorder::LE;
use ff::{PrimeField, Field};
use group::GroupEncoding;
use hex_literal::hex;
use jubjub::{Fr, SubgroupPoint, Fq};
use ledger_apdu::APDUCommand;
use ledger_transport_hid::{TransportNativeHID, hidapi::HidApi};
use orchard::keys::FullViewingKey;
use rand::{rngs::OsRng, RngCore, SeedableRng};
use rand_chacha::ChaChaRng;
use reqwest::Client;
use ripemd::{Digest, Ripemd160};
use secp256k1::{All, PublicKey, Secp256k1, SecretKey};
use serde_json::Value;
use sha2::Sha256;
use tonic::{Request, transport::Channel};
use warp_api_ffi::{Destination, Source, TransactionPlan, connect_lightwalletd, RawTransaction, CompactTxStreamerClient, build_broadcast_tx};
use zcash_client_backend::encoding::{decode_extended_spending_key, encode_extended_full_viewing_key, encode_payment_address};
use zcash_note_encryption::EphemeralKeyBytes;
use zcash_params::tx;
use anyhow::{anyhow, Result};
use zcash_primitives::{
consensus::{BlockHeight, BranchId, MainNetwork, Parameters},
merkle_tree::IncrementalWitness,
sapling::{
note_encryption::sapling_note_encryption, value::{NoteValue, ValueCommitment, ValueSum}, Diversifier, Node, Note,
PaymentAddress, Rseed, ProofGenerationKey, Nullifier, prover::TxProver, redjubjub::Signature,
},
transaction::{
components::{sapling::{OutputDescriptionV5, Bundle, Authorized as SapAuthorized}, Amount, OutputDescription, SpendDescription},
TransactionData, TxVersion, Authorized,
},
zip32::{DiversifiableFullViewingKey, ExtendedFullViewingKey, ExtendedSpendingKey}, constants::PROOF_GENERATION_KEY_GENERATOR,
};
use zcash_primitives::merkle_tree::Hashable;
use zcash_primitives::transaction::components::GROTH_PROOF_SIZE;
use zcash_proofs::{prover::LocalTxProver, sapling::SaplingProvingContext};
use ripemd::Digest;
use secp256k1::SecretKey;
use warp_api_ffi::{TransactionPlan, connect_lightwalletd, build_broadcast_tx, ledger_get_taddr, derive_from_secretkey};
use anyhow::Result;
use zcash_client_backend::encoding::encode_transparent_address;
use zcash_primitives::{legacy::TransparentAddress, consensus::{Parameters, Network, Network::MainNetwork}};
use zcash_proofs::prover::LocalTxProver;
#[tokio::main]
async fn main() -> Result<()> {
let network: &Network = &MainNetwork;
let params_dir = Path::new(&std::env::var("HOME").unwrap()).join(".zcash-params");
let prover = LocalTxProver::new(
&params_dir.join("sapling-spend.params"),