国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ ウェブフロントエンド jsチュートリアル mina プロトコルの探索: zk アプリケーションの実用的な使用例

mina プロトコルの探索: zk アプリケーションの実用的な使用例

Dec 29, 2024 am 07:32 AM

Zkapps (ゼロ知識(shí)アプリケーション) は、ゼロ知識(shí)証明、具體的には zk-Snarks [ゼロ知識(shí)の簡(jiǎn)潔な非対話型知識(shí)引數(shù)] を利用した mina プロトコル スマート コントラクトです。zkapps は snapps [スマート非対話型知識(shí)引數(shù)] に置き換えられました。アプリケーション]。 ZkApp スマート コントラクトは、o1js (TypeScript ライブラリ) を使用して作成されます。 zkApps はユーザーの Web ブラウザでクライアント側(cè)を?qū)g行し、小さな有効性証明のみを公開し、その後、Mina ノードによって検証されます。 Zkapp はスマート コントラクトと UI で構(gòu)成されており、これについては次のセクションで詳しく説明します。

応用

個(gè)人データを介さずにユーザーの年齢を検証する年齢認(rèn)証に関する zkapp を作成しました。

zkapp-cli npm パッケージのインストールに進(jìn)み、zk 証明ビルド プロセスの一部として証明者機(jī)能と検証者機(jī)能を続行するためのテンプレートを?qū)g際に作成しました

実裝

以下は検証カスタムロジックを追加する実裝です。これは、プルーフ生成中に使用される zk-SNARK の回路ロジックを定義します。実際の証明者関數(shù)は 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() 中に証明者ロジックを呼び出し、更新された狀態(tài)をチェックすることで zkApp の動(dòng)作を検証します。

実際の証明者関數(shù)は基礎(chǔ)となる 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
  });
});


以下はテスト結(jié)果です

Exploring the Mina Protocol: Practical Use Cases for zk Applications

interact.ts ファイルに証明者メカニズムを追加しました。これは基本的に zk-SNARK 証明を生成し、mina ブロックチェーンでのトランザクションに移行するときに証明を送信します。 interact.ts スクリプトが証明を生成する間、検証はトランザクションの処理時(shí)に Min ブロックチェーンによって実行されます。これは、証明者が検証者 (Mina ネットワーク) がチェックする証明を生成するという zk-SNARK システムの重要な側(cè)面です。

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 を?qū)g行することでテストが正常に完了したため。 zk config

を使用して devnet へのデプロイを進(jìn)めました。

ここで次の入力を提供しました:

エイリアスのデプロイ: test
ネットワークの種類: テストネット
URL: https://api.minascan.io/node/devnet/v1/graphql
料金支払者: 新しい料金支払者キー
トランザクション: 0.1

URL はここから取得できます:

Exploring the Mina Protocol: Practical Use Cases for zk Applications

その後、デプロイすると次の応答が返されました。

Exploring the Mina Protocol: Practical Use Cases for zk Applications

Exploring the Mina Protocol: Practical Use Cases for zk Applications

コントラクトは次の開発ネットにデプロイされます

デプロイ後、RPC URL を指定して単純な HTML、CSS、JS を選択し、コントラクト アドレスをデプロイした UI を進(jìn)めました。これが最終的な UI です。

Exploring the Mina Protocol: Practical Use Cases for zk Applications

これで、スマート コントラクトと UI を統(tǒng)合した後の zkapp の作成は完了です。 AgeVerification zkApp のユーザー インターフェイス (UI) を構(gòu)築した後、フロントエンドとスマート コントラクトの統(tǒng)合により、ユーザーはゼロ知識(shí)証明システムとシームレスに対話できるようになります。 UI は、zk-SNARK を通じてプライバシーを維持しながら、ユーザーの年齢としきい値データの契約への提出を容易にします。これにより、ユーザーは実際の値を明らかにすることなく自分の年齢を確認(rèn)でき、機(jī)密性が保たれます。バックエンドは証明者機(jī)能を利用して証明を生成し、Mina ブロックチェーンがそれを効率的に検証します。このエンドツーエンドのソリューションは、Mina の zk-SNARK ベースのアーキテクチャが提供するプライバシーとスケーラビリティの機(jī)能を最大限に活用しながら、安全でユーザーフレンドリーなエクスペリエンスを保証します。

以上がmina プロトコルの探索: zk アプリケーションの実用的な使用例の詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國(guó)語(yǔ) Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負(fù)いません。盜作または侵害の疑いのあるコンテンツを見つけた場(chǎng)合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡(jiǎn)単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國(guó)語(yǔ)版

SublimeText3 中國(guó)語(yǔ)版

中國(guó)語(yǔ)版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強(qiáng)力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JavaScriptで使用するコメントシンボル:明確な説明 JavaScriptで使用するコメントシンボル:明確な説明 Jun 12, 2025 am 10:27 AM

JavaScriptでは、シングルラインコメント(//)またはマルチラインコメント(//)を選択することは、コメントの目的とプロジェクトの要件に依存します。 2。詳細(xì)なドキュメントには、マルチラインコメントを使用します。 3。コメントスタイルの一貫性を維持します。 4。過剰な承認(rèn)を避けます。 5.コメントがコードと同期して更新されていることを確認(rèn)してください。適切な注釈スタイルを選択すると、コードの読みやすさと保守性を向上させることができます。

JavaScriptの究極のガイドコメント:コードの明確さを強(qiáng)化します JavaScriptの究極のガイドコメント:コードの明確さを強(qiáng)化します Jun 11, 2025 am 12:04 AM

はい、javascriptcommentsは不必要に使用されています。

Java vs. JavaScript:混亂を解消します Java vs. JavaScript:混亂を解消します Jun 20, 2025 am 12:27 AM

JavaとJavaScriptは異なるプログラミング言語(yǔ)であり、それぞれ異なるアプリケーションシナリオに適しています。 Javaは大規(guī)模なエンタープライズおよびモバイルアプリケーション開発に使用されますが、JavaScriptは主にWebページ開発に使用されます。

JavaScriptコメント:短い説明 JavaScriptコメント:短い説明 Jun 19, 2025 am 12:40 AM

JavaScriptcommentsEareEssentialential-formaining、およびGuidingCodeexecution.1)single-linecommentseared forquickexplanations.2)多LinecommentsexplaincomplexlogiCorprovidededocumentation.3)clarifyspartsofcode.bestpractic

JavaScriptのマスターコメント:包括的なガイド JavaScriptのマスターコメント:包括的なガイド Jun 14, 2025 am 12:11 AM

ContureCrucialInjavascript formantaining andFosteringCollaboration.1)TheypindeBugging、Onboarding、およびUnderstandingCodeevolution.2)usesingle-linecomments for quickexplanations andmulti-linecomments fordeTeTaileddespransions.3)BestPractsinclud

JavaScriptデータ型:ディープダイビング JavaScriptデータ型:ディープダイビング Jun 13, 2025 am 12:10 AM

javascripthasseveralprimitivedatypes:number、string、boolean、undefined、null、symbol、andbigint、andnon-primitiveTypeslike objectandarray

JavaScript vs. Java:開発者向けの包括的な比較 JavaScript vs. Java:開発者向けの包括的な比較 Jun 20, 2025 am 12:21 AM

javascriptispreferredforwebdevelopment、whilejavaisbetterforlge-scalebackendsystemsandroidapps.1)javascriptexcelsininintingtivewebexperiences withitsdynAmicnature anddommanipulation.2)javaofferstruntypyping-dobject-reientedpeatures

JSで日付と時(shí)間を操作する方法は? JSで日付と時(shí)間を操作する方法は? Jul 01, 2025 am 01:27 AM

JavaScriptで日付と時(shí)間を処理する場(chǎng)合は、次の點(diǎn)に注意する必要があります。1。日付オブジェクトを作成するには多くの方法があります。 ISO形式の文字列を使用して、互換性を確保することをお?jiǎng)幛幛筏蓼埂?2。時(shí)間情報(bào)を取得および設(shè)定して、メソッドを設(shè)定でき、月は0から始まることに注意してください。 3.手動(dòng)でのフォーマット日付には文字列が必要であり、サードパーティライブラリも使用できます。 4.ルクソンなどのタイムゾーンをサポートするライブラリを使用することをお?jiǎng)幛幛筏蓼?。これらの重要なポイントを?xí)得すると、一般的な間違いを効果的に回避できます。

See all articles