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
17 changes: 17 additions & 0 deletions Cargo.lock

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

14 changes: 14 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,17 @@ opt-level = 'z' # Optimize for size.
lto = true # Enable Link Time Optimization.
panic = "abort"
debug = false

# ProveKit has an additional `pattern` in the Whir R1CS proof which is used in debugging builds,
# because this isn't serialized, we explicitly remove it here as WalletKit only uses serialized proofs.
[profile.dev.package.provekit-common]
debug-assertions = false

[profile.dev.package.provekit-whir]
debug-assertions = false

[profile.dev.package.provekit-verifier]
debug-assertions = false

[profile.dev.package.provekit-prover]
debug-assertions = false
2 changes: 2 additions & 0 deletions walletkit-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ path = "src/main.rs"
[dependencies]
walletkit-core = { workspace = true, features = ["issuers", "embed-zkeys"] }
world-id-core = { workspace = true }
world-id-proof = { workspace = true, features = ["zk-ownership-verify"] }
alloy = { version = "2", default-features = false, features = ["contract", "json", "getrandom", "signer-local"] }
base64 = "0.22"
ciborium = "0.2"
clap = { version = "4", features = ["derive", "env"] }
dirs = "6"
eyre = "0.6"
Expand Down
79 changes: 75 additions & 4 deletions walletkit-cli/src/commands/proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,17 @@ use std::time::{SystemTime, UNIX_EPOCH};
use alloy::providers::ProviderBuilder;
use alloy::signers::{local::PrivateKeySigner, SignerSync};
use alloy::sol;
use base64::{prelude::BASE64_URL_SAFE_NO_PAD, Engine as _};
use clap::Subcommand;
use eyre::WrapErr as _;
use rand::rngs::OsRng;
use walletkit_core::requests::ProofRequest;
use world_id_core::primitives::{rp::RpId, FieldElement};
use world_id_core::primitives::{rp::RpId, FieldElement, OwnershipProof};
use world_id_core::requests::{
ProofRequest as CoreProofRequest, ProofResponse as CoreProofResponse, RequestItem,
RequestVersion,
};
use world_id_proof::ownership_proof::verify_ownership_proof;

use crate::output;

Expand Down Expand Up @@ -93,6 +95,18 @@ pub enum ProofCommand {
#[arg(long, default_value = "test_signal")]
signal: String,
},
/// Verify a WIP-103 ownership proof from a base64-encoded file.
VerifyOwnership {
/// Path to a file containing the base64url-encoded ownership proof, or `-` for stdin.
#[arg(long)]
proof: String,
/// Nonce used when generating the proof, as a 32-byte hex field element (with optional `0x` prefix).
#[arg(long)]
nonce: String,
/// Credential `sub` (commitment) the proof claims ownership of, as a 32-byte hex field element.
#[arg(long)]
sub: String,
},
}

fn read_file_or_stdin(path: &str) -> eyre::Result<String> {
Expand Down Expand Up @@ -248,12 +262,15 @@ fn print_verify_items_human(results: &[VerifyItemResult]) {
for r in results {
if r.verified {
println!(
" [PASS] {} (issuer_schema_id={})",
r.identifier, r.issuer_schema_id
" {} {} (issuer_schema_id={})",
output::pass_label(),
r.identifier,
r.issuer_schema_id
);
} else {
println!(
" [FAIL] {} (issuer_schema_id={}): {}",
" {} {} (issuer_schema_id={}): {}",
output::fail_label(),
r.identifier,
r.issuer_schema_id,
r.error.as_deref().unwrap_or("unknown")
Expand Down Expand Up @@ -459,6 +476,57 @@ async fn run_test(cli: &Cli, signal: &str) -> eyre::Result<()> {
Ok(())
}

fn parse_field_element(value: &str, label: &str) -> eyre::Result<FieldElement> {
value.trim().parse::<FieldElement>().wrap_err_with(|| {
format!("invalid {label}: expected 32-byte hex field element")
})
}

fn run_verify_ownership(
cli: &Cli,
proof_path: &str,
nonce: &str,
sub: &str,
) -> eyre::Result<()> {
let b64 = read_file_or_stdin(proof_path)?;
let bytes = BASE64_URL_SAFE_NO_PAD
.decode(b64.trim())
.wrap_err("invalid base64 ownership proof")?;
let proof: OwnershipProof = ciborium::from_reader(&bytes[..])
.wrap_err("failed to decode ownership proof CBOR")?;

let nonce_fe = parse_field_element(nonce, "--nonce")?;
let sub_fe = parse_field_element(sub, "--sub")?;

let result = verify_ownership_proof(&proof, nonce_fe, sub_fe);
let merkle_root = proof.merkle_root.to_string();

if cli.json {
output::print_json_data(
&serde_json::json!({
"verified": result.is_ok(),
"merkle_root": merkle_root,
"error": result.as_ref().err().map(|e| format!("{e:#}")),
}),
true,
);
} else if let Err(ref err) = result {
println!(
"{} ownership proof verification failed: {err:#}",
output::fail_label()
);
println!(" merkle_root: {merkle_root}");
} else {
println!("{} ownership proof verified", output::pass_label());
println!(" merkle_root: {merkle_root}");
}

if result.is_err() {
std::process::exit(1);
}
Ok(())
}

pub async fn run(cli: &Cli, action: &ProofCommand) -> eyre::Result<()> {
match action {
ProofCommand::Generate { request, now } => {
Expand All @@ -476,5 +544,8 @@ pub async fn run(cli: &Cli, action: &ProofCommand) -> eyre::Result<()> {
verifier_address,
} => run_verify(cli, request, response, verifier_address.as_deref()).await,
ProofCommand::Test { signal } => run_test(cli, signal).await,
ProofCommand::VerifyOwnership { proof, nonce, sub } => {
run_verify_ownership(cli, proof, nonce, sub)
}
}
}
26 changes: 26 additions & 0 deletions walletkit-cli/src/output.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
//! Output formatting helpers for human-readable and JSON modes.

use std::io::IsTerminal as _;

const GREEN: &str = "\x1b[32m";
const RED: &str = "\x1b[31m";
const RESET: &str = "\x1b[0m";

fn colorize(label: &str, color: &str) -> String {
if std::io::stdout().is_terminal() {
format!("{color}{label}{RESET}")
} else {
label.to_string()
}
}

/// Returns `[PASS]` colored green when stdout is a TTY, otherwise plain.
#[must_use]
pub fn pass_label() -> String {
colorize("[PASS]", GREEN)
}

/// Returns `[FAIL]` colored red when stdout is a TTY, otherwise plain.
#[must_use]
pub fn fail_label() -> String {
colorize("[FAIL]", RED)
}

/// Prints a raw JSON value wrapped in the standard envelope.
pub fn print_json_data(data: &serde_json::Value, json: bool) {
if json {
Expand Down
Loading