### Running Hardhat Tasks (Shell) Source: https://github.com/sorasuegami/voice_recovery_circuit/blob/main/hardhat/README.md This snippet shows common commands to interact with a Hardhat project. These tasks include getting help, running tests, and deploying contracts. Ensure Hardhat is installed and configured in your project. ```shell npx hardhat help npx hardhat test REPORT_GAS=true npx hardhat test npx hardhat node npx hardhat run scripts/deploy.ts ``` -------------------------------- ### Generate ZK Circuit Setup Parameters (Rust CLI) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates trusted setup parameters for the ZK circuit using the Rust CLI. These parameters are essential for key generation and must be generated once beforehand. The `--k` parameter determines the circuit capacity (2^k) and influences memory usage. ```bash # Generate setup parameters with degree k (circuit size = 2^k) cargo run --release --bin voice_recovery -- gen-params \ --k 20 \ --params-path ./build/params/app.bin # The k parameter determines: # - Circuit capacity: 2^k rows # - Memory usage: ~2^k * 64 bytes # - Typical values: k=20 for testing, k=22-24 for production ``` -------------------------------- ### Generate ZK Proving and Verifying Keys (Rust CLI) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates proving and verifying keys from the previously generated setup parameters and circuit configuration using the Rust CLI. This step is necessary for creating and verifying ZK proofs. ```bash # This command is not provided in the input text, but would typically follow gen-params. # Example placeholder: # cargo run --release --bin voice_recovery -- gen-keys \ # --params-path ./build/params/app.bin \ # --proving-key-path ./build/keys/proving.key \ # --verifying-key-path ./build/keys/verifying.key ``` -------------------------------- ### Python Bindings - evm_prove Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Python wrapper for the Rust proof generation, allowing direct proof creation from a Python backend. ```APIDOC ## Python Bindings - evm_prove ### Description Python wrapper for the Rust proof generation, allowing direct proof creation from Python backend. ### Method `evm_prove` (Python function) ### Endpoint N/A (Python library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from voice_recovery_python import evm_prove # Generate EVM-compatible ZK proof evm_prove( params_dir="../build/params", app_circuit_config="../eth_voice_recovery/configs/test1_circuit.config", agg_circuit_config="../eth_voice_recovery/configs/agg_circuit.config", pk_dir="../build/pks", input_path="./storage/session123/input.json", proof_path="./storage/session123/proof.hex", public_input_path="./storage/session123/public.json" ) # Read the generated proof with open("./storage/session123/proof.hex", "r") as f: proof_hex = f.read() print(f"Proof bytes: {len(proof_hex) // 2 - 1} bytes") ``` ### Response #### Success Response (200) Generates an EVM-compatible ZK proof and saves it to the specified `proof_path`. Public inputs are saved to `public_input_path`. #### Response Example ``` Proof bytes: XXX bytes ``` ``` -------------------------------- ### Generate EVM Proof (Python) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Provides a Python wrapper for the Rust proof generation functionality, enabling direct creation of EVM-compatible ZK proofs from a Python backend. It takes various configuration paths and input/output file paths. ```python from voice_recovery_python import evm_prove # Generate EVM-compatible ZK proof evm_prove( params_dir="../build/params", app_circuit_config="../eth_voice_recovery/configs/test1_circuit.config", agg_circuit_config="../eth_voice_recovery/configs/agg_circuit.config", pk_dir="../build/pks", input_path="./storage/session123/input.json", proof_path="./storage/session123/proof.hex", public_input_path="./storage/session123/public.json" ) # Read the generated proof with open("./storage/session123/proof.hex", "r") as f: proof_hex = f.read() print(f"Proof bytes: {len(proof_hex) // 2 - 1} bytes") ``` -------------------------------- ### Python API: Generate ZK Proof for Voice Match Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt This Flask endpoint generates a Zero-Knowledge proof to verify that a provided voice sample matches a previously registered commitment within a specified error threshold. It takes the audio file and JSON data containing the original feature hash, fuzzy commitment, and a message (oldOwner || newOwner) as input. It then uses `recover` and `generate_proof` functions to compute the error vector and generate the EVM-compatible proof, returning various hashes, the recovered hash, the error code, the proof itself, and a session ID. ```python # Flask endpoint for ZK proof generation @app.route('/api/gen-proof', methods=['POST']) def gen_proof(): form_file = request.files['file'] new_feat = feat_bytearray_from_wav_blob(form_file) # Request format: # { # "hash_ecc": "0x...", # Feature hash from registration # "feat_xor_ecc": "0x...", # Commitment from registration # "msg": "0x..." # Message to sign (oldOwner || newOwner) # } json_data = json.loads(request.form['jsonData']) hash_ecc = hex_to_bytearray(json_data["hash_ecc"]) feat_xor_ecc = hex_to_bytearray(json_data["feat_xor_ecc"]) msg = hex_to_bytearray(json_data["msg"]) # Recover BCH codeword and compute error vector code_error, hash_ecc_msg, recovered_hash_ecc = recover( new_feat, feat_xor_ecc, hash_ecc, msg ) # Generate EVM-compatible ZK proof proof_succeed, proof_bin, session_id = generate_proof( new_feat, code_error, feat_xor_ecc, msg ) return jsonify({ "new_feat": bytearray_to_hex(new_feat), "recovered_hash_ecc": bytearray_to_hex(recovered_hash_ecc), "hash_ecc_msg": bytearray_to_hex(hash_ecc_msg), "code_error": bytearray_to_hex(code_error), "proof": bytearray_to_hex(proof_bin), "session_id": session_id, }) # Example curl request: # curl -X POST http://localhost:5000/api/gen-proof \ # -F "file=@recovery_voice.wav" \ # -F 'jsonData={"hash_ecc":"0x...","feat_xor_ecc":"0x...","msg":"0x9a8f43"}' ``` -------------------------------- ### Solidity Verifier Wrapper for ZK Proof Verification Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Wraps the auto-generated Halo2 verifier contract to handle public input formatting for on-chain ZK proof verification. It takes commitment hash, feature hash, message hash, the message itself, and the proof bytes as input. The public inputs are formatted, including packing message bytes into 128-bit chunks, before calling the underlying Verifier.verify function. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Verifier.sol"; contract VerifierWrapper is Verifier { uint maxMsgSize; constructor(uint _maxMsgSize) { maxMsgSize = _maxMsgSize; } // Verify a ZK proof with structured public inputs // Parameters: // commitmentHash: Hash of the fuzzy commitment // featureHash: Hash of the recovered BCH codeword // messageHash: Hash binding the recovery message // message: The encoded (oldOwner, newOwner) message // proof: Raw proof bytes from evm_prove function verify( bytes32 commitmentHash, bytes32 featureHash, bytes32 messageHash, bytes memory message, bytes memory proof ) public view returns (bool) { uint256[] memory pubInputs = new uint256[](3 + maxMsgSize); pubInputs[0] = uint256(commitmentHash); pubInputs[1] = uint256(featureHash); pubInputs[2] = uint256(messageHash); // Pack message bytes into 128-bit chunks bytes memory messageExt = abi.encodePacked( message, new bytes(maxMsgSize - message.length) ); for (uint i = 0; i < messageExt.length / 16; i++) { uint coeff = 1; for (uint j = 0; j < 16; j++) { pubInputs[3 + i] += coeff * uint256(uint8(messageExt[16 * i + j])); coeff = coeff << 8; } } return Verifier.verify(pubInputs, proof); } } ``` -------------------------------- ### Generate EVM Proof from Input Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Creates an EVM-compatible proof from a JSON input file containing voice biometric features, errors, and commitments. The generated proof can be submitted to an on-chain verifier. ```bash # Generate EVM proof from input.json cargo run --release --bin voice_recovery -- evm-prove \ --params-dir ./build/params \ --app-circuit-config ./eth_voice_recovery/configs/test1_circuit.config \ --agg-circuit-config ./eth_voice_recovery/configs/agg_circuit.config \ --pk-dir ./build/pks \ --input-path ./build/input.json \ --proof-path ./build/evm_proof.hex \ --public-input-path ./build/evm_public_input.json ``` -------------------------------- ### Generate Proving and Verifying Keys Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates the proving and verifying keys required for the voice recovery circuit. This process uses specified parameters and circuit configurations to create key files in designated directories. ```bash cargo run --release --bin voice_recovery -- gen-keys \ --params-dir ./build/params \ --app-circuit-config ./eth_voice_recovery/configs/test1_circuit.config \ --agg-circuit-config ./eth_voice_recovery/configs/agg_circuit.config \ --pk-dir ./build/pks \ --vk-path ./build/app.vk ``` -------------------------------- ### React Voice Registration Flow with Smart Contract Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt This snippet demonstrates how to register a user's voice with the VoiceKeyRecover smart contract using React. It connects to the Ethereum provider, sends the audio data to a backend API for feature extraction, and then calls the contract's register function with the extracted features. Dependencies include ethers.js and the contract's ABI. ```javascript import { ethers } from "ethers"; import VoiceKeyRecovery from "./contracts/VoiceKeyRecover.sol/VoiceKeyRecover.json"; const contractAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3"; const apiUrl = "http://127.0.0.1:5000"; async function registerVoice(audioBlob, walletAddress) { // 1. Connect to contract const provider = new ethers.providers.Web3Provider(window.ethereum); await provider.send("eth_requestAccounts", []); const signer = provider.getSigner(); const vk = new ethers.Contract(contractAddress, VoiceKeyRecovery.abi, signer); // 2. Extract voice features via backend const formData = new FormData(); formData.append("file", audioBlob, "recorded_audio.wav"); const response = await fetch(`${apiUrl}/api/feature-vector`, { method: "POST", body: formData }); const data = await response.json(); // 3. Register on-chain // data contains: hash_ecc, hash_feat_xor_ecc, feat_xor_ecc const tx = await vk.register( walletAddress, data.hash_ecc, // featureHash data.hash_feat_xor_ecc, // commitmentHash data.feat_xor_ecc // commitment bytes ); await tx.wait(); console.log("Voice registered successfully!"); return data; } // Usage with MediaRecorder: // const mediaRecorder = new MediaRecorder(stream); // mediaRecorder.ondataavailable = (e) => { // registerVoice(e.data, "0x1234...walletAddr"); // }; ``` -------------------------------- ### POST /api/gen-proof Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates a zero-knowledge proof that the provided voice sample matches the registered commitment within the BCH error correction threshold (64 bits). ```APIDOC ## POST /api/gen-proof ### Description Generates a zero-knowledge proof that the provided voice sample matches the registered commitment within the BCH error correction threshold (64 bits). ### Method `POST` ### Endpoint `/api/gen-proof` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (file) - Required - The audio file (e.g., WAV format) for which to generate the proof. - **jsonData** (string) - Required - A JSON string containing the following fields: - **hash_ecc** (string) - Hex-encoded hash of the error correction code from registration. - **feat_xor_ecc** (string) - Hex-encoded fuzzy commitment from registration. - **msg** (string) - Hex-encoded message to sign (e.g., oldOwner || newOwner). ### Request Example ```bash curl -X POST http://localhost:5000/api/gen-proof \ -F "file=@recovery_voice.wav" \ -F 'jsonData={"hash_ecc":"0x...","feat_xor_ecc":"0x...","msg":"0x9a8f43"}' ``` ### Response #### Success Response (200) - **new_feat** (string) - Hex-encoded bytearray of the new voice features. - **recovered_hash_ecc** (string) - Hex-encoded hash of the recovered BCH codeword. - **hash_ecc_msg** (string) - Hex-encoded hash of the message combined with the error correction code. - **code_error** (string) - Hex-encoded bytearray representing the code error. - **proof** (string) - Hex-encoded bytearray of the generated ZK proof. - **session_id** (string) - Identifier for the proof generation session. #### Response Example ```json { "new_feat": "0x...", "recovered_hash_ecc": "0x...", "hash_ecc_msg": "0x...", "code_error": "0x...", "proof": "0x...", "session_id": "some_session_id" } ``` ``` -------------------------------- ### Generate Proving and Verifying Keys Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates the proving and verifying keys required for the voice recovery circuit. These keys are essential for creating and verifying ZK proofs. ```APIDOC ## Generate Proving and Verifying Keys ### Description Generates the proving and verifying keys required for the voice recovery circuit. These keys are essential for creating and verifying ZK proofs. ### Method `cargo run --release --bin voice_recovery -- gen-keys` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Command Example ```bash cargo run --release --bin voice_recovery -- gen-keys \ --params-dir ./build/params \ --app-circuit-config ./eth_voice_recovery/configs/test1_circuit.config \ --agg-circuit-config ./eth_voice_recovery/configs/agg_circuit.config \ --pk-dir ./build/pks \ --vk-path ./build/app.vk ``` ### Response #### Success Response (200) Keys are generated and saved to the specified directories/files. #### Response Example N/A (Command-line output) ### Circuit Config Format (Example: test1_circuit.config) ```json { "degree": 20, "num_advice": 10, "num_lookup_advice": 1, "num_fixed": 1, "lookup_bits": 19, "error_threshold": 64, "word_size": 140, "max_msg_size": 48 } ``` ``` -------------------------------- ### Python Utility: Fuzzy Commitment with BCH Codes Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt This Python code snippet demonstrates the creation of a fuzzy commitment using voice features and BCH error-correcting codes. This technique allows for the recovery of the original commitment even if the voice features have slight variations, ensuring robustness. The function `fuzzy_commitment` is designed to be used within the backend API for voice registration. ```python import bchlib import os from convert import bytearray_to_hex ``` -------------------------------- ### VerifierWrapper.verify Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Wraps the auto-generated Halo2 verifier contract to handle public input formatting for on-chain ZK proof verification. It takes various hashes and the message, packs the message into 128-bit chunks, and then calls the underlying Verifier.verify function. ```APIDOC ## VerifierWrapper.verify ### Description Wraps the auto-generated Halo2 verifier contract to handle public input formatting for on-chain ZK proof verification. ### Method `verify` (public view function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **commitmentHash** (bytes32) - Required - Hash of the fuzzy commitment. - **featureHash** (bytes32) - Required - Hash of the recovered BCH codeword. - **messageHash** (bytes32) - Required - Hash binding the recovery message. - **message** (bytes memory) - Required - The encoded (oldOwner, newOwner) message. - **proof** (bytes memory) - Required - Raw proof bytes from evm_prove. ### Request Example ```solidity // Example usage within another contract or transaction VerifierWrapper wrapper = new VerifierWrapper(16); // Assuming maxMsgSize is 16 bool isValid = wrapper.verify( commitmentHash, featureHash, messageHash, message, proof ); ``` ### Response #### Success Response (200) - **bool** - `true` if the proof is valid, `false` otherwise. #### Response Example ```json // This is a Solidity function, so the return value is directly the boolean result. // If called via an external tool, it would be represented as: true ``` ``` -------------------------------- ### Python Bindings - poseidon_hash Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Computes the Poseidon hash, which is used throughout the protocol for commitment and feature hashing. ```APIDOC ## Python Bindings - poseidon_hash ### Description Computes the Poseidon hash used throughout the protocol for commitment and feature hashing. ### Method `poseidon_hash` (Python function) ### Endpoint N/A (Python library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from voice_recovery_python import poseidon_hash # Compute Poseidon hash of arbitrary bytes input_hex = "0x52ad6993e8ed48b87023fa32cb416c49b4e0b87c2c63a8ea8e68818c776d9e7f" output_hex = poseidon_hash(input_hex) print(f"Poseidon hash: {output_hex}") ``` ### Response #### Success Response (200) Returns the Poseidon hash as a hexadecimal string. #### Response Example ``` Poseidon hash: 0x1a2b3c4d... (32 bytes as hex) ``` ``` -------------------------------- ### React Voice Recovery Flow with Smart Contract Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt This snippet shows how to recover wallet access using voice authentication with the VoiceKeyRecover smart contract in React. It sends the audio and registration data to a backend to generate a ZK proof, optionally verifies the voice match locally, and then submits the recovery transaction to the contract. It requires ethers.js and the contract's ABI. ```javascript async function recoverWallet(audioBlob, walletAddress, registrationData) { const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); const vk = new ethers.Contract(contractAddress, VoiceKeyRecovery.abi, signer); // 1. Generate ZK proof via backend const formData = new FormData(); formData.append("file", audioBlob, "recovery_audio.wav"); formData.append("jsonData", JSON.stringify({ hash_ecc: registrationData.hash_ecc, feat_xor_ecc: registrationData.feat_xor_ecc, msg: "0x9a8f43" // Recovery message })); const response = await fetch(`${apiUrl}/api/gen-proof`, { method: "POST", body: formData }); const proofData = await response.json(); // 2. Verify voice match locally (optional) const errorBitCount = countOnes(proofData.code_error); if (errorBitCount > 64) { throw new Error(`Voice mismatch: ${errorBitCount} bit errors exceeds threshold`); } // 3. Submit recovery transaction const tx = await vk.recover( walletAddress, proofData.hash_ecc_msg, // messageHash proofData.proof // ZK proof bytes ); await tx.wait(); console.log("Wallet recovered successfully!"); } // Helper to count error bits function countOnes(hexString) { let ones = 0; for (let i = 2; i < hexString.length; i += 2) { let byte = parseInt(hexString.substr(i, 2), 16); while (byte !== 0) { ones += byte & 1; byte >>= 1; } } return ones; } ``` -------------------------------- ### BCH Configuration and Fuzzy Commitment Generation (Python) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Configures BCH error correction and generates a fuzzy commitment from a voice feature vector. The commitment is created by XORing the padded feature vector with an encoded secret. It also returns the Poseidon hash of the BCH codeword. ```python import bchlib import os BCH_POLYNOMIAL = 8219 BCH_BITS = 64 bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS) def fuzzy_commitment(feat_vec): """ Generate fuzzy commitment from voice feature vector. Args: feat_vec: Voice features as bytearray (256 bits from RawNet3) Returns: c: Commitment = feat_vec XOR (s || ecc(s)) h_w: Poseidon hash of the BCH codeword """ # Generate random secret s = bytearray(os.urandom(32)) # Encode with BCH error correction ecc = bch.encode(s) packet = s + ecc # 140 bytes total # Pad features to match packet length feat_vec = padding(feat_vec, len(packet)) # XOR to create commitment c = xor(feat_vec, packet) # Hash the codeword for verification h_w = my_hash(packet) return c, h_w # Example usage: # feat = feat_bytearray_from_wav_blob(audio_file) # commitment, feature_hash = fuzzy_commitment(feat) # print(f"Commitment: {bytearray_to_hex(commitment)}") # print(f"Feature Hash: {bytearray_to_hex(feature_hash)}") ``` -------------------------------- ### Generate EVM Verifier Contract Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates a Solidity verifier contract from the verifying key. This contract includes precomputed verification key points, KZG pairing check logic, and public input validation, ready for on-chain deployment. ```bash # Generate Verifier.sol from verifying key cargo run --release --bin voice_recovery -- gen-evm-verifier \ --params-dir ./build/params \ --app-circuit-config ./eth_voice_recovery/configs/test1_circuit.config \ --agg-circuit-config ./eth_voice_recovery/configs/agg_circuit.config \ --vk-path ./build/app.vk \ --code-path ./hardhat/contracts/Verifier.sol ``` -------------------------------- ### Recover Wallet Ownership with ZK Proof (Solidity) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Transfers wallet ownership to a new address by verifying a zero-knowledge proof. The proof confirms that the caller's voice matches the registered voice biometrics within an acceptable error threshold. This function requires the wallet address to recover, a message hash for replay protection, and the EVM-compatible ZK proof bytes. ```Solidity // Recover wallet ownership using ZK proof of voice authentication // Parameters: // walletAddr: The wallet address to recover // messageHash: Hash of (oldOwner, newOwner, word) for replay protection // proof: The EVM-compatible ZK proof bytes function recover( address walletAddr, bytes32 messageHash, bytes calldata proof ) public { require(isRegistered[walletAddr], "The wallet is not registered"); require(!usedMessageHashes[messageHash], "Message hash already used"); VoiceData memory voiceData = voiceDataOfWallet[walletAddr]; address oldOwner = voiceData.owner; address newOwner = msg.sender; bytes memory message = abi.encodePacked(oldOwner, newOwner); require( VerifierWrapper.verify( voiceData.commitmentHash, voiceData.featureHash, messageHash, message, proof ), "invalid proof" ); usedMessageHashes[messageHash] = true; voiceDataOfWallet[walletAddr].owner = newOwner; } // Example usage: // await vk.recover( // "0x1234...wallet", // "0xabc...messageHash", // "0x123456...proofBytes" // ); ``` -------------------------------- ### Python Utilities - fuzzy_commitment Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Creates a fuzzy commitment from voice features using BCH error-correcting codes. This enables recovery even when the voice features have minor differences. ```APIDOC ## fuzzy_commitment ### Description Creates a fuzzy commitment from voice features using BCH error-correcting codes. This enables recovery even when the voice features have minor differences. ### Parameters - **features** (bytearray) - The voice features to commit. ### Returns - **tuple** - A tuple containing: - **feat_xor_ecc** (bytearray) - The fuzzy commitment. - **hash_ecc** (bytearray) - The hash of the error correction code. ### Example ```python import bchlib import os from convert import bytearray_to_hex # Assuming bchlib and convert are available # Placeholder for actual implementation details def fuzzy_commitment(features): # This is a conceptual representation. Actual implementation would involve: # 1. Initializing BCH encoder with appropriate parameters (e.g., n, m, t) # 2. Encoding the features to get the BCH codeword. # 3. Generating a random secret 's'. # 4. Computing ecc(s) - an error correction code applied to 's'. # 5. Computing feat_xor_ecc = features XOR (s || ecc(s)). # 6. Computing hash_ecc = hash(ecc(s)). # Dummy values for illustration: feat_xor_ecc = bytearray(os.urandom(32)) hash_ecc = bytearray(os.urandom(32)) return feat_xor_ecc, hash_ecc # Example usage: # voice_features = bytearray([...]) # feat_xor_ecc, hash_ecc = fuzzy_commitment(voice_features) # print(f"Fuzzy Commitment: {bytearray_to_hex(feat_xor_ecc)}") # print(f"ECC Hash: {bytearray_to_hex(hash_ecc)}") ``` ``` -------------------------------- ### Calculate Voice Feature Vector using RawNet3 (Python) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Extracts a 256-dimensional binary voice feature vector from audio using the RawNet3 speaker recognition model. It loads a pre-trained model, extracts speaker embeddings, and then binarizes the output based on positive or negative values. ```python from machine_learning.RawNet3.models import RawNet3 from machine_learning.RawNet3.infererence import extract_speaker_embd import torch import numpy as np def calc_feat_vec(audio, sample_rate): """ Extract binary voice features from audio. Args: audio: Audio waveform as numpy array sample_rate: Sample rate of the audio Returns: binary_vec: 256-bit binary feature vector """ # Load pre-trained RawNet3 model torch_model = RawNet3.MainModel( encoder_type="ECA", nOut=256, out_bn=False, sinc_stride=10, log_sinc=True, norm_sinc="mean", grad_mult=1 ) torch_model.load_state_dict( torch.load("machine_learning/RawNet3/models/weights/model.pt", map_location=lambda storage, loc: storage)["model"] ) torch_model.eval() # Extract speaker embedding output = extract_speaker_embd( torch_model, audio, sample_rate, n_samples=48000, n_segments=10, gpu=False, ).mean(0) # Binarize: positive values -> 1, negative -> 0 binary_vec = np.where(output > 0, 1, 0) return binary_vec # Example usage: # import soundfile # audio, sr = soundfile.read("voice.wav") # features = calc_feat_vec(audio, sr) # feat_bytes = bytearray(np.packbits(features)) ``` -------------------------------- ### POST /api/feature-vector Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Extracts voice features from an audio file and generates the fuzzy commitment data needed for registration. Returns the feature hash, commitment, and commitment hash. ```APIDOC ## POST /api/feature-vector ### Description Extracts voice features from an audio file and generates the fuzzy commitment data needed for registration. Returns the feature hash, commitment, and commitment hash. ### Method `POST` ### Endpoint `/api/feature-vector` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (file) - Required - The audio file (e.g., WAV format) to process. ### Request Example ```bash curl -X POST http://localhost:5000/api/feature-vector \ -F "file=@recording.wav" ``` ### Response #### Success Response (200) - **feat** (string) - Hex-encoded bytearray of the extracted voice features. - **hash_ecc** (string) - Hex-encoded hash of the error correction code. - **hash_feat_xor_ecc** (string) - Hex-encoded hash of the fuzzy commitment. - **feat_xor_ecc** (string) - Hex-encoded bytearray of the fuzzy commitment. #### Response Example ```json { "feat": "0x52ad6993e8ed48b87023fa32...", "hash_ecc": "0xb577b007bd3c08abfb74aa19...", "hash_feat_xor_ecc": "0x7dcaa671ca4df240d277ffde...", "feat_xor_ecc": "0xb577b007bd3c08abfb74aa19..." } ``` ``` -------------------------------- ### EVM Proof Generation Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates an EVM-compatible proof from voice biometric inputs. This proof can be submitted to the on-chain verifier. ```APIDOC ## EVM Proof Generation ### Description Generates an EVM-compatible proof from voice biometric inputs. The proof can be submitted to the on-chain verifier. ### Method `cargo run --release --bin voice_recovery -- evm-prove` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Command Example ```bash # Generate EVM proof from input.json cargo run --release --bin voice_recovery -- evm-prove \ --params-dir ./build/params \ --app-circuit-config ./eth_voice_recovery/configs/test1_circuit.config \ --agg-circuit-config ./eth_voice_recovery/configs/agg_circuit.config \ --pk-dir ./build/pks \ --input-path ./build/input.json \ --proof-path ./build/evm_proof.hex \ --public-input-path ./build/evm_public_input.json ``` ### Request Example (input.json) ```json { "features": "0x52ad6993e8ed48b87023fa32...", "errors": "0x02000401080080007000040030...", "commitment": "0xb577b007bd3c08abfb74aa19...", "message": "0xf39fd6e51aad88f6f4ce6ab8..." } ``` ### Response #### Success Response (200) An EVM-compatible proof is generated and saved to the specified `proof-path`. Public inputs are saved to `public-input-path`. #### Response Example (evm_public_input.json) ```json { "commitment": "0x...", "commitment_hash": "0x...", "message": "0x...", "feature_hash": "0x...", "message_hash": "0x..." } ``` ``` -------------------------------- ### Python API: Extract Voice Features and Generate Commitment Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt This Flask endpoint extracts voice features from an uploaded WAV file and generates the necessary fuzzy commitment data for registration. It utilizes `fuzzy_commitment` and `my_hash` from utility functions to compute feature hashes and commitments. The response includes the raw feature data, hash of the error correction code, hash of the XORed commitment, and the fuzzy commitment itself, all in hexadecimal format. ```python # Flask endpoint for voice feature extraction from flask import Flask, jsonify, request from utils import fuzzy_commitment, my_hash from convert import bytearray_to_hex, feat_bytearray_from_wav_blob @app.route('/api/feature-vector', methods=['POST']) def feat_vec(): form_file = request.files['file'] feat = feat_bytearray_from_wav_blob(form_file) # Generate fuzzy commitment: c = feat XOR (s || ecc(s)) feat_xor_ecc, hash_ecc = fuzzy_commitment(feat) hash_feat_xor_ecc = my_hash(feat_xor_ecc) return jsonify({ "feat": bytearray_to_hex(feat), "hash_ecc": bytearray_to_hex(hash_ecc), "hash_feat_xor_ecc": bytearray_to_hex(hash_feat_xor_ecc), "feat_xor_ecc": bytearray_to_hex(feat_xor_ecc), }) # Example curl request: # curl -X POST http://localhost:5000/api/feature-vector \ # -F "file=@recording.wav" # # Response: # { # "feat": "0x52ad6993e8ed48b87023fa32...", # "hash_ecc": "0xb577b007bd3c08abfb74aa19...", # "hash_feat_xor_ecc": "0x7dcaa671ca4df240d277ffde...", # "feat_xor_ecc": "0xb577b007bd3c08abfb74aa19..." # } ``` -------------------------------- ### Generate EVM Verifier Contract Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Generates a Solidity verifier contract from the verifying key. This contract can be deployed on-chain to verify proofs. ```APIDOC ## Generate EVM Verifier Contract ### Description Generates a Solidity verifier contract from the verifying key. This contract is deployed on-chain to verify proofs. ### Method `cargo run --release --bin voice_recovery -- gen-evm-verifier` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Command Example ```bash # Generate Verifier.sol from verifying key cargo run --release --bin voice_recovery -- gen-evm-verifier \ --params-dir ./build/params \ --app-circuit-config ./eth_voice_recovery/configs/test1_circuit.config \ --agg-circuit-config ./eth_voice_recovery/configs/agg_circuit.config \ --vk-path ./build/app.vk \ --code-path ./hardhat/contracts/Verifier.sol ``` ### Response #### Success Response (200) A Solidity verifier contract (`Verifier.sol`) is generated and saved to the specified `code-path`. #### Response Example The generated `Verifier.sol` contains: - Precomputed verification key points - KZG pairing check logic - Public input validation ``` -------------------------------- ### Register Wallet Address with Voice Data (Solidity) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Registers a wallet address with its associated voice biometric commitment and feature hashes on the blockchain. This function stores on-chain references to private voice data, enabling future recovery operations. It requires the wallet address, feature hash, commitment hash, and the raw commitment bytes. ```Solidity // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; // Register voice data for wallet recovery // Parameters: // walletAddr: The wallet address to register // featureHash: Poseidon hash of the BCH-encoded voice features // commitmentHash: Hash of the fuzzy commitment (feat XOR ecc) // commitment: The raw commitment bytes for recovery verification contract VoiceKeyRecover { struct VoiceData { address owner; bytes32 featureHash; bytes32 commitmentHash; bytes commitment; } mapping(address => bool) public isRegistered; mapping(address => VoiceData) public voiceDataOfWallet; function register( address walletAddr, bytes32 featureHash, bytes32 commitmentHash, bytes calldata commitment ) public { require(!isRegistered[walletAddr], "already registered"); voiceDataOfWallet[walletAddr] = VoiceData( msg.sender, featureHash, commitmentHash, commitment ); isRegistered[walletAddr] = true; } } // Example usage with ethers.js: // const vk = new ethers.Contract(contractAddress, VoiceKeyRecoveryABI, signer); // await vk.register( // "0x1234...wallet", // "0xabc...featureHash", // "0xdef...commitmentHash", // "0x123...commitment" // ); ``` -------------------------------- ### Compute Poseidon Hash (Python) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Computes the Poseidon hash of arbitrary bytes, a function used for commitment and feature hashing within the protocol. It takes a hexadecimal string as input and returns the hash as a hexadecimal string. ```python from voice_recovery_python import poseidon_hash # Compute Poseidon hash of arbitrary bytes input_hex = "0x52ad6993e8ed48b87023fa32cb416c49b4e0b87c2c63a8ea8e68818c776d9e7f" output_hex = poseidon_hash(input_hex) print(f"Poseidon hash: {output_hex}") ``` -------------------------------- ### Recover BCH Codeword (Python) Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Recovers the original BCH codeword from new voice features and a stored commitment. It uses BCH error correction to handle minor voice differences and verifies the recovered hash against the original. The function returns the error vector, the hash of the message concatenated with the recovered word, and the hash of the recovered word. ```python def recover(feat_vec, c, h_w, m): """ Recover BCH codeword from voice features and commitment. Args: feat_vec: New voice features (bytearray) c: Stored commitment from registration h_w: Original feature hash for verification m: Message to bind (oldOwner || newOwner) Returns: e: Error vector (difference between voices) h_m_w: Hash of message concatenated with recovered word recovered_h_w: Hash of recovered word for verification """ assert len(c) >= len(feat_vec) # Pad features to commitment length feat_vec = padding(feat_vec, len(c)) # XOR to get noisy codeword: w' = feat' XOR c w1 = xor(feat_vec, c) # Apply BCH error correction to recover original codeword w = bch_error_correction(w1) # Compute error vector (must have Hamming weight <= 64) e = xor(w, w1) # Hash message with recovered word for signing h_m_w = my_hash(m + w) # Verify recovered hash matches original recovered_h_w = my_hash(w) return e, h_m_w, recovered_h_w # Example usage: # new_feat = feat_bytearray_from_wav_blob(new_audio) # error, msg_hash, recovered_hash = recover( # new_feat, # commitment_from_chain, # feature_hash_from_chain, # message_bytes # ) # assert recovered_hash == feature_hash_from_chain # Voice matches! ``` -------------------------------- ### VoiceKeyRecover.recover Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Transfers wallet ownership to a new address by verifying a zero-knowledge proof. This proof confirms that the caller's voice matches the registered voice biometrics within the allowed error threshold. ```APIDOC ## POST /recover ### Description Transfers wallet ownership to a new address by verifying a zero-knowledge proof that the caller's voice matches the registered voice biometrics within the error threshold. ### Method POST ### Endpoint `/recover` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **walletAddr** (address) - Required - The wallet address to recover - **messageHash** (bytes32) - Required - Hash of (oldOwner, newOwner, word) for replay protection - **proof** (bytes) - Required - The EVM-compatible ZK proof bytes ### Request Example ```json { "walletAddr": "0x1234...wallet", "messageHash": "0xabc...messageHash", "proof": "0x123456...proofBytes" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful recovery. #### Response Example ```json { "status": "Wallet ownership recovered successfully" } ``` ``` -------------------------------- ### VoiceKeyRecover.register Source: https://context7.com/sorasuegami/voice_recovery_circuit/llms.txt Registers a wallet address with voice biometric data. This function stores commitment and feature hashes on the blockchain, while the actual voice data remains private. ```APIDOC ## POST /register ### Description Registers a wallet address with voice biometric data. The commitment hash and feature hash are stored on-chain while the actual voice data remains private. ### Method POST ### Endpoint `/register` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **walletAddr** (address) - Required - The wallet address to register - **featureHash** (bytes32) - Required - Poseidon hash of the BCH-encoded voice features - **commitmentHash** (bytes32) - Required - Hash of the fuzzy commitment (feat XOR ecc) - **commitment** (bytes) - Required - The raw commitment bytes for recovery verification ### Request Example ```json { "walletAddr": "0x1234...wallet", "featureHash": "0xabc...featureHash", "commitmentHash": "0xdef...commitmentHash", "commitment": "0x123...commitment" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful registration. #### Response Example ```json { "status": "Registration successful" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.