Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement a Confidential Smart Contract for Health Data Access

A developer tutorial for building smart contracts that process encrypted health data using Trusted Execution Environments (TEEs) and verifiable off-chain computation.
Chainscore © 2026
introduction
PRACTICAL TUTORIAL

How to Implement a Confidential Smart Contract for Health Data Access

A step-by-step guide to building a smart contract that manages health data with privacy, using confidential computing and zero-knowledge proofs.

Confidential smart contracts for health data combine blockchain's auditability with advanced privacy technologies like zero-knowledge proofs (ZKPs) and trusted execution environments (TEEs). Unlike public smart contracts where all data is visible, confidential contracts process sensitive information—such as patient diagnoses or genomic data—in an encrypted or private state. This enables use cases like selective data sharing for clinical trials, automated insurance claims without exposing personal details, and secure health record audits. The core challenge is to verify that computations on private inputs were performed correctly, which is where ZKPs and hardware-based TEEs provide cryptographic or hardware-backed guarantees.

To implement a basic system, you first define the access control logic and data schema. A typical contract might manage patient records where each record is encrypted and stored off-chain (e.g., on IPFS or a decentralized storage network), with only a cryptographic hash or commitment stored on-chain. The smart contract holds the access rules. For example, using the OpenZeppelin access control library, you can assign roles like PATIENT, DOCTOR, or RESEARCHER. A patient can grant access to a doctor's public key, and the contract emits an event logging this permission change without revealing the underlying data.

The critical privacy component is proving data validity without exposure. For a ZKP-based approach, you could use a circuit written in Circom or Noir to prove that a patient's data satisfies a condition (e.g., "age > 18") without revealing the actual age. The verifier contract, often deployed on a chain like Ethereum or a zkRollup, would verify this proof. For TEE-based confidentiality, a service like Oasis Sapphire or Secret Network executes contract logic inside secure enclaves (e.g., Intel SGX). Here, encrypted data is sent to the enclave, processed in memory, and only the result (e.g., "eligibility: true") is returned and recorded on-chain.

A practical code snippet for an access grant function in a Solidity-based contract using a ZKP verifier might look like this:

solidity
function grantAccess(address grantee, bytes32 dataCommitment, Proof calldata zkProof) public {
    require(hasRole(PATIENT_ROLE, msg.sender), "Not a patient");
    require(verifyZKProof(zkProof, dataCommitment), "Invalid proof");
    _accessList[grantee][dataCommitment] = true;
    emit AccessGranted(msg.sender, grantee, dataCommitment);
}

The verifyZKProof function would call a pre-deployed verifier contract for a zk-SNARK, ensuring the patient actually owns the data referenced by the dataCommitment.

Key considerations for deployment include cost (ZKPs have high gas fees for verification, TEEs may have lower compute overhead), trust assumptions (TEEs rely on hardware manufacturers, ZKPs are trustless but complex), and data availability. Always use established libraries for cryptographic operations and conduct thorough audits. Platforms like Aztec Network for private L2s or Oasis Protocol for TEE-based smart contracts provide specialized environments that abstract some complexity, allowing developers to focus on application logic while maintaining strong confidentiality guarantees for sensitive health information.

prerequisites
CONFIDENTIAL SMART CONTRACTS

Prerequisites and Setup

Before building a confidential smart contract for health data, you must establish a secure development environment and understand the core technologies involved.

To implement a confidential smart contract for health data, you need a foundational understanding of blockchain development and privacy-preserving technologies. This includes proficiency with a general-purpose language like JavaScript or Python, and familiarity with Ethereum concepts such as accounts, gas, and transactions. You should also be comfortable with the command line and using package managers like npm or yarn. For handling sensitive data, a basic grasp of cryptographic primitives—such as public-key encryption and zero-knowledge proofs—is highly beneficial, though not strictly required to get started.

The primary tool for this tutorial is the Aztec Network, a Layer 2 zk-rollup focused on programmable privacy. You will write your contract using Noir, a domain-specific language for creating zero-knowledge circuits. First, install the Noir development environment. Using npm, run npm install -g @noir-lang/noir_wasm @noir-lang/aztec_backend. This installs the Noir compiler and the Aztec backend, which allows you to compile circuits into an Aztec-compatible format. Verify your installation by running nargo --version.

Next, set up a local development network. The easiest method is to use the Aztec Sandbox, a Docker container that runs a local Aztec node, a sequencer, and a prover. Pull and run the sandbox with docker run -p 8080:8080 -p 8081:8081 -it aztecprotocol/aztec-sandbox. This provides a local RPC endpoint at http://localhost:8080 and a PXE (Private eXecution Environment) at http://localhost:8081. The PXE is a client-side component that manages user keys and note databases, essential for interacting with private state.

With the sandbox running, initialize a new Noir project. Create a directory for your contract and run nargo new health_data_contract. This generates a src/main.nr file for your circuit logic and a Nargo.toml project manifest. You will also need the Aztec.nr library, which provides Aztec-specific types and functions for managing private and public state. Add it as a dependency in your Nargo.toml under [dependencies] with aztec = { git = "https://github.com/AztecProtocol/aztec-packages" }.

Finally, you'll need a wallet to deploy and interact with your contract. For development, use the Aztec.js SDK. Create a new Node.js project and install it: npm install @aztec/aztec.js. You can then generate accounts using the createAccount method from the SDK, which connects to your local sandbox's PXE. This account will hold the encryption keys necessary to decrypt private notes on-chain. Ensure your development environment is isolated and secure, as you will be working with simulated private keys and data structures.

architecture-overview
TUTORIAL

System Architecture: On-Chain and Off-Chain Components

A practical guide to building a confidential smart contract system for managing sensitive health data, detailing the roles of on-chain logic and off-chain computation.

A confidential smart contract for health data requires a hybrid architecture that separates public verification from private computation. The on-chain component is a standard smart contract deployed on a blockchain like Ethereum or Polygon. Its primary role is to manage access control policies, log permission events, and store cryptographic commitments (hashes) of data—never the raw data itself. The off-chain component is a secure, trusted execution environment (TEE) or a zero-knowledge proof prover that handles all sensitive operations, such as decrypting data, running computations, and generating verifiable proofs of correct execution.

The core workflow begins when a user (e.g., a patient) encrypts their health data and sends it to the off-chain service. This service stores the encrypted data and computes a hash, posting this commitment to the on-chain contract. When a researcher requests access, they call the contract, which checks their permissions. If authorized, the off-chain service retrieves the encrypted data, performs the approved computation (like calculating an average), and generates a zero-knowledge proof (ZKP) or a TEE attestation. This proof, which verifies the computation was performed correctly without revealing the inputs, is then submitted back to the on-chain contract for validation and final approval.

Key technologies enable this separation. For off-chain computation, zk-SNARKs (via Circom or Halo2) or TEEs like Intel SGX or AWS Nitro Enclaves provide the confidential environment. On-chain, verifier contracts (often auto-generated from the proof system) check the submitted proofs. A common pattern uses the EIP-3668 "CCIP Read" standard for secure off-chain data retrieval. This ensures the blockchain remains a lightweight, immutable ledger of permissions and verifications, while the heavy lifting of privacy-preserving computation happens off-chain in a secure enclave.

Implementing this requires careful design. Start by defining the on-chain interface for access requests and proof verification using a framework like Foundry or Hardhat. For the off-chain prover, set up a ZKP circuit that takes encrypted inputs and a public researcher query, outputting the result and a proof. A service like zkKit or a custom Rust service using the arkworks library can generate these proofs. The on-chain contract must then validate the proof against a known verification key. This architecture balances transparency and privacy, making it suitable for HIPAA-compliant applications or clinical trial data management.

Security considerations are paramount. The off-chain component must be robust against side-channel attacks if using a TEE. For ZKPs, ensure the trusted setup ceremony is conducted securely if required. Always use standard, audited cryptographic libraries. The on-chain contract should include emergency pause functions and role-based access control (using OpenZeppelin's AccessControl). Furthermore, consider data availability—while the raw data is off-chain, its encrypted form should be stored in a decentralized manner, such as on IPFS or Arweave, with the content identifier (CID) stored on-chain for redundancy and censorship resistance.

This architecture demonstrates how blockchain's trustless verification can be extended to private data. By combining on-chain governance with off-chain confidential computing, developers can build applications that respect user privacy while providing verifiable and auditable data utility. The next step is to prototype using frameworks like Semaphore for anonymous credentials or Aztec Network for private smart contracts, which abstract much of this complexity.

key-concepts
IMPLEMENTATION GUIDE

Key Concepts for Confidential Computing

Build a confidential smart contract for health data. This guide covers the core concepts, tools, and design patterns for creating privacy-preserving applications on blockchain.

03

Designing the Data Flow

A secure architecture separates public logic from private computation. A typical flow for health data access:

  1. Encrypted Input: Patient data is encrypted client-side and sent to the contract.
  2. Enclave Processing: The contract's confidential function decrypts data inside the TEE, processes it (e.g., calculates a risk score), and encrypts the result.
  3. Selective Output: Only the necessary, minimal output (e.g., "authorized" or a specific metric) is released on-chain. Raw data never leaves the enclave.
05

Managing Access Control & Keys

Confidentiality requires robust key management. Critical patterns include:

  • Threshold Encryption: Data is encrypted to a public key, requiring multiple private key shares (held by authorized entities) to decrypt within the TEE.
  • Consent Receipts: Store permission grants (e.g., patient signatures) on-chain as verifiable, public records, while the accessed data remains private.
  • Key Rotation: Implement policies for periodically updating encryption keys to maintain long-term security.
IMPLEMENTATION GUIDE

Comparison of TEE Platforms for Blockchain

Key architectural and operational differences between leading TEE providers for confidential smart contracts.

Feature / MetricIntel SGXAMD SEV-SNPAWS Nitro Enclaves

Trusted Execution Environment Type

CPU Enclave

Virtual Machine

Virtual Machine

Memory Encryption

Enclave Page Cache (EPC)

Transparent SME & SEV

Nitro Hypervisor

Attestation Service

Intel Attestation Service (IAS)

AMD Key Distribution Server (KDS)

AWS Nitro Attestation

Native Blockchain SDK Support

Maximum Enclave Memory

128 MB (Standard), 256 GB (Flex)

Varies by VM size

Varies by instance type

Remote Attestation Latency

< 500 ms

1-2 seconds

< 300 ms

Monthly Cost for Baseline Node

$50-100

$40-80

$70-120

Open-Source Tooling Maturity

High (Open Enclave SDK)

Medium (AMD SEV-Tool)

Low (AWS Proprietary)

step1-contract-design
CORE ARCHITECTURE

Step 1: Design the On-Chain Access Control Contract

This step defines the smart contract that will manage permissions for accessing encrypted health data, establishing a transparent and immutable record of who can decrypt what.

The foundation of a confidential health data system is an on-chain access control contract. This smart contract does not store sensitive data; instead, it acts as a permission registry and policy engine. Its primary functions are to store public encryption keys, manage access control lists (ACLs), and emit events for off-chain listeners. For health data, this contract must enforce policies like patient consent, provider authorization, and audit trail logging. A common design pattern is to use a mapping, such as mapping(address patient => mapping(address entity => uint256 expiry)) public accessGrants, to track permissions with expiration timestamps.

A robust design implements a role-based access control (RBAC) system. Key roles include the PATIENT (data owner), PROVIDER (e.g., a hospital address), RESEARCHER (with anonymized data access), and AUDITOR. The contract should include functions like grantAccess(address grantee, uint256 dataId, uint256 expiry), which can only be called by the patient, and revokeAccess(address grantee, uint256 dataId) for immediate permission removal. It's critical to include event emissions (e.g., AccessGranted, AccessRevoked) for every state change. These events allow an off-chain gateway service or oracle to react and manage the corresponding decryption keys.

For handling complex policies, consider integrating with a policy engine like the Open Policy Agent (OPA) via an oracle, or implementing zk-SNARKs for privacy-preserving proof of eligibility. The contract must also account for emergency access scenarios, often requiring a multi-signature or decentralized identity (DID) attestation. Security is paramount; use established libraries like OpenZeppelin's AccessControl for role management and ensure all state-changing functions are protected against reentrancy and access control vulnerabilities. The final contract becomes the single source of truth for access rights, enabling a system where data remains encrypted off-chain but is governed transparently on-chain.

step2-tee-enclave
CONFIDENTIAL COMPUTING

Step 2: Build the Off-Chain TEE Enclave Application

This guide details the implementation of a secure enclave application that processes sensitive health data off-chain, acting as the trusted execution environment for a confidential smart contract.

The off-chain application runs inside a Trusted Execution Environment (TEE), such as an Intel SGX enclave or an AMD SEV secure VM. This isolated environment ensures that health data—like patient records or genomic sequences—is processed in encrypted memory, invisible to the host operating system, cloud provider, and even the application developer. The enclave's code and attestation are cryptographically measured, allowing the on-chain contract to verify its integrity before sending any sensitive data.

Your application needs two core components: an attestation handler and a confidential logic module. The attestation handler generates a remote attestation report (e.g., an Intel SGX quote) when initialized. This report is submitted to the blockchain to prove the enclave is running the expected, unmodified code on genuine hardware. The smart contract verifies this report against a known Measurement (MRENCLAVE) and the hardware vendor's attestation service before granting the enclave permission to interact with it.

The confidential logic module contains the actual business rules for processing data. For a health data access contract, this might involve: - Checking a patient's consent token. - Decrypting incoming medical records using a key sealed inside the enclave. - Running a specific analysis, like calculating a risk score from lab results. - Producing an encrypted, verifiable result (or zero-knowledge proof) to return to the blockchain. All operations occur within the TEE's secure perimeter.

Develop this application using a TEE SDK like the Intel SGX SDK or the Occlum LibOS for Gramine. The code must be structured to separate trusted (enclave) and untrusted (host) components. Critical secrets, such as the decryption key for health data, should be provisioned securely into the enclave upon attestation, often via a remote secure channel established with the blockchain verifier.

Finally, the enclave exposes a well-defined API for the on-chain contract to call. This is typically done via an off-chain worker or oracle pattern. The smart contract emits an event with encrypted input data. An off-chain listener relays this to the enclave application. After processing, the enclave signs the result with its attested key and posts it back to the chain via a transaction, completing the confidential computation loop without exposing the raw input data.

step3-attestation-verification
SECURITY LAYER

Step 3: Implement Remote Attestation and Verification

This step establishes trust in the off-chain enclave by cryptographically proving its integrity and the code it's running.

Remote attestation is the cryptographic process that allows a client (like our blockchain contract) to verify that a specific piece of code is running securely inside a genuine Intel SGX enclave on a remote server. It creates a verifiable report that includes the enclave's measurement (a hash of its initial code and data), the identity of the platform, and a signature from the Intel Attestation Service (IAS). For our health data contract, this proves that the sensitive access control logic is executing in a trusted environment, not on a compromised server.

The verification flow involves several components. First, the enclave generates a quote, which is a signed report containing its measurement. This quote is sent to the Intel Attestation Service via a Relying Party (your backend service). The IAS validates the quote against Intel's root keys and returns an attestation verification report. Your smart contract must then verify this report's signature and check that the enclosed measurement matches the expected hash of your trusted enclave code, often stored as a constant (ENCLAVE_MRENCLAVE).

Here is a simplified Solidity function outline for on-chain verification. It checks the report's signature using Intel's root CA and validates the critical mrEnclave value.

solidity
function verifyAttestationReport(
    bytes memory quote,
    bytes memory iasSignature,
    bytes memory signingCert,
    bytes memory enclaveMrEnclave
) public view returns (bool) {
    // 1. Verify the signing certificate chain leads to Intel's root CA.
    require(verifyCertificateChain(signingCert), "Invalid cert chain");
    
    // 2. Verify the IAS signature over the quote.
    bytes32 quoteHash = sha256(quote);
    require(verifyIASSignature(iasSignature, quoteHash, signingCert), "Bad IAS sig");
    
    // 3. Parse the quote to extract the `mrEnclave` measurement.
    bytes32 reportedMrEnclave = extractMrEnclaveFromQuote(quote);
    
    // 4. Ensure it matches our trusted, hardcoded value.
    require(reportedMrEnclave == enclaveMrEnclave, "Enclave mismatch");
    return true;
}

After successful on-chain verification, the contract can trust the public key presented by the enclave. This key is typically generated inside the enclave during initialization and is included in the attestation data. The contract should store this attestation-approved public key and use it to encrypt any sensitive data (like a data decryption key) sent to the enclave, or to verify signatures on responses from the enclave. This establishes a secure channel between the blockchain and the proven trusted execution environment.

For production, you must integrate with Intel's services. Use the Intel SGX DCAP (Data Center Attestation Primitives) library for quote generation on the server side. Your relying party service will interact with the Intel Provisioning Certification Service (PCS) to verify quotes. Consider using a library like sgx-ssl or a framework such as Occlum or Gramine to simplify enclave development and attestation. Always hardcode the expected MRENCLAVE value from your final, audited build into the contract.

This step is critical for regulatory compliance (like HIPAA) in a health data context, as it provides an auditable, cryptographic proof that data is only processed by authorized, unaltered code. Failure to properly implement attestation renders the entire confidential smart contract model insecure, as there is no guarantee the off-chain component hasn't been tampered with to leak private information.

step4-data-flow-integration
IMPLEMENTATION

Step 4: Integrate the Data Flow and Sealing

This step connects the contract's components to enforce a secure, auditable data access flow, culminating in the cryptographic sealing of patient consent.

With the core contract logic and data structures defined, the final implementation phase wires everything together. The primary function orchestrates the entire access request lifecycle. It must validate the requester's role and permissions, check the patient's active consent status, log the access event immutably, and finally, return the requested data. This function acts as the single entry point, ensuring all security and policy checks are executed in the correct sequence before any data is released.

Critical to this flow is the integration of the consent sealing mechanism. Upon successful access, the contract must generate a cryptographic proof. Using a construct like keccak256(abi.encodePacked(patientId, requesterId, timestamp, dataHash)), it creates a unique, tamper-evident seal. This hash is then stored in the AccessRecord and can be emitted in an event. This seal serves as an unforgeable receipt, allowing patients to cryptographically audit who accessed their data and when, which is essential for compliance with regulations like HIPAA or GDPR.

The contract should emit detailed events at each major state transition. Key events include ConsentGranted, ConsentRevoked, and DataAccessed. These events are crucial for off-chain applications. A user's dashboard or an auditor's monitoring tool can listen for these events to update UIs in real-time or populate audit logs without needing to query the chain state repeatedly, improving efficiency and user experience.

Consider implementing a withdrawal pattern for emergency scenarios. Instead of sending data directly to the requester's address, the contract can assign it to them internally. A separate withdrawData function then allows the requester to claim it. This pattern prevents malicious contracts from being able to execute arbitrary code in the middle of your sensitive data flow (a reentrancy attack), adding a critical layer of security for high-stakes health data.

Finally, thorough testing is non-negotiable. Write comprehensive unit tests (using Foundry or Hardhat) that simulate the full flow: granting consent, requesting data with valid and invalid permissions, revoking consent, and testing edge cases. Include tests for the sealing mechanism to verify the hash output is consistent and unique for each access event. This ensures the contract behaves predictably and securely before deployment to a testnet or mainnet environment.

DEVELOPER FAQ

Frequently Asked Questions

Common technical questions and solutions for building confidential smart contracts that handle sensitive health data on-chain.

A confidential smart contract is a program that executes on a blockchain while keeping its internal state and inputs/outputs encrypted. Unlike a regular smart contract where all data is public, confidential contracts use cryptographic techniques like zero-knowledge proofs (ZKPs) or trusted execution environments (TEEs) to compute over encrypted data.

Key differences:

  • Data Privacy: Patient health records, access logs, and computation results remain encrypted on-chain.
  • Selective Disclosure: Data can be proven to satisfy conditions (e.g., "patient is over 18") without revealing the underlying data.
  • On-Chain Verification: The network verifies the correctness of the private computation via cryptographic proofs, maintaining blockchain integrity.

Common protocols for implementation include zk-SNARKs (e.g., with Circom), Aztec Network, and Oasis Network with Sapphire TEEs.

conclusion-next-steps
IMPLEMENTATION GUIDE

Conclusion and Next Steps

You have now implemented a confidential smart contract for secure health data access. This guide covered the core concepts of zero-knowledge proofs, on-chain verification, and privacy-preserving data handling.

This implementation demonstrates a foundational pattern for building privacy-first applications on public blockchains. By using zero-knowledge proofs (ZKPs) through frameworks like Circom and SnarkJS, you can verify sensitive conditions—such as a patient's age or vaccination status—without revealing the underlying data. The smart contract acts as a trustless verifier, enabling controlled data access for insurers or researchers while maintaining patient confidentiality. This architecture is critical for compliance with regulations like HIPAA and GDPR in decentralized systems.

To extend this project, consider integrating with oracles like Chainlink to fetch real-world medical credentials or test results verifiably. You could also explore more complex proof circuits for multi-party computations, such as proving an individual's health metrics fall within a normal range across a dataset. For production, audit your Circom circuits with tools like Picus and implement robust key management for the trusted setup ceremony. The Semaphore framework offers advanced primitives for anonymous signaling in such systems.

The next step is to build a frontend interface using a library like ethers.js or viem to allow users to generate proofs client-side. A practical workflow involves: 1) a patient submitting encrypted data to IPFS or a decentralized storage service, 2) generating a ZKP locally in their browser, and 3) submitting the proof to the verifier contract. For scalability, look into zkRollups like zkSync or Polygon zkEVM to batch transactions and reduce costs. Always prioritize security by using established libraries and conducting thorough testing on testnets before any mainnet deployment.

How to Build a Confidential Smart Contract for Health Data | ChainScore Guides