惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Cybersecurity and Infrastructure Security Agency CISA
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - 【当耐特】
爱范儿
爱范儿
美团技术团队
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
月光博客
月光博客
宝玉的分享
宝玉的分享
V
V2EX
Blog — PlanetScale
Blog — PlanetScale
Spread Privacy
Spread Privacy
博客园 - 叶小钗
量子位
Security Archives - TechRepublic
Security Archives - TechRepublic
Google DeepMind News
Google DeepMind News
L
LINUX DO - 热门话题
Hacker News - Newest:
Hacker News - Newest: "LLM"
P
Privacy International News Feed
Y
Y Combinator Blog
P
Proofpoint News Feed
NISL@THU
NISL@THU
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
G
Google Developers Blog
Hacker News: Ask HN
Hacker News: Ask HN
Help Net Security
Help Net Security
I
InfoQ
Cisco Talos Blog
Cisco Talos Blog
Google Online Security Blog
Google Online Security Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recent Announcements
Recent Announcements
Simon Willison's Weblog
Simon Willison's Weblog
Vercel News
Vercel News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
B
Blog
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
N
News | PayPal Newsroom
J
Java Code Geeks
Latest news
Latest news
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Designing public vs. private state: what goes where and why
Tosin Akinbo · 2026-05-09 · via DEV Community

One of the most common sources of confusion when building on Midnight is the question of privacy. Developers expect that marking something as "not exported" or keeping it off the main interface will make it private. It does not. On Midnight, privacy is a deliberate design decision that requires using the right tools at the right layer. This tutorial gives you a clear framework for making that decision.

By the end, you will understand the three layers of data in a Midnight smart contract, when to use disclose(), the difference between shielded and unshielded tokens, and the common mistakes that accidentally leak private information.

Prerequisites

  • Midnight toolchain installed (installation guide)
  • Basic familiarity with Compact. If you have not worked through the hello world tutorial, start there
  • Node.js installed for running tests

The three layers of data

Every Midnight smart contract works with data at three distinct layers. Getting clarity on these layers is the foundation of good privacy design.

Public ledger state is stored on-chain and is visible to anyone. Every field you declare with ledger lives here, regardless of whether you add export. This is the permanent, verifiable record of the contract's state.

Private state lives off-chain in the user's wallet or node. It is never written to the blockchain. It is brought into circuits through witness functions, which act as a bridge between the off-chain world and the on-chain proof. Private state is the only category of data that is genuinely hidden.

The transaction transcript is what gets revealed when a transaction is submitted. Every call to disclose() in your circuit contributes to this transcript. The transcript is public and permanent.

Understanding which layer your data belongs to is the first question you should answer when designing a contract.

Exported vs. non-exported ledger fields

Both export ledger and ledger (without export) store data on-chain. The difference is not about privacy.

pragma language_version 0.23;

import CompactStandardLibrary;

// Exported: visible to TypeScript clients and other contracts via ledger()
export ledger memberCount: Counter;
export ledger registry: Map<Bytes<32>, Bytes<32>>;

// Non-exported: still stored on-chain, not part of the generated Ledger type
ledger operationCount: Counter;

Enter fullscreen mode Exit fullscreen mode

export ledger memberCount makes the field accessible through the generated ledger() function in TypeScript. It also makes it callable from other Compact contracts that import this one.

ledger operationCount without export is still stored on-chain. Anyone querying the raw contract state on the blockchain can read it. What changes is that it does not appear in the generated TypeScript Ledger type, so TypeScript clients cannot access it through the standard API.

The test below demonstrates this distinction:

const state = ledger(circuitContext.currentQueryContext.state);

// memberCount is exported - accessible through the generated Ledger type
expect(state.memberCount).toBe(1n);

// operationCount is not exported - undefined in the TypeScript API
// It is still on-chain, just not surfaced by the generated bindings
expect((state as any).operationCount).toBeUndefined();

Enter fullscreen mode Exit fullscreen mode

The rule: use export to control your contract's public interface, not to control privacy. If you want something to stay private, it must not go into ledger state at all. It belongs in private state, managed through witness functions.

Private state: the only true privacy

Private state is data that never touches the blockchain. In Compact, you access it through witness declarations:

witness getCallerSecret(): Bytes<32>;

Enter fullscreen mode Exit fullscreen mode

When a circuit calls this witness, the TypeScript runtime provides the value from the user's private state. The value is used inside the zero-knowledge proof but never written to the ledger. The proof confirms that the circuit ran correctly without revealing what the secret was.

This is the mechanism behind Midnight's privacy guarantees. If you need to store a user's identity, a private balance, or any sensitive value, it must live in private state and be accessed through witnesses. Putting it in a non-exported ledger field achieves nothing from a privacy standpoint.

Understanding disclose()

Every circuit parameter is a private witness by default. When a private value needs to interact with the public ledger, you must explicitly mark that transition with disclose().

In the registry contract, both the id and data parameters are private circuit inputs. Since they are being written into the public ledger, they must be disclosed:

export circuit register(id: Bytes<32>, data: Bytes<32>): [] {
    assert(!registry.member(disclose(id)), "id already registered");
    registry.insert(disclose(id), disclose(data));
    memberCount.increment(1);
    operationCount.increment(1);
}

Enter fullscreen mode Exit fullscreen mode

The disclose() call tells the compiler: this value is moving from the private witness domain into the public transaction transcript. It is a deliberate, explicit act. The compiler enforces this - you cannot write a private value to the public ledger without disclosing it first.

What does not need disclose() is any computation that stays private. If you compute something from a private input and the result never touches the ledger, no disclosure is needed.

Common mistake 1: thinking non-exported means private

This is the most widespread misconception. A developer adds an internal tracking counter, omits export because it is "internal," and assumes no one can see it. But the data is on-chain. Anyone running a node or querying raw contract state can read every ledger field, exported or not.

If your field tracks something sensitive, such as a per-user action count or an internal identifier, it must not be a ledger field at all. Use private state instead.

Common mistake 2: disclosing intermediate values that leak private state

disclose() does not just reveal the value you pass it. It reveals information about where that value came from.

Consider a circuit that checks whether a user's secret key belongs to a known set:

// MISTAKE: disclosing an intermediate value derived from a private input
export circuit badCheck(secret: Bytes<32>): Boolean {
    const derived = someTransformation(secret);
    return registry.member(disclose(derived));
}

Enter fullscreen mode Exit fullscreen mode

Even though secret itself is never disclosed, disclosing derived reveals that the caller knows a value that maps to derived through someTransformation. If that transformation is known or guessable, an observer can narrow down what secret must be.

The rule is to disclose only what must be public, and nothing more. If the only reason a value is being disclosed is because it touches the ledger, ask whether the ledger interaction itself can be restructured to avoid the exposure.

Common mistake 3: accidental Merkle path disclosure

Merkle trees are a common tool for proving membership in a large set without revealing the full set. The membership proof is a MerkleTreePath, which contains two things: the sibling hashes along the path from the leaf to the root, and the leaf's index (its position in the tree).

If you disclose the full path, you reveal the leaf's index. Since leaves are inserted in order, the index corresponds directly to when the user was added to the set. This can de-anonymize users by linking their position to a timestamp or insertion order.

// PRIVACY RISK: disclose(path) reveals leaf.index - the user's position in the tree
export circuit riskyVerify(leaf: Bytes<32>): [] {
    const path = findLeaf(leaf);
    assert(allowlist.checkRoot(merkleTreePathRoot<20, Bytes<32>>(disclose(path))));
}

Enter fullscreen mode Exit fullscreen mode

The correct pattern keeps the path entirely private. The path is used inside the zero-knowledge circuit to compute the root. Only the root - which is already public ledger state - is checked:

// PREFERRED: path stays private, only the computed root is compared against public state
export circuit safeVerify(leaf: Bytes<32>): [] {
    const path = findLeaf(leaf);
    assert(allowlist.checkRoot(merkleTreePathRoot<20, Bytes<32>>(path)));
}

Enter fullscreen mode Exit fullscreen mode

The merkleTreePathRoot circuit recomputes the root from the path entirely inside the ZK proof. The path itself never enters the transaction transcript.

Shielded vs. unshielded tokens

Token transfers introduce a separate privacy dimension. Unshielded tokens record the transferred amount on-chain. Anyone can see who sent what to whom. Shielded tokens use ZK proofs to keep the amount and the recipient hidden. Only the sender and recipient know the details.

When choosing between them, start with this question: does the amount of this transfer need to be public?

For a payment in a public marketplace, unshielded is appropriate. The amount is part of the public record of the trade. For a private payroll, a confidential investment, or any transfer where the amount reveals sensitive information, shielded tokens are the right choice.

A secondary consideration is coin color. Shielded coins carry a color field that identifies the token type. Even with shielded transfers, the token type is visible. If the token type itself is sensitive information, that is a separate design problem that requires a different approach.

Decision trees for common patterns

Where does this data belong?

  • Does it need to be verified by the circuit and persist across transactions?
    • Yes, and it can be public: use export ledger
    • Yes, but only needed inside this contract: use ledger (note: still on-chain)
    • Yes, but it must stay private: use private state via a witness function
  • No, it is only needed for one computation: keep it as a local variable in the circuit

Does this value need disclose()?

  • Is it a circuit parameter being written to the ledger? Yes: wrap in disclose()
  • Is it being passed to a ledger operation like registry.member() or registry.insert()? Yes: wrap in disclose()
  • Is it an intermediate value derived from a private input, not touching the ledger? No: do not disclose it
  • Is it a MerkleTreePath used only to compute a root? No: pass it directly to merkleTreePathRoot() without disclosing

Shielded or unshielded tokens?

  • Must the transfer amount stay private? Yes: shielded
  • Is the transfer part of a public record? Yes: unshielded
  • Is auditability by a third party required? Unshielded or shielded with selective disclosure

What you have built

The registry smart contract in this tutorial demonstrates:

  • Declaring export ledger fields that are accessible via the generated TypeScript API
  • Declaring non-exported ledger fields that are on-chain but not surfaced in TypeScript bindings
  • Using disclose() correctly when writing private circuit inputs to the public ledger
  • The test that shows operationCount is absent from the generated Ledger type even though it exists on-chain

The key takeaway: privacy on Midnight is not a default. It is something you design for deliberately by choosing the right data layer, using witness functions for sensitive data, and being precise about what disclose() exposes.

Next steps

  • Read the Compact language reference for the full specification of ledger types and witness functions
  • Explore the Midnight developer documentation to understand how private state is managed in a full DApp
  • Try building a contract that combines a public Map registry with a private Merkle tree membership proof to see both patterns working together