Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

certified-variables认证变量

Agent Skill

certified-variables 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

2,448

周安装

102

GitHub Stars

16

下载量

816
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:certified-variables(认证变量)
来源仓库:https://github.com/dfinity/icskills
仓库路径:skills/certified-variables
安装命令:
npx skills add https://github.com/dfinity/icskills --skill certified-variables
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dfinity/icskills --skill certified-variables

简介

certified-variables 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。

  • 它支持认证变量与资产的查询响应,通过子网认证状态树和阈值 BLS 密钥签名确保数据真实性与快速访问。
  • 使用时需结合来源仓库、安装命令和原始 README 核验具体用法,建议确认权限范围和维护状态。
  • 安装前应检查是否会触发联网、命令执行或文件读写,避免意外操作影响系统安全。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Certified Variables & Certified Assets

What This Is

Query responses on the Internet Computer come from a single replica and are NOT verified by consensus. A malicious or faulty replica could return fabricated data. Certification solves this: the canister stores a hash in the subnet's certified state tree during update calls, and then query responses include a certificate signed by the subnet's threshold BLS key proving the data is authentic. The result is responses that are both fast (no consensus delay) AND cryptographically verified.

Prerequisites

  • Rust: ic-certified-map crate (for Merkle tree), ic-cdk (for certified_data_set / data_certificate)
  • Motoko: CertifiedData module (included in mo:core/mo:base), ic-certification package (mops add ic-certification) for Merkle tree with witness support
  • Frontend: @icp-sdk/core (>= 5.0.0) (agent, principal), @dfinity/certificate-verification (>= 3.1.0)

Canister IDs

No external canister IDs required. Certification uses the IC system API exposed through CDK wrappers:

  • ic_cdk::api::certified_data_set (Rust) / CertifiedData.set (Motoko) -- called during update calls to set the certified hash (max 32 bytes)
  • ic_cdk::api::data_certificate (Rust) / CertifiedData.getCertificate (Motoko) -- called during query calls to retrieve the subnet certificate

The IC root public key (needed for client-side verification):

  • Mainnet: 308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae
  • Local: available from icp (agent handles this automatically)

Mistakes That Break Your Build

  1. Trying to store more than 32 bytes of certified data. The certified_data_set API accepts exactly one blob of at most 32 bytes. You cannot certify arbitrary data directly. Instead, build a Merkle tree over your data and certify only the root hash (32 bytes). The tree structure provides proofs for individual values.
  2. Calling certified_data_set in a query call. Certification can ONLY be set during update calls (which go through consensus). Calling it in a query traps. Pattern: set the hash during writes, read the certificate during queries.
  3. Forgetting to include the certificate in query responses. The certificate is obtained via data_certificate() during query calls. If you return data without the certificate, clients cannot verify anything. Always return a tuple of (data, certificate, witness).
  4. Not updating the certified hash after data changes. If you modify the data but forget to call certified_data_set with the new root hash, query responses will fail verification because the certificate proves a stale hash.
  5. Building the witness for the wrong key. The witness (Merkle proof) must correspond to the exact key being queried. A witness for key "users/alice" will not verify key "users/bob".
  6. Assuming data_certificate() returns a value in update calls. It returns null/None during update calls. Certificates are only available during query calls.
  7. Certifying data at canister init but not on upgrades. After a canister upgrade, the certified data is cleared. You must call certified_data_set in both #[init] and #[post_upgrade] (Rust) or system func postupgrade (Motoko) to re-establish certification.
  8. Not validating certificate freshness on the client. The certificate's state tree contains a /time field with the timestamp when the subnet produced it. Clients MUST check that this timestamp is recent (recommended: within 5 minutes of current time). Without this check, an attacker could replay a stale certificate with outdated data. Always verify certificate_time is within an acceptable delta before trusting the response.

How Certification Works

UPDATE CALL (goes through consensus):
  1. Canister modifies data
  2. Canister builds/updates Merkle tree
  3. Canister calls certified_data_set(root_hash)  -- 32 bytes
  4. Subnet includes root_hash in its certified state tree

QUERY CALL (single replica, no consensus):
  1. Client sends query
  2. Canister calls data_certificate() -- gets subnet BLS signature
  3. Canister builds witness (Merkle proof) for the requested key
  4. Canister returns: { data, certificate, witness }

CLIENT VERIFICATION:
  1. Verify certificate signature against IC root public key
  2. Extract root_hash from certificate's state tree
  3. Verify witness: root_hash + witness proves data is in the tree
  4. Trust the data

Implementation

Rust

Cargo.toml:

[package]
name = "certified_vars_backend"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
candid = "0.10"
ic-cdk = "0.19"
ic-certified-map = "0.4"
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11"
ciborium = "0.2"

Complete certified key-value store:

use candid::{CandidType, Deserialize};
use ic_cdk::{init, post_upgrade, query, update};
use ic_certified_map::{AsHashTree, RbTree};
use serde_bytes::ByteBuf;
use std::cell::RefCell;

thread_local! {
    // RbTree is a Merkle-tree-backed map: keys and values are byte slices
    static TREE: RefCell<RbTree<Vec<u8>, Vec<u8>>> = RefCell::new(RbTree::new());
}

// Update the certified data hash after any modification
fn update_certified_data() {
    TREE.with(|tree| {
        let tree = tree.borrow();
        // root_hash() returns a 32-byte SHA-256 hash of the entire tree
        ic_cdk::api::certified_data_set(&tree.root_hash());
    });
}

#[init]
fn init() {
    update_certified_data();
}

#[post_upgrade]
fn post_upgrade() {
    // Assumes data has already been deserialized from stable memory into the TREE.
    // CRITICAL: re-establish certification after upgrade — certified_data is cleared on upgrade.
    update_certified_data();
}

#[update]
fn set(key: String, value: String) {
    TREE.with(|tree| {
        let mut tree = tree.borrow_mut();
        tree.insert(key.as_bytes().to_vec(), value.as_bytes().to_vec());
    });
    // Must update certified hash after every data change
    update_certified_data();
}

#[update]
fn delete(key: String) {
    TREE.with(|tree| {
        let mut tree = tree.borrow_mut();
        tree.delete(key.as_bytes());
    });
    update_certified_data();
}

#[derive(CandidType, Deserialize)]
struct CertifiedResponse {
    value: Option<String>,
    certificate: ByteBuf,      // subnet BLS signature
    witness: ByteBuf,          // Merkle proof for this key
}

#[query]
fn get(key: String) -> CertifiedResponse {
    // data_certificate() is only available in query calls
    let certificate = ic_cdk::api::data_certificate()
        .expect("data_certificate only available in query calls");

    TREE.with(|tree| {
        let tree = tree.borrow();

        // Look up the value
        let value = tree.get(key.as_bytes())
            .map(|v| String::from_utf8(v.clone()).unwrap());

        // Build a witness (Merkle proof) for this specific key
        let witness = tree.witness(key.as_bytes());

        // Serialize the witness as CBOR
        let mut witness_buf = vec![];
        ciborium::into_writer(&witness, &mut witness_buf)
            .expect("Failed to serialize witness as CBOR");

        CertifiedResponse {
            value,
            certificate: ByteBuf::from(certificate),
            witness: ByteBuf::from(witness_buf),
        }
    })
}

// Batch set multiple values in one update call (more efficient)
#[update]
fn set_many(entries: Vec<(String, String)>) {
    TREE.with(|tree| {
        let mut tree = tree.borrow_mut();
        for (key, value) in entries {
            tree.insert(key.as_bytes().to_vec(), value.as_bytes().to_vec());
        }
    });
    // Single certification update for all changes
    update_certified_data();
}

HTTP Certification (v2) for Custom HTTP Canisters

For canisters serving HTTP responses directly (not through the asset canister), responses must be certified so the HTTP gateway can verify them.

Additional Cargo.toml dependency:

[package]
name = "http_certified_backend"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
ic-http-certification = "3.1"

Certifying HTTP responses:

Note: The HTTP certification API is evolving rapidly. Verify these examples against the latest ic-http-certification docs before use.
use ic_http_certification::{
    HttpCertification, HttpCertificationPath, HttpCertificationTree,
    HttpCertificationTreeEntry, HttpRequest, HttpResponse,
    DefaultCelBuilder, DefaultResponseCertification,
};
use std::cell::RefCell;

thread_local! {
    static HTTP_TREE: RefCell<HttpCertificationTree> = RefCell::new(
        HttpCertificationTree::default()
    );
}

// Define what gets certified using CEL (Common Expression Language)
fn certify_response(path: &str, request: &HttpRequest, response: &HttpResponse) {
    // Full certification: certify both request path and response body
    let cel = DefaultCelBuilder::full_certification()
        .with_response_certification(DefaultResponseCertification::certified_response_headers(
            vec!["Content-Type", "Content-Length"],
        ))
        .build();

    // Create the certification from the CEL expression, request, and response
    let certification = HttpCertification::full(&cel, request, response, None)
        .expect("Failed to create HTTP certification");

    let http_path = HttpCertificationPath::exact(path);

    HTTP_TREE.with(|tree| {
        let mut tree = tree.borrow_mut();
        let entry = HttpCertificationTreeEntry::new(http_path, certification);
        tree.insert(&entry);

        // Update canister certified data with tree root hash
        ic_cdk::api::certified_data_set(&tree.root_hash());
    });
}

Motoko

Using CertifiedData module:

import CertifiedData "mo:core/CertifiedData";
import Blob "mo:core/Blob";
import Nat8 "mo:core/Nat8";
import Text "mo:core/Text";
import Map "mo:core/Map";
import Array "mo:core/Array";
import Iter "mo:core/Iter";
// Requires: mops add sha2
import Sha256 "mo:sha2/Sha256";

persistent actor {

  // Simple certified single-value example:
  var certifiedValue : Text = "";

  // Set a certified value (update call only)
  public func setCertifiedValue(value : Text) : async () {
    certifiedValue := value;
    // Hash the value and set as certified data (max 32 bytes)
    let hash = Sha256.fromBlob(#sha256, Text.encodeUtf8(value));
    CertifiedData.set(hash);
  };

  // Get the certified value with its certificate (query call)
  public query func getCertifiedValue() : async {
    value : Text;
    certificate : ?Blob;
  } {
    {
      value = certifiedValue;
      certificate = CertifiedData.getCertificate();
    }
  };
};

Certified key-value store with Merkle tree (advanced):

For certifying multiple values with per-key witnesses, use the ic-certification mops package (mops add ic-certification). It provides a real Merkle tree (CertTree) that can generate proofs for individual keys:

import CertifiedData "mo:core/CertifiedData";
import Blob "mo:core/Blob";
import Text "mo:core/Text";
// Requires: mops add ic-certification
import CertTree "mo:ic-certification/CertTree";

persistent actor {

  // CertTree.Store is stable -- persists across upgrades
  let certStore : CertTree.Store = CertTree.newStore();
  let ct = CertTree.Ops(certStore);

  // Set certified data on init
  ct.setCertifiedData();

  // Set a key-value pair and update certification
  public func set(key : Text, value : Text) : async () {
    ct.put([Text.encodeUtf8(key)], Text.encodeUtf8(value));
    // CRITICAL: call after every mutation to update the subnet-certified root hash
    ct.setCertifiedData();
  };

  // Delete a key and update certification
  public func remove(key : Text) : async () {
    ct.delete([Text.encodeUtf8(key)]);
    ct.setCertifiedData();
  };

  // Query with certificate and Merkle witness for the requested key
  public query func get(key : Text) : async {
    value : ?Blob;
    certificate : ?Blob;
    witness : Blob;
  } {
    let path = [Text.encodeUtf8(key)];
    // reveal() generates a Merkle proof for this specific path
    let witness = ct.reveal(path);
    {
      value = ct.lookup(path);
      certificate = CertifiedData.getCertificate();
      witness = ct.encodeWitness(witness);
    }
  };

  // Re-establish certification after upgrade
  // (CertTree.Store is stable, so the tree data survives, but certified_data is cleared)
  system func postupgrade() {
    ct.setCertifiedData();
  };
};

Frontend Verification (TypeScript)

Uses @dfinity/certificate-verification which handles the full 6-step verification:

  1. Verify certificate BLS signature against IC root key
  2. Validate certificate freshness (/time within maxCertificateTimeOffsetMs)
  3. CBOR-decode the witness into a HashTree
  4. Reconstruct the witness root hash
  5. Compare reconstructed root hash with certified_data from the certificate
  6. Return the verified HashTree for value lookup
import { verifyCertification } from "@dfinity/certificate-verification";
import { lookup_path, HashTree } from "@icp-sdk/core/agent";
import { Principal } from "@icp-sdk/core/principal";

const MAX_CERT_TIME_OFFSET_MS = 5 * 60 * 1000; // 5 minutes

async function getVerifiedValue(
  rootKey: ArrayBuffer,
  canisterId: string,
  key: string,
  response: { value: string | null; certificate: ArrayBuffer; witness: ArrayBuffer }
): Promise<string | null> {
  // verifyCertification performs steps 1-5:
  //  - verifies BLS signature on the certificate
  //  - checks certificate /time is within maxCertificateTimeOffsetMs
  //  - CBOR-decodes the witness into a HashTree
  //  - reconstructs root hash from the witness tree
  //  - compares it against certified_data in the certificate
  // Throws CertificateTimeError or CertificateVerificationError on failure.
  const tree: HashTree = await verifyCertification({
    canisterId: Principal.fromText(canisterId),
    encodedCertificate: response.certificate,
    encodedTree: response.witness,
    rootKey,
    maxCertificateTimeOffsetMs: MAX_CERT_TIME_OFFSET_MS,
  });

  // Step 6: Look up the specific key in the verified witness tree.
  // The path must match how the canister inserted the key (e.g., key as UTF-8 bytes).
  const leafData = lookup_path([new TextEncoder().encode(key)], tree);

  if (!leafData) {
    // Key is provably absent from the certified tree
    return null;
  }

  const verifiedValue = new TextDecoder().decode(leafData);

  // Confirm the canister-returned value matches the witness-proven value
  if (response.value !== null && response.value !== verifiedValue) {
    throw new Error(
      "Response value does not match witness — canister returned tampered data"
    );
  }

  return verifiedValue;
}

For asset canisters, the HTTP gateway (boundary node) verifies certification transparently using the HTTP Gateway Protocol -- no client-side code needed.

Deploy & Test

# Deploy the canister
icp deploy backend

# Set a certified value (update call -- goes through consensus)
icp canister call backend set '("greeting", "hello world")'

# Query the certified value
icp canister call backend get '("greeting")'
# Returns: record { value = opt "hello world"; certificate = blob "..."; witness = blob "..." }

# Set multiple values
icp canister call backend set '("name", "Alice")'
icp canister call backend set '("age", "30")'

# Delete a value
icp canister call backend delete '("age")'

# Verify the root hash is being set
# (No direct command -- verified by the presence of a non-null certificate in query response)

Verify It Works

# 1. Verify certificate is present in query response
icp canister call backend get '("greeting")'
# Expected: certificate field is a non-empty blob (NOT null)
# If certificate is null, you are calling from an update context (wrong)

# 2. Verify data integrity after update
icp canister call backend set '("key1", "value1")'
icp canister call backend get '("key1")'
# Expected: value = opt "value1" with valid certificate

# 3. Verify certification survives canister upgrade
icp canister call backend set '("persistent", "data")'
icp deploy backend  # triggers upgrade
icp canister call backend get '("persistent")'
# Expected: certificate is still non-null (postupgrade re-established certification)
# Note: data persistence depends on stable storage implementation

# 4. Verify non-existent key returns null value with valid certificate
icp canister call backend get '("nonexistent")'
# Expected: value = null, certificate = blob "..." (certificate still valid)

# 5. Frontend verification test
# Open browser developer tools, check network requests
# Query responses should include IC-Certificate header
# The service worker (if using asset canister) validates automatically
# Console should NOT show "Certificate verification failed" errors

# 6. For HTTP certification (custom HTTP canister):
curl -v https://CANISTER_ID.ic0.app/path
# Expected: Response headers include IC-Certificate
# HTTP gateway verifies the certificate before forwarding to client

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.61%
按下载量换算307

Claude

31.59%
按下载量换算258

Cursor

17.67%
按下载量换算144

Gemini CLI

9.91%
按下载量换算81

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills