Back to Browse

Use with your AI agent

  1. Install — run npx skills add Kali-Decoder/Midnight-skills --skill midnight-security for this skill, or npx skills add Kali-Decoder/Midnight-skills for all
  2. Prompt — copy the example prompt and paste it into Cursor, Claude Code, or Codex
  3. Build — the agent loads this skill and scaffolds your Midnight work

Security

DomainAdvancedReviewedUpdated 3 days agov1.0.0

Agent picks this when: Privacy audit checklist, prevent data leaks, defensive Compact patterns

Privacy audit checklist, data leak patterns, defensive Compact patterns.

Good for

  • Privacy audit checklist, data leak patterns, commitment/nullifier design.
  • Witness trust, front-running resistance, transaction semantics.

Preview in agent

Suggested prompts

Privacy audit checklist, prevent data leaks, defensive Compact patterns. Use the "midnight-security" skill from MIDSKILLS. Follow Compact smart-contract best practices, wire wallet flows where needed, and explain each step as you implement. Target Midnight Preprod unless I specify otherwise.

Loaded skill midnight-security

What the skill guides the agent to do:

  1. Privacy audit checklist, data leak patterns, commitment/nullifier design.
  2. Witness trust, front-running resistance, transaction semantics.

Illustrative — based on the skill's description, not recorded agent output.

Try it without installing: npx skills use Kali-Decoder/Midnight-skills@midnight-security

What changed in v1.0.16

All registry changes

Updated since v1.0.14: +2 −0 lines.

Show diff
SKILL.md+2−0
@@ -9,6 +9,8 @@  Midnight's privacy model is opt-in privacy on top of a public chain. The ZK proof proves correctness of execution — it does not hide the *existence* of a transaction, its *structure*, or anything in `export ledger`. Security on Midnight means being precise about what leaks and designing contracts so that leaks are intentional. +**Shipping?** Run the pass/fail gate in `midnight-security-checklist/` first; this skill explains each item.+ **Primary references:** - `docs.midnight.network/concepts/how-midnight-works/keeping-data-private` - `docs.midnight.network/concepts/how-midnight-works/semantics`
On this page · 26 sections
SKILL.md

Midnight Security Skill

Versions: every pin in this skill comes from references/versions.json, the repo's single source of truth (checked in CI). Resolve the current set at use time with references/volatile.md. Never install @latest.

Midnight's privacy model is opt-in privacy on top of a public chain. The ZK proof proves correctness of execution — it does not hide the existence of a transaction, its structure, or anything in export ledger. Security on Midnight means being precise about what leaks and designing contracts so that leaks are intentional.

Shipping? Run the pass/fail gate in midnight-security-checklist/ first; this skill explains each item.

Primary references:

  • docs.midnight.network/concepts/how-midnight-works/keeping-data-private
  • docs.midnight.network/concepts/how-midnight-works/semantics
  • docs.midnight.network/concepts/how-midnight-works/smart-contracts
  • Official docs: docs.midnight.network/compact (language reference + standard library) and the toolchain release notes. There is still no dedicated security guide, which this skill fills in
  • Targets Compact 0.36.1 / language 0.28.0 (Ledger 9). Every full example below compiles with 0.36.1, and the hash-auth example was also executed (right key passes, wrong key is rejected)

1) The Fundamental Visibility Rule

Everything in export ledger is public. Everything in witness is private. The proof is public. The witness data is not.

More precisely, for every ledger operation:

OperationWhat is revealed
ledger.insert(v)The value v
ledger.lookup(k)The key k and the returned value
set.insert(v)The value v
set.member(f(x))The value f(x) — not x directly
map.insert(k, v)The key k and value v
counter.increment(n)The increment amount n and new value
merkleTree.insert(v)Does NOT reveal v — only that the tree grew
merkleTree.checkRoot(path)That someone proved membership — not which entry
Circuit argumentsAll of them — they are part of the public transcript
witness return valuesNothing on-chain — the ZK proof only proves they existed

The public transcript is what the chain records: ledger reads, writes, and the structure of those operations. Witness values exist only in the proof's private inputs — they are never posted.


2) Privacy Audit Checklist

Run this against every contract before shipping.

Ledger fields

  • Every export ledger field: who can read it, and is that acceptable?
  • Is any export ledger field per-user data that should be local (witness)?
  • Does the field exist only because the frontend needs to read it? If only one user cares, it should not be on-chain.
  • For any Map<K, V>: is the key K itself sensitive? (Map keys are public on insert/lookup.)
  • Is a Set<T> used when anonymity is required? (Set.member(v) reveals v — use MerkleTree instead.)

Circuit arguments

  • Every circuit parameter: is it part of the public transcript? (Yes, all of them.)
  • Is any sensitive value passed directly as a circuit argument instead of through a witness?

Commitments and hashes

  • Any persistentHash over a small value space (e.g., boolean, vote, role)? → brute-forcible → use persistentCommit with a fresh nonce instead.
  • Any two commitments that reuse the same nonce? → identical inputs produce identical commitments on-chain → linkable.
  • Is transientHash/transientCommit used for ledger storage? → does not survive contract upgrades → use persistent*.

Domain separators

  • Every persistentHash call: does it include a unique domain separator string?
  • Is the same secret key used to derive multiple public keys without domain separation? → same key, same hash → different purposes become linked.
  • Is the same domain separator used for both a commitment and its nullifier? → potential collision.

Witness trust

  • Every witness output: is it validated with assert before being used in logic?
  • Does any circuit assume that a witness returns "honest" data without checking it?

Replay and reuse

  • Any auth pattern using a secret key without a sequence counter or nullifier? → replay attack.
  • Any commitment that can be reused to re-authorize the same action? → missing nullifier.

Transaction structure leaks

  • Does calling a specific circuit reveal intent even if data is hidden? (e.g., calling submitVote reveals that someone voted)
  • Does the number of merkleTree.insert calls within a circuit reveal anything about the private inputs?

3) What Leaks Even With Witnesses

These things are always visible to any chain observer, regardless of privacy measures:

  • Which contract was called — the contract address is public
  • Which circuit was called — the entryPoint field in the indexer
  • When it was called — block timestamp
  • That a transaction occurred — existence is always public
  • Circuit argument values — every parameter passed to an export circuit
  • All ledger writes — every export ledger field that changes
  • The shape of the public transcript — how many reads, writes, inserts happened (though not the private values behind them)

Practical implication: If your circuit takes vote: Boolean as an argument, the vote is public even though you never write it to the ledger directly. Move it to a witness.


4) Data Leak Patterns (The Common Mistakes)

Pattern 1: Sensitive value as circuit argument

// ❌ vote is a circuit argument → public transcript → everyone sees it
export circuit submitVote(vote: Boolean): [] {
  votes.insert(disclose(makeCommitment(vote)));
}

// ✅ vote comes from witness → stays in proof's private inputs
witness userVote(): Boolean;

export circuit submitVote(): [] {
  const vote = userVote();  // private
  votes.insert(disclose(makeCommitment(vote)));  // only commitment is public
}

Pattern 2: Using Set when anonymity is required

// ❌ Set.member(v) reveals v — which user's commitment is being checked
export ledger members: Set<Bytes<32>>;

export circuit prove(): [] {
  const pk = publicKey(secretKey());
  assert(members.member(pk), "not a member");  // reveals pk
}

// ✅ MerkleTree proves membership without revealing which entry
export ledger members: MerkleTree<16, Bytes<32>>;
witness findMemberPath(pk: Bytes<32>): MerkleTreePath<16, Bytes<32>>;

export circuit prove(): [] {
  const pk = publicKey(secretKey());
  const path = findMemberPath(pk);
  assert(
    members.checkRoot(merkleTreePathRoot<16, Bytes<32>>(path)),
    "not a member"
  );
  // Only proves: "someone in the tree called this." Does not reveal who.
}

Pattern 3: Hash without nonce over small value space

// ❌ persistentHash over Boolean → 2 possible outputs → trivially brute-forced
export ledger commitment: Bytes<32>;
export circuit commit(vote: Boolean): [] {
  commitment = disclose(persistentHash<Boolean>(vote));
}

// ✅ persistentCommit with fresh nonce → infeasible to brute-force
witness voteNonce(): Bytes<32>;
export circuit commit(vote: Boolean): [] {  // vote still a circuit arg here — see pattern 1
  const nonce = voteNonce();
  commitment = disclose(persistentCommit<Boolean>(vote, nonce));
}
// Combine with pattern 1 to also move vote to witness

Pattern 4: Nonce reuse linking commitments

// ❌ same secret key as nonce → if same value committed twice, identical on-chain
export circuit recordBalance(amount: Uint<64>): [] {
  const sk = secretKey();
  const c = persistentCommit<Uint<64>>(amount, sk);  // reusing sk as nonce
  commitments.insert(disclose(c));
}

// ✅ derive a unique nonce per commitment using round counter or fresh randomness
export ledger round: Counter;
export circuit recordBalance(amount: Uint<64>): [] {
  const sk = secretKey();
  const nonce = persistentHash<Vector<2, Bytes<32>>>(
    [sk, pad(32, "balance-nonce"), round as Field as Bytes<32>]
  );
  const c = persistentCommit<Uint<64>>(amount, nonce);
  commitments.insert(disclose(c));
  round.increment(1);
}

Pattern 5: Missing domain separator — key reuse across purposes

// ❌ same sk → same hash for auth and for commitment → linkable across contracts
pure circuit publicKey(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Bytes<32>>(sk);
}

pure circuit commitmentKey(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Bytes<32>>(sk);  // identical output
}

// ✅ unique domain separator per purpose
pure circuit authPublicKey(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:auth:v1"), sk]);
}

pure circuit commitmentKey(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:commit:v1"), sk]);
}

Pattern 6: Untrusted witness output

// ❌ trusting that the DApp-provided witness returns the right balance
export circuit transfer(to: Bytes<32>, amount: Uint<64>): [] {
  const balance = userBalance();  // could return anything
  balances.insert(to, disclose(balance - amount));
}

// ✅ assert all witness outputs before using them
export circuit transfer(to: Bytes<32>, amount: Uint<64>): [] {
  const balance = userBalance();
  assert(balance >= amount, "insufficient balance");
  assert(balance <= MAX_SUPPLY, "invalid balance");
  balances.insert(to, disclose((balance - amount) as Uint<64>));
}

5) Defensive Patterns (Full Implementations)

Hash-Based Authentication (ZK Signature)

Proves knowledge of a secret key without revealing it. The sequence counter prevents replay across rounds.

pragma language_version >= 0.28.0;
import CompactStandardLibrary;

export ledger admin: Bytes<32>;
export ledger round: Counter;

witness secretKey(): Bytes<32>;

constructor() {
  admin = disclose(publicKey(secretKey(), roundBytes(0)));
}

export circuit adminAction(): [] {
  const sk = secretKey();
  assert(admin == disclose(publicKey(sk, roundBytes(round.read()))), "not authorized");
  // ... do the action
  round.increment(1);  // invalidates old proofs against this round
  admin = disclose(publicKey(sk, roundBytes(round.read())));
}

pure circuit roundBytes(r: Uint<64>): Bytes<32> {
  return (r as Field) as Bytes<32>;
}

pure circuit publicKey(sk: Bytes<32>, roundBytes: Bytes<32>): Bytes<32> {
  return persistentHash<Vector<3, Bytes<32>>>([
    pad(32, "myapp:admin:v1"),  // domain separator
    roundBytes,                  // round prevents replay
    sk,
  ]);
}

Commitment/Nullifier (Single-Use Anonymous Token)

Proves a token exists in the Merkle tree and has not been spent, without revealing which token.

pragma language_version >= 0.28.0;
import CompactStandardLibrary;

export ledger commitments: HistoricMerkleTree<16, Bytes<32>>;
export ledger nullifiers: Set<Bytes<32>>;
export ledger counter: Counter;

witness secretKey(): Bytes<32>;
witness findCommitmentPath(c: Bytes<32>): MerkleTreePath<16, Bytes<32>>;

export circuit addToken(commitment: Bytes<32>): [] {
  commitments.insert(disclose(commitment));
}

export circuit spend(): [] {
  const sk = secretKey();
  const c = commitment(sk);
  const path = findCommitmentPath(c);

  // 1. Prove token is in the tree (without revealing which)
  assert(
    commitments.checkRoot(disclose(merkleTreePathRoot<16, Bytes<32>>(path))), // the root is public; the path stays private
    "commitment not in tree"
  );

  // 2. Prove token has not been spent
  const nul = nullifier(sk);
  assert(!nullifiers.member(disclose(nul)), "already spent");

  // 3. Record the spend — reveals nullifier, not the commitment
  nullifiers.insert(disclose(nul));
  counter.increment(1);
}

// CRITICAL: commitment and nullifier MUST use different domain separators
// If they shared a domain, the same sk would produce the same hash for both
pure circuit commitment(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:commit:v1"), sk]);
}

pure circuit nullifier(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:nullifier:v1"), sk]);
}

Use HistoricMerkleTree instead of MerkleTree when: the tree has frequent insertions that would otherwise invalidate outstanding proofs. Use plain MerkleTree when proofs are always generated against the current root and items are never removed.

Anonymous Allowlist (Merkle Membership)

Authorize a set of users without revealing which one is acting.

pragma language_version >= 0.28.0;
import CompactStandardLibrary;

export ledger allowlist: MerkleTree<16, Bytes<32>>;

witness secretKey(): Bytes<32>;
witness findAllowlistPath(pk: Bytes<32>): MerkleTreePath<16, Bytes<32>>;

export circuit addToAllowlist(commitment: Bytes<32>): [] {
  // Admin adds a commitment — reveals commitment (hash of user's key)
  // The commitment itself doesn't reveal who the user is unless brute-forced
  allowlist.insert(disclose(commitment));
}

export circuit allowlistedAction(): [] {
  const sk = secretKey();
  const pk = allowlistKey(sk);
  const path = findAllowlistPath(pk);

  assert(
    allowlist.checkRoot(disclose(merkleTreePathRoot<16, Bytes<32>>(path))), // the root is public; the path stays private
    "not on allowlist"
  );

  // Action proceeds. Observer knows: "someone on the allowlist did this."
  // Observer does NOT know: which allowlisted user.
}

pure circuit allowlistKey(sk: Bytes<32>): Bytes<32> {
  return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:allowlist:v1"), sk]);
}

5b) Ledger 9 Audit Surface (language 0.28.0)

Ledger 9 added features that create new things to review. All of these behaviors were checked with the 0.36.1 compiler.

FeatureWhat leaks / what to check
emit(...) eventsEverything emitted is public, indexed (contractEvents) and permanent. Treat an event like a ledger write: only emit disclose()d values. Emitting from the constructor is a compile error.
Cross-contract calls (contract X { circuit ...; })The callee reference and every argument must be disclosed. The compiler rejects undisclosed ones (contract call argument 1 might disclose the witness value). The call graph is visible on-chain, so a call reveals which contract you touched and with what. Cycles fail at run time. Per the language reference, circuits that satisfy a contract type may not call witnesses.
Callee trustA contract-typed argument is supplied by the caller. Verify it is the contract you expect (compare against a stored address) before trusting its return values.
kernel.caller()Returns Maybe<PublicAddress>. Useful for contract-to-contract authorization, but it is the immediate caller. Check is_some and don't assume an end user.
secp256k1EcdsaVerify(msgHash, sig, pk)Verifies a hash, not a message: hash the message yourself, with domain separation, inside the circuit. Always assert on the result. Since 0.35 it rejects the identity point as pk. The compiler changelog (0.33.x) says it accepts both low-s and high-s signatures, so treat signatures as malleable: never use one (or its hash) as a nullifier/replay key. Bind a nonce or round instead.
keccak256 / sha512Fine for Ethereum interop. Prefer persistentHash / persistentCommit for Midnight-native commitments, and never hash small value spaces without a nonce.
Recompiling for Ledger 9Moving from compiler 0.31 to 0.36.x changes verifier keys. Redeploy, or install new keys via the maintenance authority, and re-audit cross-contract callers and callees together.

6) Transaction Semantics — Security Implications

Midnight transactions execute in two phases with different failure behavior:

well-formedness check  →  guaranteed phase  →  fallible phase
PhaseFailure behaviorFee behavior
Well-formednessTransaction rejected entirely, not includedNo fee
GuaranteedTransaction rejected entirely, not includedNo fee
FallibleGuaranteed phase effects persist; fallible phase rolled backFees forfeited

Security implications:

Partial success is real. If your contract does work in the guaranteed phase (e.g., burns a token) and then fails in the fallible phase (e.g., a balance check fails), the burn is permanent but the balance isn't updated. Design state transitions so they either succeed atomically or the guaranteed phase does nothing consequential.

Fees are forfeited on fallible failure. An attacker who can force fallible failures can drain DUST from users' wallets. Ensure assert conditions in fallible circuits cannot be triggered by external state that an attacker can manipulate between proof generation and submission.

Front-running via public transcript. Because the public transcript (including which circuit was called and all circuit arguments) is visible in the mempool before finalization, an observer can potentially act on that information before the transaction lands. If ordering matters (e.g., a swap), design circuits that include slippage bounds or use commitment reveals to defer sensitive data.


7) What ZK Proofs Do and Do Not Guarantee

ZK proofs guarantee:

  • The circuit logic ran correctly with some valid private inputs
  • The public transcript faithfully records what the circuit read/wrote to the ledger
  • The prover knew a witness satisfying all circuit constraints at proof time

ZK proofs do NOT guarantee:

  • That the private inputs were "honest" from the application's perspective (only that they satisfied the circuit's assert statements)
  • Anything about the prover's identity
  • That the same witness values were used as in a previous call
  • Confidentiality of circuit arguments — those are always public

Practical consequence: Every invariant your contract cares about must be enforced by an assert in the circuit. The ZK proof only proves what the circuit checks.


8) Merkle Tree Depth Selection

DepthMax leavesCircuit impactUse for
8256MinimalTiny allowlists, tests
101,024LowSmall user sets
1665,536ModerateMedium DApps
201,048,576HigherLarge user sets
32~4 billionSignificantMaximum scale

Use the minimum depth needed. Each additional level increases circuit size and proof time. Overflow (inserting beyond capacity) is a runtime error — size your tree for your expected maximum.

HistoricMerkleTree stores all past roots — it has higher storage cost than MerkleTree. Only use it when you need to prove membership against a past root (e.g., when tree is frequently updated between proof generation and submission).


9) Security Quick-Reference Table

RiskBad patternSafe pattern
Sensitive value on-chainCircuit argument for private dataMove to witness
Membership reveals identitySet<T> membership checkMerkleTree<n, T> path proof
Brute-forcible hashpersistentHash over small domainpersistentCommit with fresh nonce
Linked commitmentsSame nonce across multiple commitsRound counter or fresh nonce per commit
Key reuse across purposesSame sk → same hash everywhereUnique domain separator per purpose
Commitment = nullifier collisionSame domain for bothDifferent pad(32, ...) strings
Replay attackAuth without sequence counterInclude round/counter in public key derivation
Double-spendNo nullifier trackingSet<Bytes<32>> nullifier registry
Untrusted witnessUse witness output directlyassert all witness outputs before use
Upgrade breaks commitmentstransientHash in ledgerpersistentHash / persistentCommit
Partial success trapConsequential work in guaranteed phaseKeep guaranteed phase minimal
Front-runningSensitive args in circuit parametersUse witness + commitment reveal pattern

Start in 2 steps

  1. 1. Install — one skill or the full set
  2. 2. Prompt — paste the example into your agent

Install all skills (recommended)

npx skills add Kali-Decoder/Midnight-skills

One command adds every Midnight skill to Cursor, Claude Code, and similar agents.

Install this skill only

npx skills add Kali-Decoder/Midnight-skills --skill midnight-security

Installs only "midnight-security" into every detected agent (Cursor, Claude Code, Codex, …).

Example agent prompt

Privacy audit checklist, prevent data leaks, defensive Compact patterns. Use the "midnight-security" skill from MIDSKILLS. Follow Compact smart-contract best practices, wire wallet flows where needed, and explain each step as you implement. Target Midnight Preprod unless I specify otherwise.

Paste into Cursor, Claude Code, or Codex after installing.

Author
Tusharpamnani
Category
Domain
Difficulty
advanced
Version
v1.0.0

Tags

SecurityAuditPrivacy

Files included

SKILL.md
Create Social CardLive HackathonsGallery
Mock Demo
Security