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
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
152 changes: 70 additions & 82 deletions crates/webzjs-keys/src/pczt_sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ pub async fn pczt_sign_inner(
},
}
let mut keys = BTreeMap::<zip32::AccountId, Vec<KeyRef>>::new();
let pczt = Verifier::new(pczt)
.with_orchard::<Infallible, _>(|bundle| {
for (index, action) in bundle.actions().iter().enumerate() {
if let Some(account_index) =
action
let pczt =
Verifier::new(pczt)
.with_orchard::<Infallible, _>(|bundle| {
for (index, action) in bundle.actions().iter().enumerate() {
if let Some(account_index) = action
.spend()
.zip32_derivation()
.as_ref()
Expand All @@ -78,21 +78,20 @@ pub async fn pczt_sign_inner(
zip32::ChildIndex::hardened(network.network_type().coin_type()),
)
})
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Orchard { index });
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Orchard { index });
}
}
}
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))?
.with_ironwood::<Infallible, _>(|bundle| {
// Ironwood reuses the Orchard action/key shape, so collect spendable
// Ironwood actions exactly as for Orchard (same zip32 derivation).
for (index, action) in bundle.actions().iter().enumerate() {
if let Some(account_index) =
action
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))?
.with_ironwood::<Infallible, _>(|bundle| {
// Ironwood reuses the Orchard action/key shape, so collect spendable
// Ironwood actions exactly as for Orchard (same zip32 derivation).
for (index, action) in bundle.actions().iter().enumerate() {
if let Some(account_index) = action
.spend()
.zip32_derivation()
.as_ref()
Expand All @@ -102,59 +101,59 @@ pub async fn pczt_sign_inner(
zip32::ChildIndex::hardened(network.network_type().coin_type()),
)
})
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Ironwood { index });
}
}
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))?
.with_sapling::<Infallible, _>(|bundle| {
for (index, spend) in bundle.spends().iter().enumerate() {
if let Some(account_index) =
spend.zip32_derivation().as_ref().and_then(|derivation| {
derivation.extract_account_index(
&seed_fp,
zip32::ChildIndex::hardened(network.network_type().coin_type()),
)
})
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Sapling { index });
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Ironwood { index });
}
}
}
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))?
.with_transparent::<Infallible, _>(|bundle| {
for (index, input) in bundle.inputs().iter().enumerate() {
for derivation in input.bip32_derivation().values() {
if let Some((account_index, scope, address_index)) = derivation
.extract_bip_44_fields(
&seed_fp,
bip32::ChildNumber(
network.network_type().coin_type()
| bip32::ChildNumber::HARDENED_FLAG,
),
)
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))?
.with_sapling::<Infallible, _>(|bundle| {
for (index, spend) in bundle.spends().iter().enumerate() {
if let Some(account_index) =
spend.zip32_derivation().as_ref().and_then(|derivation| {
derivation.extract_account_index(
&seed_fp,
zip32::ChildIndex::hardened(network.network_type().coin_type()),
)
})
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Transparent {
index,
scope,
address_index,
});
.push(KeyRef::Sapling { index });
}
}
}
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))?
.finish();
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))?
.with_transparent::<Infallible, _>(|bundle| {
for (index, input) in bundle.inputs().iter().enumerate() {
for derivation in input.bip32_derivation().values() {
if let Some((account_index, scope, address_index)) = derivation
.extract_bip_44_fields(
&seed_fp,
bip32::ChildNumber(
network.network_type().coin_type()
| bip32::ChildNumber::HARDENED_FLAG,
),
)
{
keys.entry(account_index)
.or_default()
.push(KeyRef::Transparent {
index,
scope,
address_index,
});
}
}
}
Ok(())
})
.map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))?
.finish();
let mut signer = Signer::new(pczt).unwrap();
//.map_err(|e| anyhow!("Failed to initialize Signer: {:?}", e))?;
for (_, spends) in keys {
Expand All @@ -168,10 +167,7 @@ pub async fn pczt_sign_inner(
&orchard::keys::SpendAuthorizingKey::from(usk.orchard()),
)
.map_err(|e| {
Error::PcztSign(format!(
"Failed to sign Orchard spend {index}: {:?}",
e
))
Error::PcztSign(format!("Failed to sign Orchard spend {index}: {e:?}"))
})?;
}
KeyRef::Ironwood { index } => {
Expand All @@ -182,20 +178,14 @@ pub async fn pczt_sign_inner(
&orchard::keys::SpendAuthorizingKey::from(usk.orchard()),
)
.map_err(|e| {
Error::PcztSign(format!(
"Failed to sign Ironwood spend {index}: {:?}",
e
))
Error::PcztSign(format!("Failed to sign Ironwood spend {index}: {e:?}"))
})?;
}
KeyRef::Sapling { index } => {
signer
.sign_sapling(index, &usk.sapling().expsk.ask)
.map_err(|e| {
Error::PcztSign(format!(
"Failed to sign Sapling spend {index}: {:?}",
e
))
Error::PcztSign(format!("Failed to sign Sapling spend {index}: {e:?}"))
})?;
}
KeyRef::Transparent {
Expand All @@ -210,15 +200,13 @@ pub async fn pczt_sign_inner(
.derive_secret_key(scope, address_index)
.map_err(|e| {
Error::PcztSign(format!(
"Failed to derive transparent key at .../{:?}/{:?}: {:?}",
scope, address_index, e,
"Failed to derive transparent key at .../{scope:?}/{address_index:?}: {e:?}"
))
})?,
)
.map_err(|e| {
Error::PcztSign(format!(
"Failed to sign transparent input {index}: {:?}",
e
"Failed to sign transparent input {index}: {e:?}"
))
})?;
}
Expand Down
Loading
Loading