Zkapps(零知识应用)是由零知识证明支持的 mina 协议智能合约,特别是 zk-Snarks [零知识简洁非交互式知识论证]。zkapps 取代了 snapps [智能非交互式知识论证]应用]。 ZkApp 智能合约是使用 o1js(一个 TypeScript 库)编写的。 zkApps 在用户的 Web 浏览器中运行客户端,并仅发布一个小的有效性证明,然后由 Mina 节点进行验证。 Zkapp 由智能合约和 UI 组成,我将在下一节中进一步描述。
我创建了关于年龄验证的 zkapp,其中用户年龄在不干预个人数据的情况下得到验证。
我继续安装 zkapp-cli npm 包,它实际上创建了用于继续使用证明器函数和验证器函数的模板,作为 zk 证明构建过程的一部分
下面是添加验证自定义逻辑的实现。它定义了 zk-SNARK 的电路逻辑,在证明生成过程中使用。实际的证明者函数由 o1js 库管理,并在使用私有输入在链外执行 zkApp 方法时调用。
import { Field, SmartContract, state, State, method } from 'o1js'; /** * Private Age Verification Contract * The contract will verify if the user's age is greater than or equal to the threshold age. * The contract uses zero-knowledge proofs to keep the user's age private. */ export class AgeVerification extends SmartContract { // State variable to store the verification result (valid or invalid) @state(Field) valid = State<Field>(); // Method to initialize the state init() { super.init(); this.valid.set(Field(0)); // Default is invalid } // Method to verify the age @method async verifyAge(age: Field, threshold: Field) { // Compute age - threshold const difference = age.sub(threshold); // Use circuit-compatible logic to check if the difference is non-negative const isValid = difference.equals(Field(0)).or(difference.greaterThanOrEqual(Field(0))) ? Field(1) : Field(0); // Set the validity of the verification result this.valid.set(isValid); } }
以下脚本是与 AgeVerification zkApp 交互的测试套件。它在 txn.prove() 期间调用证明者逻辑,并通过检查其更新状态来验证 zkApp 的行为。
实际的证明者功能位于底层的 zkApp 方法(verifyAge)中,txn.prove() 是在测试过程中生成证明的机制。
为了测试输入,我编辑了测试脚本,如下所示。
import { AccountUpdate, Field, Mina, PrivateKey, PublicKey } from 'o1js'; import { AgeVerification } from './AgeVerification'; // Import the correct contract let proofsEnabled = false; describe('AgeVerification', () => { let deployerAccount: Mina.TestPublicKey, deployerKey: PrivateKey, senderAccount: Mina.TestPublicKey, senderKey: PrivateKey, zkAppAddress: PublicKey, zkAppPrivateKey: PrivateKey, zkApp: AgeVerification; // Update to use AgeVerification instead of Add beforeAll(async () => { if (proofsEnabled) await AgeVerification.compile(); // Update compile for AgeVerification }); beforeEach(async () => { const Local = await Mina.LocalBlockchain({ proofsEnabled }); Mina.setActiveInstance(Local); [deployerAccount, senderAccount] = Local.testAccounts; let feePayer = Local.testAccounts[0].key; deployerKey = deployerAccount.key; senderKey = senderAccount.key; zkAppPrivateKey = PrivateKey.random(); zkAppAddress = zkAppPrivateKey.toPublicKey(); zkApp = new AgeVerification(zkAppAddress); // Instantiate AgeVerification contract }); async function localDeploy() { const txn = await Mina.transaction(deployerAccount, async () => { AccountUpdate.fundNewAccount(deployerAccount); await zkApp.deploy(); }); await txn.prove(); // this tx needs .sign(), because `deploy()` adds an account update that requires signature authorization await txn.sign([deployerKey, zkAppPrivateKey]).send(); } it('generates and deploys the `AgeVerification` smart contract', async () => { await localDeploy(); const valid = zkApp.valid.get(); // Access the 'valid' state variable expect(valid).toEqual(Field(0)); // Initially, the contract should set 'valid' to Field(0) }); it('correctly verifies the age in the `AgeVerification` smart contract', async () => { await localDeploy(); const age = Field(25); // Example age value const threshold = Field(18); // Example threshold value // Call the verifyAge method const txn = await Mina.transaction(senderAccount, async () => { await zkApp.verifyAge(age, threshold); // Use the verifyAge method }); await txn.prove(); await txn.sign([senderKey]).send(); const valid = zkApp.valid.get(); // Check the validity state after verification expect(valid).toEqual(Field(1)); // Expected to be valid if age >= threshold }); });
以下是测试结果
我在interact.ts文件中添加了证明者机制,它基本上生成一个zk-SNARK证明,并在mina区块链中进行交易时提交证明。当 interact.ts 脚本生成证明时,验证是在处理交易时由 Mina 区块链执行的。这是 zk-SNARK 系统的一个关键方面,证明者生成验证者(Mina 网络)检查的证明。
import fs from 'fs/promises'; import { Mina, NetworkId, PrivateKey, Field } from 'o1js'; import { AgeVerification } from './AgeVerification'; // check command line arg let deployAlias = process.argv[2]; if (!deployAlias) throw Error(`Missing <deployAlias> argument. Usage: node build/src/interact.js <deployAlias> `); Error.stackTraceLimit = 1000; const DEFAULT_NETWORK_ID = 'testnet'; // parse config and private key from file type Config = { deployAliases: Record< string, { networkId?: string; url: string; keyPath: string; fee: string; feepayerKeyPath: string; feepayerAlias: string; } >; }; let configJson: Config = JSON.parse(await fs.readFile('config.json', 'utf8')); let config = configJson.deployAliases[deployAlias]; let feepayerKeysBase58: { privateKey: string; publicKey: string } = JSON.parse( await fs.readFile(config.feepayerKeyPath, 'utf8') ); let zkAppKeysBase58: { privateKey: string; publicKey: string } = JSON.parse( await fs.readFile(config.keyPath, 'utf8') ); let feepayerKey = PrivateKey.fromBase58(feepayerKeysBase58.privateKey); let zkAppKey = PrivateKey.fromBase58(zkAppKeysBase58.privateKey); // set up Mina instance and contract we interact with const Network = Mina.Network({ // We need to default to the testnet networkId if none is specified for this deploy alias in config.json // This is to ensure the backward compatibility. networkId: (config.networkId ?? DEFAULT_NETWORK_ID) as NetworkId, mina: config.url, }); const fee = Number(config.fee) * 1e9; // in nanomina (1 billion = 1.0 mina) Mina.setActiveInstance(Network); let feepayerAddress = feepayerKey.toPublicKey(); let zkAppAddress = zkAppKey.toPublicKey(); let zkApp = new AgeVerification(zkAppAddress); let age = Field(25); // Example age let threshold = Field(18); // Example threshold age // compile the contract to create prover keys console.log('compile the contract...'); await AgeVerification.compile(); try { // call verifyAge() and send transaction console.log('build transaction and create proof...'); let tx = await Mina.transaction( { sender: feepayerAddress, fee }, async () => { await zkApp.verifyAge(age, threshold); // Replacing update() with verifyAge } ); await tx.prove(); console.log('send transaction...'); const sentTx = await tx.sign([feepayerKey]).send(); if (sentTx.status === 'pending') { console.log( '\nSuccess! Age verification transaction sent.\n' + '\nYour smart contract state will be updated' + `\nas soon as the transaction is included in a block:` + `\n${getTxnUrl(config.url, sentTx.hash)}` ); } } catch (err) { console.log(err); } function getTxnUrl(graphQlUrl: string, txnHash: string | undefined) { const hostName = new URL(graphQlUrl).hostname; const txnBroadcastServiceName = hostName .split('.') .filter((item) => item === 'minascan')?.[0]; const networkName = graphQlUrl .split('/') .filter((item) => item === 'mainnet' || item === 'devnet')?.[0]; if (txnBroadcastServiceName && networkName) { return `https://minascan.io/${networkName}/tx/${txnHash}?type=zk-tx`; } return `Transaction hash: ${txnHash}`; }
我使用的年龄和阈值输入为 25 和 18。
由于测试已通过运行 npm run test 成功完成。我继续使用 zk config 在 devnet 上进行部署
我提供了以下输入:
部署别名:test
网络类型:测试网
网址:https://api.minascan.io/node/devnet/v1/graphql
付费者:新的付费者密钥
交易:0.1
可以从这里检索 URL:
然后在部署后我得到了以下响应。
合约部署在以下devnet
部署后,我继续使用 UI,通过提供 RPC URL 和部署的合约地址,选择简单的 html、css 和 js,这是最终的 UI。
将智能合约与UI集成后zkapp的创建就完成了。在为 AgeVerification zkApp 构建用户界面 (UI) 后,前端与智能合约的集成允许用户与零知识证明系统无缝交互。 UI 有助于向合约提交用户年龄和阈值数据,同时通过 zk-SNARK 维护隐私。这使得用户能够在不透露实际值的情况下验证自己的年龄,从而保持机密性。后端利用证明者功能生成证明,Mina 区块链对其进行有效验证。这种端到端解决方案可确保安全、用户友好的体验,同时充分利用 Mina 基于 zk-SNARK 的架构提供的隐私和可扩展性功能。
以上是探索 Mina 协议:zk 应用程序的实际用例的详细内容。更多信息请关注PHP中文网其他相关文章!