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

Setting Up a Patient-Centric Health Data Wallet

A developer tutorial for building a self-sovereign health data wallet that aggregates and controls access to medical records using W3C Verifiable Credentials.
Chainscore © 2026
introduction
GUIDE

Setting Up a Patient-Centric Health Data Wallet

A technical walkthrough for developers to implement a self-sovereign health data wallet using decentralized identity and verifiable credentials.

A patient-centric health data wallet is a digital tool that allows individuals to own, manage, and share their health information. Unlike traditional systems where data is siloed within provider networks, these wallets leverage decentralized identity (DID) standards and verifiable credentials (VCs) to give users cryptographic control. The core components are a secure digital wallet app, a DID method (like did:ethr or did:key), and a mechanism to request, store, and present VCs from issuers like hospitals or labs. This architecture shifts control from institutions to the individual, enabling selective data sharing for telehealth, clinical trials, or personal health records.

The first step is generating a Decentralized Identifier (DID) for the user. A DID is a globally unique identifier that is independent of any central registry. Using a library like did-jwt-vc or daf, you can create a DID linked to a user's cryptographic keys. For example, an Ethereum-based DID (did:ethr) might be generated from a new Ethereum account. The private key remains securely in the user's wallet, while the public DID document is recorded on a blockchain or other decentralized network, providing a trust anchor for verifiable interactions without revealing personal data.

Next, the wallet must be able to receive and store Verifiable Credentials. A VC is a tamper-evident credential, like a digital vaccination record or lab result, issued by a trusted entity (the issuer). It is cryptographically signed and contains claims about the user. The wallet receives these as JWTs or JSON-LD documents. Secure storage is critical; credentials should be encrypted locally on the user's device. The wallet's core function is to allow the user to selectively disclose these credentials. For instance, when applying for a gym membership, the user could present only a "cleared for exercise" attestation from their doctor, without revealing their full medical history.

The final key capability is presenting proofs. When a third party (a verifier) requests data, the wallet creates a verifiable presentation. This is a package of one or more VCs, often with zero-knowledge proofs (ZKPs) to enhance privacy. Using ZKPs, a user can prove they are over 18 from a government ID VC without revealing their birth date. A library like @veramo/core can handle this presentation logic. The verifier receives the presentation, checks the cryptographic signatures against the issuer's public DID, and validates the proof, all without needing to call the original issuer—this is the power of decentralized verification.

For developers, implementing a basic flow involves integrating SDKs like Veramo or Trinsic. A typical code snippet to create a presentation might look like:

typescript
const presentation = await agent.createVerifiablePresentation({
  presentation: {
    holder: userDid,
    verifiableCredential: [vaccinationCredentialJWT],
  },
  proofFormat: 'jwt',
});

The ecosystem relies on open standards from W3C (DID, VC) and DIF (Identity Hubs). Successful implementations, such as those by Evernym or the EU's ESSIF framework, demonstrate the viability of this model for creating interoperable, user-controlled health data systems.

prerequisites
PREREQUISITES AND SETUP

Setting Up a Patient-Centric Health Data Wallet

A health data wallet is a self-sovereign identity (SSI) application that allows individuals to store, manage, and share their verifiable health credentials. This guide covers the technical prerequisites and initial setup for developers building on decentralized identity protocols.

Before writing any code, you need to understand the core components of a health data wallet. The system relies on Verifiable Credentials (VCs) and Decentralized Identifiers (DIDs). A DID is a unique, user-controlled identifier (e.g., did:key:z6Mk...) that does not depend on a central registry. VCs are tamper-evident digital claims, like a vaccination record or lab result, issued by a trusted entity (an issuer) and cryptographically signed. The wallet, acting as a holder, stores these VCs and can generate Verifiable Presentations to share specific data with a verifier, such as a hospital or insurance provider.

Your development environment requires specific tools and libraries. For a JavaScript/TypeScript stack, essential packages include did-resolver and universal-resolver for resolving DIDs to their DID Documents, and a VC library like vc-js or Veramo for creating and verifying credentials. You will also need a key management system; @stablelib/ed25519 is a common choice for generating the EdDSA key pairs used by many DID methods. For persistent storage of credentials and private keys, consider IndexedDB for browser-based wallets or SQLite for mobile applications using frameworks like React Native.

The first setup step is to generate a DID for the user. Using the did:key method is straightforward for development. The process involves creating a new public/private key pair and formatting it into a DID document. Here's a simplified example using @stablelib/ed25519:

javascript
import { generateKeyPair } from '@stablelib/ed25519';
const keyPair = generateKeyPair();
// Convert public key to multibase encoding for DID
const did = `did:key:z6Mk${publicKeyMultibase}`;

The private key must be stored securely, as it represents the user's control over their identity. Never store it in plaintext or transmit it over the network.

Next, configure a resolver to interact with the DID ecosystem. You need to resolve DIDs from issuers and verifiers to fetch their public keys and service endpoints. Set up a universal resolver instance or use a lightweight, method-specific resolver. For did:web and did:key, you can use the web-did-resolver and key-did-resolver packages. This resolver will be passed to your VC library to enable signature verification during the credential issuance and presentation flows.

Finally, plan your data model and storage schema. A health wallet must store multiple types of objects: the user's own DID and keys, received Verifiable Credentials (storing the full JWT or JSON-LD proof), and metadata about interactions with issuers and verifiers. Structure your database to allow efficient querying of credentials by type (e.g., "Immunization"), issuer DID, and expiration date. Implement robust backup and recovery mechanisms, such as encrypted seed phrase exports, as losing the private key means losing access to all credentials.

architecture-overview
SYSTEM ARCHITECTURE AND DATA FLOW

Setting Up a Patient-Centric Health Data Wallet

A patient-centric health data wallet is a self-sovereign identity (SSI) application that gives individuals control over their medical records. This guide explains the core architectural components and data flow required to build one.

The foundation is a decentralized identifier (DID). This is a globally unique, cryptographically verifiable identifier that the patient owns, independent of any centralized registry. It is typically anchored to a public blockchain like Ethereum or a dedicated ledger such as ION on Bitcoin. The DID is paired with a DID Document containing public keys, which enables secure authentication and interaction with other entities without revealing personal information.

Health data itself is stored off-chain for privacy, scalability, and cost efficiency. Common storage solutions include the user's local device, a personal cloud server, or decentralized storage networks like IPFS or Arweave. The on-chain DID only stores cryptographic proofs—specifically Verifiable Credentials (VCs)—that attest to the authenticity of the off-chain data. A VC is a tamper-evident credential, like a digital version of a doctor's note, issued and cryptographically signed by a trusted entity (e.g., a hospital).

The core data flow involves three roles: the Issuer (healthcare provider), the Holder (patient/wallet), and the Verifier (insurance company, new doctor). First, an Issuer signs a VC containing health data and sends it to the Holder's wallet. The wallet stores the VC and its associated off-chain data. When a Verifier needs proof, the Holder presents a Verifiable Presentation (VP)—a selective disclosure of specific credentials—without exposing the raw data or other unrelated records.

For developers, implementing this requires a wallet SDK like Trinsic, Veramo, or Serto. A typical setup involves generating a DID, creating a secure local storage vault for credentials, and integrating with a VC issuer API. Code to create a simple DID with the Veramo framework might look like:

typescript
import { createAgent } from '@veramo/core';
import { DIDManager } from '@veramo/did-manager';
const agent = createAgent({ plugins: [new DIDManager()] });
const identifier = await agent.didManagerCreate({ provider: 'did:ethr' });
console.log('New DID:', identifier.did);

Key architectural decisions include the DID method (e.g., did:ethr, did:key), the signature suite for VCs (like Ed25519Signature2018), and the presentation exchange protocol. Security is paramount; private keys must never leave the user's device, often secured in a hardware module or trusted execution environment. Interoperability is achieved by adhering to W3C standards for DIDs and VCs, ensuring the wallet can interact with systems from different healthcare providers and jurisdictions.

The final system enables patients to aggregate records from multiple sources, grant time-limited, granular access to verifiers, and revoke consent at any time. This shifts the paradigm from institution-held silos to a user-controlled, portable health data ecosystem, reducing administrative overhead and empowering individuals in their care journey.

core-components
HEALTH DATA WALLET ARCHITECTURE

Core Technical Components

Build a secure, user-controlled health data wallet using these essential Web3 primitives and protocols.

step1-did-creation
FOUNDATIONAL IDENTITY

Step 1: Generating Patient and Provider DIDs

The first step in building a patient-centric health data wallet is establishing decentralized identifiers (DIDs) for all participants. This creates the foundation for secure, verifiable digital identity without relying on a central authority.

A Decentralized Identifier (DID) is a globally unique, persistent identifier that an individual, organization, or device controls. Unlike traditional usernames or email addresses tied to a specific provider, a DID is anchored on a verifiable data registry, typically a blockchain or distributed ledger. For a health data wallet, this means the patient's identity is portable and sovereign, not locked into a single hospital's or app's database. The DID itself is a URI, such as did:ethr:0xabc123..., that resolves to a DID Document containing public keys and service endpoints.

Generating a DID for a patient involves creating a cryptographic key pair. The private key is securely stored in the user's wallet (often on their mobile device), while the public key is published to the DID Document. Using the ethr-did method on Ethereum, a patient's DID can be created from an Ethereum account. The process is self-sovereign; the user generates their own keys and registers the DID on-chain, often via a smart contract like the EthereumDIDRegistry. This establishes cryptographic proof of ownership that cannot be revoked by any intermediary.

Healthcare providers (e.g., clinics, labs, physicians) also need DIDs to participate in this trusted ecosystem. A provider's DID serves as their verifiable professional identity, allowing them to issue digitally signed health credentials (like vaccination records or lab results) to patient DIDs. The generation process is similar but may involve additional Verifiable Credentials attesting to the provider's accreditation, which are linked to their DID. This creates a web of trust where patients can cryptographically verify the source of their medical data.

The DID Document is critical. It's a JSON-LD file that declares the public keys for authentication and capability invocation, along with service endpoints for interacting with the identity holder. For a patient wallet, a key service endpoint might point to the wallet's encrypted data storage. The document is updated via transactions signed by the current controller's private key, ensuring only the legitimate owner can make changes. This mechanism enables key rotation and recovery protocols essential for long-lived digital identities.

Implementing this in practice requires choosing a DID method suitable for your stack, such as did:ethr for Ethereum-based systems or did:key for simpler, offline scenarios. Libraries like ethr-did-resolver and did-jwt-vc handle the complexity of creation, resolution, and verification. The outcome is a foundational layer where both patients and providers have cryptographically verifiable identities, setting the stage for the secure exchange of health credentials in Step 2.

step2-credential-issuance
SETTING UP A PATIENT-CENTRIC HEALTH DATA WALLET

Step 2: Issuing a Verifiable Health Credential

This step details the process of creating a secure, self-sovereign digital wallet for a patient, which will hold their private keys and serve as the foundation for receiving and managing Verifiable Credentials (VCs).

A health data wallet is a software application that allows a patient to generate and securely store a Decentralized Identifier (DID) and its associated cryptographic keys. Unlike a traditional account, a DID is not issued by a central authority; it is created by the user. The wallet's primary function is to manage the private key, which is used to sign transactions and prove control over the DID. Popular open-source libraries for implementing wallet logic include didkit from SpruceID and veramo, which provide APIs for key generation, DID document creation, and VC issuance workflows.

The technical setup begins with the wallet generating a key pair, typically using the Ed25519 signature scheme for its efficiency and security. This key pair is then used to create a DID following a method like did:key or did:jwk. For example, a did:key is essentially a public key encoded as a DID. The resulting DID Document is a JSON-LD file that contains the public key and service endpoints, describing how to interact with the DID holder. This document is not stored on a blockchain by default, preserving privacy, but its integrity can be cryptographically verified.

Once the patient's wallet is initialized, it must establish a secure communication channel with the Issuer (e.g., a hospital or lab). This is often done using a DIDComm protocol. The wallet presents its DID to the issuer, initiating a request for a credential. The issuer's system verifies the patient's identity through existing channels (like a patient portal login) and prepares the credential data. The actual issuance involves the issuer creating a digitally signed JSON object containing the health data, the patient's DID as the subject, and metadata defining the credential type and expiration.

step3-wallet-storage
TUTORIAL

Step 3: Wallet Implementation and Credential Storage

This guide walks through building a secure, patient-owned wallet for managing Verifiable Credentials (VCs) in a healthcare context, using modern Web3 standards.

A health data wallet is a self-sovereign application that allows patients to store, manage, and selectively share their Verifiable Credentials. Unlike a traditional crypto wallet, its primary function is to manage identity attestations—like a digital immunization record or a doctor's note—rather than fungible tokens. The core technical stack for such a wallet typically involves a Decentralized Identifier (DID) for the patient, a secure local storage mechanism for private keys, and a library for handling the W3C Verifiable Credentials data model. Popular frameworks include SpruceID's didkit or Microsoft's ION SDK for DID operations, paired with a React Native or Flutter frontend for mobile accessibility.

The first implementation step is generating and securing the user's cryptographic keys. For a DID, you'll create a keypair (e.g., using the ed25519 signature scheme) and derive a DID method like did:key or did:ion. The private key must never leave the user's device. Use platform-specific secure enclaves: Keychain Services on iOS or Android Keystore. Here's a conceptual snippet using @digitalbazaar/ed25519-verification-key-2020 library:

javascript
import { Ed25519VerificationKey2020 } from '@digitalbazaar/ed25519-verification-key-2020';

const keyPair = await Ed25519VerificationKey2020.generate();
// Store keyPair.privateKeyMultibase securely in device keystore
const did = `did:key:${zQ3s...}`; // Derived from public key

Once the DID is established, the wallet must handle Verifiable Credential lifecycle events: receiving, validating, storing, and presenting. When a healthcare issuer sends a signed VC (a JSON-LD document), the wallet must verify the issuer's signature and check the credential status. Store the VC in an encrypted local database (e.g., SQLite with SQLCipher or Realm). For presentation, the wallet creates a Verifiable Presentation (VP), signing it with the user's private key to prove control over the DID. This selective disclosure is crucial—a patient can share only their vaccination date from a credential without revealing their full medical history.

Interoperability is non-negotiable. Your wallet should support standard exchange protocols like DIDComm v2 for encrypted messaging with issuers/verifiers or OpenID for Verifiable Credentials (OIDC4VC) for web-based flows. Furthermore, consider implementing the W3C Verifiable Credentials API draft specification for a standardized interface. For user experience, design clear consent screens that show exactly what data is being requested by a verifier (a clinic's front desk app) and log all sharing events locally for audit. The ultimate goal is a wallet that is as secure as a hardware wallet for keys, as usable as a modern mobile app, and as interoperable as a web browser for the emerging decentralized identity ecosystem.

step4-data-access
PATIENT DATA SOVEREIGNTY

Step 4: Selective Disclosure and Data Access Control

Implement granular permissions for sharing health data, allowing patients to reveal specific information to providers without exposing their entire medical history.

Selective disclosure is the cryptographic principle that enables a user to prove a specific claim from a larger set of verifiable credentials without revealing the underlying data. In a health data wallet, this means a patient can prove they are over 18 for a clinical trial, or that their latest HbA1c level is below 7.0%, without showing their full lab report, date of birth, or other identifiers. This is typically achieved using zero-knowledge proofs (ZKPs) or BBS+ signatures, which allow for the creation of a derived, minimal proof from a signed credential.

To implement this, your wallet's architecture must separate the credential storage from the presentation logic. When a healthcare provider requests data, your application should present a clear consent interface asking, "What would you like to share?" Options could include: - Proof of age range (over 18) - Latest vaccination status (yes/no) - Specific lab result value (e.g., Cholesterol < 200 mg/dL). The user selects the exact claims, and the wallet uses a proving library (like anoncreds-rs or jsonld-signatures-bbs) to generate a Verifiable Presentation containing only those proofs.

Data access control extends beyond initial sharing to include temporal and contextual rules. Using standards like W3C's ODRL (Open Digital Rights Language) or UCANs (User Controlled Authorization Networks), you can encode permissions such as: - This ECG data can be accessed by Dr. Smith at Memorial Hospital for 30 days. - This prescription history can be used for research purposes but cannot be re-shared. These policies are signed by the patient and must be validated by the data holder (e.g., a decentralized storage node) before releasing any encrypted data.

Here is a simplified conceptual flow using pseudocode for a selective disclosure request:

javascript
// User holds a Verifiable Credential with multiple claims
const fullCredential = {
  "@context": "https://www.w3.org/2018/credentials/v1",
  "credentialSubject": {
    "id": "did:example:patient123",
    "age": 45,
    "bloodType": "O+",
    "covidVaccinated": true
  }
};
// Provider requests only proof of vaccination status
const presentationDefinition = {
  "requiredFields": ["covidVaccinated"]
};
// Wallet generates a ZK proof for the single claim
const verifiablePresentation = await wallet.createPresentation(
  fullCredential,
  presentationDefinition
);
// Sent to provider: Contains proof of vaccination, but no age or blood type.

For developers, key libraries and protocols to explore include: Hyperledger AnonCreds for ZKP-based selective disclosure, SpruceID's Kepler for policy-based storage, and Ceramic Network for composable data streams. The W3C Verifiable Credentials Data Model is the foundational standard. When designing the UI, prioritize clarity over complexity; break down medical jargon into plain-language choices. The goal is to make fine-grained control intuitive, turning a complex cryptographic capability into a simple slider or checkbox for the patient.

Ultimately, this step transforms the wallet from a passive data container into an active policy enforcement point. It ensures that the principle of data minimization—a core tenet of regulations like GDPR and HIPAA—is baked into the technical architecture. By giving patients a practical tool to share just enough information, you build trust and create a system where data utility and privacy are not in conflict, but are jointly optimized through user consent.

ARCHITECTURE

Comparison of Health Data Storage Options

Evaluating the core technical and operational trade-offs for storing sensitive patient health data.

Feature / MetricOn-Chain StorageOff-Chain Storage (IPFS/Filecoin)Hybrid Storage (Ceramic, Tableland)

Data Immutability & Audit Trail

Patient Data Privacy (GDPR/HIPAA)

Storage Cost for 1GB/year

$500-5000

$0.50-5

$5-50

Data Retrieval Speed

< 5 sec

1-30 sec

< 2 sec

Patient-Controlled Access Keys

Native Data Composability

Permanent Data Availability Guarantee

Primary Use Case

Audit logs, hashes, consent records

Medical images, large reports, raw data

Structured EHR data, portable profiles

DEVELOPER GUIDE

Frequently Asked Questions

Common technical questions and troubleshooting steps for implementing a secure, self-sovereign health data wallet using blockchain technology.

A patient-centric health data wallet is a self-sovereign identity (SSI) application that gives individuals control over their medical records. It uses decentralized identifiers (DIDs) and verifiable credentials (VCs) to create a portable, interoperable digital identity.

Core components include:

  • DID Document: Stored on a blockchain (e.g., Ethereum, Polygon) or a decentralized network (e.g., ION on Bitcoin), it contains public keys and service endpoints.
  • Verifiable Credentials: Digitally-signed attestations (like a lab result or vaccination record) issued by a trusted entity (hospital, clinic).
  • Holder/User Agent: The wallet app that stores private keys, manages DIDs, and presents VCs.

When a user needs to share data, they present a selective disclosure VC. The verifier checks the cryptographic signature against the issuer's public key in the DID document on-chain, proving authenticity without contacting the issuer directly.

conclusion-next-steps
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have successfully built a foundational patient-centric health data wallet. This guide covered the core components: a smart contract for data control, a frontend interface, and secure data storage via IPFS and Ceramic.

Your deployed HealthDataWallet.sol contract now acts as a decentralized access manager on-chain. Patients control a registry of authorized entities (doctors, researchers) who can request their data. This model shifts control from institutions to individuals using public-key cryptography and non-custodial wallets like MetaMask. The next step is to enhance this contract with more granular permissions, such as time-limited access or specific data-type allowances, using standards like the EIP-712 typed data signing for verifiable off-chain consent.

The frontend, built with Next.js and Wagmi, demonstrates a practical user flow. Key improvements include implementing a more robust state management system for wallet connections and transaction statuses. Consider integrating SIWE (Sign-In with Ethereum) for a standardized authentication layer that doesn't require gas fees for login. For production, you must rigorously audit the smart contract, especially the authorization logic in functions like grantAccess and revokeAccess, to prevent vulnerabilities like reentrancy or unauthorized withdrawals.

For data storage, we used IPFS for immutable records and Ceramic for mutable, composable data streams. The next phase is to integrate verifiable credentials (VCs) using the W3C standard. Instead of raw JSON files, patient data like immunization records could be issued as VCs by a trusted provider (e.g., a clinic), stored in the wallet, and presented to a verifier (e.g., an employer) with cryptographic proof. Explore frameworks like Veramo or Spruce ID's Kepler to manage these credentials within your application.

To move from a prototype to a viable system, address key challenges: data privacy for on-chain metadata, user experience for non-crypto-native users, and interoperability. Investigate zero-knowledge proofs (ZKPs) via zk-SNARKs libraries like SnarkJS to allow proof of data validity (e.g., "I am over 18") without revealing the underlying data. Furthermore, ensure compliance with regulations like HIPAA or GDPR by designing data minimization into the architecture and consulting legal experts on the classification of on-chain pointers.

Finally, explore the broader ecosystem. Your wallet can interact with DeHealth applications, clinical trial platforms, and personalized medicine services. Contribute to or adopt emerging standards for health data, such as those proposed by the Decentralized Identity Foundation (DIF). Continue your development by forking the example repository, adding new features, and engaging with the community on forums like Ethereum Research or Ceramic Discord to build the future of patient-owned health data.

How to Build a Self-Custody Health Data Wallet | ChainScore Guides