Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions chain-runtimes/zcash/.cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@
# it fails with "the wasm* targets are not supported by default".
[target.wasm32-unknown-unknown]
rustflags = ['--cfg', 'getrandom_backend="wasm_js"']

# NU7 exists in this zcash_* release line only under this cfg; the patched
# zcash_protocol gives it the mainnet height. Joined with the target flags above.
[target.'cfg(all())']
rustflags = ['--cfg', 'zcash_unstable="nu7"']
9 changes: 4 additions & 5 deletions chain-runtimes/zcash/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions chain-runtimes/zcash/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ members = [
exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]

[workspace.package]
version = "0.1.0-alpha.12"
version = "0.1.0-alpha.15"
edition = "2021"
license = "Apache-2.0"
rust-version = "1.85"

# Unmodified crates.io releases, except zcash_client_sqlite's Cargo.toml drops rusqlite "bundled"
# (needs a libc sysroot wasm32 lacks). See patches/manifest.json.
# (needs a libc sysroot wasm32 lacks) and zcash_protocol gains NU7 mainnet. See patches/manifest.json.
[workspace.dependencies]
blake2b_simd = "1"
zcash_client_backend = { version = "0.24.0", default-features = false, features = ["orchard", "transparent-inputs", "lightwalletd-tonic", "sync", "pczt"] }
Expand Down Expand Up @@ -64,6 +64,8 @@ tonic-web-wasm-client = "0.9.1"

# Run `bash scripts/vendor-deps.sh` first to create vendor/.
[patch.crates-io]
# Sets NU7's mainnet height and real branch ID; needs the nu7 cfg in .cargo/config.toml.
zcash_protocol = { path = "vendor/zcash_protocol-0.10.5" }
zcash_client_sqlite = { path = "vendor/zcash_client_sqlite-0.22.0" }
tonic-web-wasm-client = { path = "vendor/tonic-web-wasm-client-0.9.1" }

Expand Down
10 changes: 10 additions & 0 deletions chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ use zeroize::Zeroizing;

use crate::{account_keys, keys, review, sign, transparent_prevouts, transparent_send};

/// Sets when mainnet fees drop to the ZIP 2009 rate, for every later quote, build and
/// balance: `"null"` disables the switch and a height delays it; absent or malformed
/// keeps the default. It never advances the switch.
#[wasm_bindgen(js_name = setZip2009MainnetHeight)]
pub fn set_zip2009_mainnet_height(json: Option<String>) {
onekey_zcash_send_policy::set_zip2009_switch(
onekey_zcash_send_policy::Zip2009Switch::from_host_json(json.as_deref()),
);
}

#[wasm_bindgen(js_name = transactionPolicy)]
pub fn transaction_policy(target_height: u32) -> Result<String, JsValue> {
serde_json::to_string(&onekey_zcash_send_policy::transaction_policy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,20 @@ mod tests {
serde_json::from_str(&parse_json(&request.to_string()).unwrap()).unwrap();
assert_eq!(parsed[0]["isCoinbase"], true);
}

#[test]
fn parses_outputs_of_an_nu7_transaction() {
let mut request = request();
let mut bytes = hex::decode(request["transactions"][1]["rawTx"].as_str().unwrap()).unwrap();
// v6 header: version, version group id, then the consensus branch id.
bytes[8..12].copy_from_slice(&u32::from(BranchId::Nu7).to_le_bytes());
let tx = Transaction::read(&bytes[..], BranchId::Sprout).unwrap();
assert_eq!(tx.consensus_branch_id(), BranchId::Nu7);
request["transactions"] = json!([{
"txid": tx.txid().to_string(), "rawTx": hex::encode(bytes),
}]);
let parsed: Value =
serde_json::from_str(&parse_json(&request.to_string()).unwrap()).unwrap();
assert_eq!(parsed[0]["outputs"][0]["valueZat"], "1000");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ use crate::{
error::{ErrorCode, KeysError, Result},
};

const MAX_EXPIRY_DELTA: u32 = onekey_zcash_send_policy::EXPIRY_DELTA;
const XPRV_VERSION: [u8; 4] = [0x04, 0x88, 0xad, 0xe4];
const ACCOUNT_XPRV_DEPTH: u8 = 3;

Expand Down Expand Up @@ -242,12 +241,16 @@ fn plan_transaction(request: TransparentTxRequest) -> Result<TransactionPlan> {
)
})?;
let target_height = BlockHeight::from_u32(request.target_height);
if BranchId::for_height(&MAIN_NETWORK, target_height) != BranchId::Nu6_3 {
// Built as v6, which needs NU6.3 or later.
if !matches!(
BranchId::for_height(&MAIN_NETWORK, target_height),
BranchId::Nu6_3 | BranchId::Nu7
) {
return Err(KeysError::with(
ErrorCode::InvalidTargetHeight,
serde_json::json!({
"targetHeight": request.target_height,
"requiredBranch": "Nu6.3",
"requiredBranch": "Nu6.3+",
}),
));
}
Expand All @@ -273,7 +276,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result<TransactionPlan> {
serde_json::json!({
"targetHeight": request.target_height,
"expiryHeight": request.expiry_height,
"maximumDelta": MAX_EXPIRY_DELTA,
"maximumDelta": onekey_zcash_send_policy::expiry_delta(&MAIN_NETWORK, target_height),
}),
));
}
Expand Down Expand Up @@ -567,6 +570,7 @@ fn build_transaction(
account_key: &AccountPrivKey,
) -> Result<TransparentBuildResult> {
let quote = plan.quote();
let branch = BranchId::for_height(&MAIN_NETWORK, plan.target_height);
let mut builder = TransparentBuilder::empty();
let mut signing_set = TransparentSigningSet::new();

Expand Down Expand Up @@ -626,7 +630,7 @@ fn build_transaction(
)
})?;
let unsigned_tx = TransactionData::<TransparentUnauthorized>::from_parts_v6(
BranchId::Nu6_3,
branch,
0,
plan.expiry_height,
Some(transparent_bundle.clone()),
Expand All @@ -649,7 +653,7 @@ fn build_transaction(
)
.map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?;
let transaction = TransactionData::<Authorized>::from_parts_v6(
BranchId::Nu6_3,
branch,
0,
plan.expiry_height,
Some(authorized_bundle),
Expand Down Expand Up @@ -1024,6 +1028,25 @@ mod tests {
}
}

#[test]
fn fee_quotes_follow_a_delayed_or_disabled_switch() {
use onekey_zcash_send_policy::{set_zip2009_switch, Zip2009Switch};
let quote_at = |height: u32| {
let mut request: serde_json::Value =
serde_json::from_str(&request_json(&[100_000], true)).unwrap();
request["targetHeight"] = height.into();
request["expiryHeight"] = (height + 40).into();
let quote: serde_json::Value =
serde_json::from_str(&quote_json(&request.to_string()).unwrap()).unwrap();
quote["feeZat"].clone()
};
set_zip2009_switch(Zip2009Switch::Disabled);
assert_eq!(quote_at(3_590_100), "10000");
set_zip2009_switch(Zip2009Switch::from_host_json(Some("3600000")));
assert_eq!(quote_at(3_600_099), "10000");
assert_eq!(quote_at(3_600_100), "2000");
}

#[test]
fn a_transparent_quote_needs_eight_valid_blocks_and_at_most_forty() {
for delta in [0, 7, 41, 100] {
Expand Down Expand Up @@ -1347,6 +1370,30 @@ mod tests {
"81004865cdc4217f34aafd1d4b307b3cc5d60fcee7afdb4a829983d394ae39cd"
);
}

#[test]
fn builds_under_nu7_from_its_activation() {
use zcash_protocol::consensus::{NetworkUpgrade, Parameters};
let nu7 = u32::from(MAIN_NETWORK.activation_height(NetworkUpgrade::Nu7).unwrap());
let mut request: serde_json::Value =
serde_json::from_str(&request_json(&[100_000], true)).unwrap();
request["targetHeight"] = nu7.into();
request["expiryHeight"] = (nu7 + onekey_zcash_send_policy::NU7_EXPIRY_DELTA).into();
let raw = build_with_account_xprv_json(&request.to_string(), &xprv()).unwrap();
let result: TransparentBuildResult = serde_json::from_str(&raw).unwrap();
let tx = zcash_primitives::transaction::Transaction::read(
&hex::decode(&result.raw_tx).unwrap()[..],
BranchId::Sprout,
)
.unwrap();
assert_eq!(tx.consensus_branch_id(), BranchId::Nu7);
assert_eq!(tx.txid().to_string(), result.txid);

// Before activation the expiry must stay below NU7.
request["targetHeight"] = (nu7 - 20).into();
let error = build_with_account_xprv_json(&request.to_string(), &xprv()).unwrap_err();
assert_eq!(error.code, ErrorCode::InvalidTargetHeight);
}
}

fn require_transparent(address: RecipientAddress) -> Result<TransparentAddress> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,8 @@ fn validate_original(
let expected_anchor = has_ironwood.then(|| orchard::Anchor::empty_tree().to_bytes());
if *global.tx_version() != zcash_protocol::constants::V6_TX_VERSION
|| *global.version_group_id() != zcash_protocol::constants::V6_VERSION_GROUP_ID
|| *global.consensus_branch_id() != u32::from(BranchId::Nu6_3)
|| *global.consensus_branch_id()
!= u32::from(BranchId::for_height(&MAIN_NETWORK, plan.target_height))
|| *global.expiry_height() != u32::from(plan.expiry_height)
|| pczt::common::determine_lock_time(global, pczt.transparent().inputs()) != Some(0)
|| !pczt.sapling().spends().is_empty()
Expand Down
23 changes: 10 additions & 13 deletions chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use zcash_client_backend::data_api::{
Account as _, AccountBalance, AccountBirthday, AccountPurpose, AccountSource, Balance,
WalletCommitmentTrees, WalletRead, WalletWrite, Zip32Derivation,
};
use zcash_client_sqlite::error::SqliteClientError;
use zcash_client_sqlite::{error::SqliteClientError, ExtensionTransaction};
use zcash_keys::keys::UnifiedFullViewingKey;

use crate::error::{ErrorCode, Result, RuntimeError};
Expand Down Expand Up @@ -238,7 +238,7 @@ pub(crate) fn restart_with_birthday(
.expose_uuid()
.to_string();
// The old birthday's unscanned ranges would find what the new one excludes.
prune_scan_queue_below_wallet_birthday(wallet)?;
prune_scan_queue_below_wallet_birthday(wallet, ext)?;
crate::tx_state::prune_orphaned_rows(ext)?;
Ok(uuid)
})
Expand Down Expand Up @@ -469,26 +469,23 @@ pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> {
)
.detail(e)
})?;
prune_scan_queue_below_wallet_birthday(wallet)?;
prune_scan_queue_below_wallet_birthday(wallet, ext)?;
crate::tx_state::prune_orphaned_rows(ext)
})
}

/// delete_account leaves the scan queue alone, so ranges queued only for a
/// removed account's earlier birthday would still be scanned for nobody.
fn prune_scan_queue_below_wallet_birthday<W>(wallet: &mut W) -> Result<()>
/// removed account's earlier birthday would still be scanned for nobody. A paused
/// account still counts: its remaining history waits for it.
fn prune_scan_queue_below_wallet_birthday<W>(
wallet: &mut W,
ext: &ExtensionTransaction<'_>,
) -> Result<()>
where
W: WalletWrite,
<W as WalletRead>::Error: std::fmt::Display,
{
let birthday = wallet.get_wallet_birthday().map_err(|e| {
RuntimeError::with(
ErrorCode::DatabaseError,
json!({ "operation": "getWalletBirthday" }),
)
.detail(e)
})?;
if let Some(birthday) = birthday {
if let Some(birthday) = crate::scan_floor::earliest_birthday(ext)? {
wallet
.prune_scan_queue_below(birthday, Some(ScanPriority::OpenAdjacent))
.map_err(|e| {
Expand Down
20 changes: 16 additions & 4 deletions chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ pub fn set_request_handler(handler: Option<js_sys::Function>) {
network::set_request_handler(handler);
}

/// Sets when mainnet fees drop to the ZIP 2009 rate, for every later quote, build and
/// balance: `"null"` disables the switch and a height delays it; absent or malformed
/// keeps the default. It never advances the switch.
#[wasm_bindgen(js_name = setZip2009MainnetHeight)]
pub fn set_zip2009_mainnet_height(json: Option<String>) {
onekey_zcash_send_policy::set_zip2009_switch(
onekey_zcash_send_policy::Zip2009Switch::from_host_json(json.as_deref()),
);
}

/// Installs the storage layer. Must be awaited once before any other call. Idempotent.
#[wasm_bindgen(js_name = init)]
pub async fn init() -> Result<(), JsValue> {
Expand Down Expand Up @@ -497,8 +507,8 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra
/// stores it unless the node definitively rejected it.
///
/// Returns `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`.
/// - `rejected`: the node definitively judged it consensus-invalid or expired; it can never be
/// mined. It is not stored and its notes are spendable again at once (if an earlier submit
/// - `rejected`: the node reported it expired and the local chain has passed its expiry; it can
/// never be mined. It is not stored and its notes are spendable again at once (if an earlier submit
/// stored it, it is marked rejected and its notes return at its expiry height).
/// - `unknown`: delivery to the node is uncertain. The transaction is stored and stays pending
/// until mined or expired; the host does not resubmit it and must not treat it as failed.
Expand Down Expand Up @@ -549,7 +559,7 @@ pub fn pending_broadcast_txids(account_uuid: String) -> Result<String, JsValue>
/// Resends a stored pending transaction. Irreversible. For an explicit user request only:
/// sync does not call it, and an unmined send otherwise stays pending until mined or expired.
///
/// Throws `BROADCAST_REJECTED` when the node definitively rejects it (do not retry);
/// Throws `BROADCAST_REJECTED` when the node reports it expired and the local chain agrees (do not retry);
/// `BROADCAST_OUTCOME_UNKNOWN` when the node errored without proving it can never be mined;
/// `NETWORK_ERROR` on transport failure. In the latter two cases the transaction stays pending
/// until mined or expired.
Expand All @@ -559,7 +569,9 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> {
let r = match tx_state::assert_not_rejected(&mut db, &txid)
.and_then(|_| send::raw_transaction(&db, &txid))
{
Ok(raw) => network::broadcast(&mut client, raw).await,
Ok(raw) => network::broadcast(&mut client, raw)
.await
.map_err(|e| send::confirm_stored_rejection(&db, &txid, e)),
Err(e) => Err(e),
};
let r = match r {
Expand Down
1 change: 1 addition & 0 deletions chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod circuit_keys;
pub mod clock;
pub mod error;
pub mod history;
pub mod scan_floor;
pub mod send;
pub mod stats;
pub mod storage;
Expand Down
Loading
Loading