Skip to content
Open
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
4 changes: 4 additions & 0 deletions crates/webzjs-common/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ use wasm_bindgen::JsValue;
pub enum Error {
#[error("Invalid network string given: {0}")]
InvalidNetwork(String),
#[error("Could not parse PCZT: {0}")]
PcztParse(String),
#[error("Could not serialize PCZT: {0}")]
PcztSerialize(String),
}

impl From<Error> for JsValue {
Expand Down
15 changes: 11 additions & 4 deletions crates/webzjs-common/src/pczt.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use wasm_bindgen::prelude::*;

use crate::error::Error;

#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct Pczt(pczt::Pczt);
Expand All @@ -24,15 +26,20 @@ impl From<Pczt> for pczt::Pczt {
#[wasm_bindgen]
impl Pczt {
/// Returns the postcard serialization of the Pczt (latest PCZT version).
pub fn serialize(&self) -> Vec<u8> {
///
/// Errors are returned to JS as exceptions. A panic here would become a WASM
/// trap ("RuntimeError: unreachable") that carries no detail.
pub fn serialize(&self) -> Result<Vec<u8>, Error> {
self.0
.clone()
.serialize()
.expect("serializing a PCZT to its latest version should not fail")
.map_err(|e| Error::PcztSerialize(format!("{e:?}")))
}

/// Deserialize to a Pczt from postcard bytes.
pub fn from_bytes(bytes: &[u8]) -> Pczt {
Self(pczt::Pczt::parse(bytes).unwrap())
pub fn from_bytes(bytes: &[u8]) -> Result<Pczt, Error> {
pczt::Pczt::parse(bytes)
.map(Self)
.map_err(|e| Error::PcztParse(format!("{e:?}")))
}
}
34 changes: 26 additions & 8 deletions crates/webzjs-keys/src/demo_pczt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,18 @@ use orchard::value::NoteValue as OrchardNoteValue;
use orchard::Address as OrchardAddress;

use pczt::roles::creator::Creator;
use webzjs_common::Network;
use zcash_keys::address::UnifiedAddress;
use zcash_keys::encoding::AddressCodec;
use zcash_keys::keys::{UnifiedFullViewingKey as InnerUfvk, UnifiedSpendingKey};
use zcash_primitives::transaction::builder::PcztParts;
use zcash_primitives::transaction::TxVersion;
use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkConstants, Parameters};
use zcash_protocol::value::Zatoshis;
use webzjs_common::Network;

use zcash_transparent::address::TransparentAddress;
use zcash_transparent::bundle::{OutPoint, TxOut};
use zcash_transparent::builder::TransparentBuilder;
use zcash_transparent::bundle::{OutPoint, TxOut};
use zcash_transparent::keys::{NonHardenedChildIndex, TransparentKeyScope};
use zcash_transparent::pczt::Bip32Derivation;

Expand Down Expand Up @@ -155,7 +155,10 @@ fn build_transparent(
.map_err(|e| Error::PcztDescribe(format!("derive t-pubkey: {e:?}")))?;
let taddr = TransparentAddress::from_pubkey(&pk);

let coin = TxOut::new(Zatoshis::from_u64(SPEND_VALUE).unwrap(), taddr.script().into());
let coin = TxOut::new(
Zatoshis::from_u64(SPEND_VALUE).unwrap(),
taddr.script().into(),
);
let mut builder = TransparentBuilder::empty();
builder
.add_p2pkh_input(pk, OutPoint::new([0u8; 32], 0), coin)
Expand Down Expand Up @@ -310,7 +313,11 @@ fn build_orchard(
.clone();
let mut rng = StdRng::seed_from_u64(0x0_C_5A_u64);

let note = make_orchard_note(&mut rng, fvk.address_at(0u32, OrchardScope::External), SPEND_VALUE);
let note = make_orchard_note(
&mut rng,
fvk.address_at(0u32, OrchardScope::External),
SPEND_VALUE,
);
let cmx: ExtractedNoteCommitment = note.commitment().into();
let sibling = MerkleHashOrchard::from_cmx(&cmx);
let path = OrchardMerklePath::from_parts(0, [sibling; 32]);
Expand Down Expand Up @@ -347,7 +354,9 @@ fn build_orchard(
fn make_orchard_note(rng: &mut StdRng, recipient: OrchardAddress, value: u64) -> OrchardNote {
let mut rho_bytes = [0u8; 32];
rho_bytes[0] = 7;
let rho = Rho::from_bytes(&rho_bytes).into_option().expect("valid rho");
let rho = Rho::from_bytes(&rho_bytes)
.into_option()
.expect("valid rho");
loop {
let mut rseed_bytes = [0u8; 32];
rng.fill_bytes(&mut rseed_bytes);
Expand Down Expand Up @@ -388,9 +397,18 @@ mod tests {
let attacker = ufvk_from_seed(&net, ATTACKER_SEED).unwrap();

for (pool, demo) in [
("transparent", transparent_demo(&net, &me, &bridge, &attacker).unwrap()),
("sapling", sapling_demo(&net, &me, &bridge, &attacker).unwrap()),
("orchard", orchard_demo(&net, &me, &bridge, &attacker).unwrap()),
(
"transparent",
transparent_demo(&net, &me, &bridge, &attacker).unwrap(),
),
(
"sapling",
sapling_demo(&net, &me, &bridge, &attacker).unwrap(),
),
(
"orchard",
orchard_demo(&net, &me, &bridge, &attacker).unwrap(),
),
] {
let honest = hex_to_pczt(&demo.honest);
let spoof = hex_to_pczt(&demo.spoof);
Expand Down
8 changes: 4 additions & 4 deletions crates/webzjs-keys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// Copyright 2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

#[cfg(feature = "demo-builder")]
mod demo_pczt;
mod error;
mod keys;
mod pczt_describe;
mod pczt_sign;
#[cfg(feature = "demo-builder")]
mod demo_pczt;

#[cfg(feature = "demo-builder")]
pub use demo_pczt::*;
pub use error::*;
pub use keys::*;
pub use pczt_describe::*;
pub use pczt_sign::*;
#[cfg(feature = "demo-builder")]
pub use demo_pczt::*;
21 changes: 15 additions & 6 deletions crates/webzjs-keys/src/pczt_describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,9 @@ fn transparent_addr_is_ours(
};
bip32_derivation.iter().any(|(claimed_pk, deriv)| {
match tfvk.derive_pubkey_at_bip32_path(network, account, deriv.derivation_path()) {
Ok(pk) => &pk.serialize() == claimed_pk && TransparentAddress::from_pubkey(&pk) == *addr,
Ok(pk) => {
&pk.serialize() == claimed_pk && TransparentAddress::from_pubkey(&pk) == *addr
}
Err(_) => false,
}
})
Expand All @@ -378,8 +380,10 @@ fn transparent_addr_is_ours(
/// invariants (spends are ours, value balances / turnstile identity holds, every
/// output is commitment-bound, fee is sane) for migrations as for any PCZT.
fn detect_migration(outputs: &[PcztOutputSummary]) -> Option<MigrationSummary> {
let ironwood: Vec<&PcztOutputSummary> =
outputs.iter().filter(|o| o.pool == pool::IRONWOOD).collect();
let ironwood: Vec<&PcztOutputSummary> = outputs
.iter()
.filter(|o| o.pool == pool::IRONWOOD)
.collect();
if ironwood.is_empty() {
return None;
}
Expand Down Expand Up @@ -499,7 +503,8 @@ fn analyze(
}

for output in bundle.outputs() {
if let Err(sapling::pczt::VerifyError::InvalidValueCommitment) = output.verify_cv() {
if let Err(sapling::pczt::VerifyError::InvalidValueCommitment) = output.verify_cv()
{
cv_mismatch = true;
}
match output.value().map(|v| v.inner()) {
Expand Down Expand Up @@ -562,7 +567,9 @@ fn analyze(
let value = u64::from(*input.value());
total_in += value;
let ours = TransparentAddress::from_script_from_chain(input.script_pubkey())
.map(|addr| transparent_addr_is_ours(&network, tfvk, &addr, input.bip32_derivation()))
.map(|addr| {
transparent_addr_is_ours(&network, tfvk, &addr, input.bip32_derivation())
})
.unwrap_or(false);
if !ours {
foreign_input = true;
Expand All @@ -577,7 +584,9 @@ fn analyze(
let recipient = addr.map(|addr| addr.encode(&network));
// Change = the coin pays back to one of our own transparent keys.
let is_change = addr
.map(|addr| transparent_addr_is_ours(&network, tfvk, &addr, output.bip32_derivation()))
.map(|addr| {
transparent_addr_is_ours(&network, tfvk, &addr, output.bip32_derivation())
})
.unwrap_or(false);
total_out += value;
outputs.push(PcztOutputSummary {
Expand Down
Loading
Loading