Important! Before you proceed, please read the EUDI Wallet Reference Implementation project description
The Wallet Core library acts as a coordinator by orchestrating the various components that are required to implement the EUDI Wallet functionality. On top of that, it provides a simplified API that can be used by the application to implement the EUDI Wallet functionality.
This repository is a monorepo that contains the EUDI Wallet Core library for Android along with its companion libraries: Document Manager and Transfer Manager. All three modules are part of the EUDI Wallet Reference Implementation project and are published under the same version.
Note: The eudi-lib-android-wallet-document-manager and
eudi-lib-android-iso18013-data-transfer libraries were previously maintained in separate
repositories. They have been consolidated into this monorepo for ease of maintenance. The
standalone repositories are no longer maintained — all development continues here.
%%{init: {
"theme": "base",
"themeVariables": {
"primaryColor": "#E6F1FB",
"primaryTextColor": "#0C447C",
"primaryBorderColor": "#378ADD",
"lineColor": "#888780",
"secondaryColor": "#EAF3DE",
"tertiaryColor": "#F1EFE8",
"edgeLabelBackground": "#ffffff",
"fontSize": "13px"
}
}}%%
graph TD
A("<b>eudi-lib-android-wallet-core</b>")
subgraph android ["Android"]
B["eudi-lib-android-wallet-\ndocument-manager"]
C["eudi-lib-android-iso18013-\ndata-transfer"]
end
subgraph jvm ["JVM / KMP"]
D["eudi-lib-jvm-openid4vci-kt"]
E["eudi-lib-jvm-openid4vp-kt"]
J["eudi-lib-jvm-sdjwt-kt"]
I["eudi-lib-kmp-etsi-1196x2"]
H["eudi-lib-kmp-statium"]
end
subgraph multipaz ["Multipaz"]
F["org.multipaz"]
G["multipaz-android"]
end
B -->|DocumentManager| A
C -->|TransferManager| A
D -->|OpenId4VciManager| A
E -->|OpenId4VpManager| A
J -->|SdJwtVcVerification| A
I -->|IssuerTrustVerification| A
F -->|"SecureArea, Storage"| B
F -->|"SecureArea, Storage"| A
G --> A
B -->|DocumentManager| C
J --> B
H --> A
classDef core fill:#185FA5,stroke:#0C447C,color:#fff,font-weight:bold
classDef androidLib fill:#E6F1FB,stroke:#378ADD,color:#0C447C
classDef jvmLib fill:#EAF3DE,stroke:#639922,color:#27500A
classDef multipazLib fill:#FAEEDA,stroke:#BA7517,color:#633806
class A core
class B,C androidLib
class D,E,J,I,H jvmLib
class F,G multipazLib
The library supports the following features:
| Category | Feature | Status | Default |
|---|---|---|---|
| Document Management | Documents' Key creation and management with Android Keystore by default | ✅ | User authentication Required, StrongBox IfSupported (Document Key Protection) |
| Custom Key Management implementation | ✅ via implementation of SecureArea | ||
| Multiple Key Management implementations | ✅ | ||
| Support for Batch credentials per Document | ✅ | ||
| Document Issuance | OpenId4VCI v1.0 document issuance | ||
| Authorization Code Flow | ✅ | ||
| Pre-authorization Code Flow | ✅ | ||
| DPoP JWT in authorization | ✅ | Enabled, when the authorization server supports it | |
| Credential Formats | ✅ mso_mdoc format ✅ sd-jwt-vc format |
||
| Credential issuance | ✅ Wallet initiated issuance ✅ Via credential Offer |
||
| Credential batch issuing | ✅ | ||
| Credential reuse policies (ETSI TS 119 472-3) | ✅ once_only, limited_time, rotating_batch |
||
| Deferred issuing | ✅ | ||
| Wallet Authentication | ✅ public client, ✅ Attestation-Based Client Authentication (WIA) |
||
| Supported Proof Types | ✅ Attestation Proof Type ✅ JWT Proof Type with Key Attestation ✅ JWT Proof Type without Key Attestation ✅ No Proof |
||
| Notify credential issuer | ❌ | ||
| Issuer Trust | Trust verification during issuance (LoTE) | ✅ mso_mdoc format ✅ sd-jwt-vc format |
Enabled |
| Trust policy (ENFORCE / INFORM) | ✅ | ENFORCE | |
| Signed issuer metadata verification | ✅ RequireSigned / PreferSigned / IgnoreSigned | RequireSigned | |
| Custom credential format verifiers | ✅ via CredentialTrustVerifier | ||
| Registration Certificate | Relying party registration certificate (WRPRC, ETSI TS 119 472-2) | ✅ ISO/IEC 18013-5 ✅ OpenID4VP ✅ DC API |
Enabled; requires trust for registration certificates (REGISTRATION_CERTIFICATE.md) |
| Credential issuer registration certificate (ETSI TS 119 472-3) | ✅ OpenID4VCI | Enabled, with signed issuer metadata; requires trust for registration certificates | |
| Revocation Status | Document status resolution (token status lists) | ✅ JWT ✅ CWT |
On request (resolveStatus) |
| Status list token signer trust verification (LoTE) | ✅ | Disabled; enabled with configureDocumentStatusResolver { } and configureEtsiTrust or a trust source |
|
| Proximity Presentation | ISO-18013-5 device retrieval | ||
| Device engagement | ✅ QR ✅ NFC |
||
| Data transfer | ✅ BLE ❌ NFC ❌ Wifi-Aware |
||
| Remote Presentation | OpenID for Verifiable Presentations 1.0 | ||
| ClientID scheme | ✅ preregistered ✅ x509_san_dns ✅ x509_hash ✅ redirect_uri |
||
| DCQL | ✅ support for credential_sets ✅ support for claim_sets ✅ per-query multiple flag ✅ per-query require_cryptographic_holder_binding flag |
||
| Transaction data | ✅ SD-JWT VC ✅ ISO/IEC 18013-5 mdoc |
||
| Digital Credential API | ✅ ISO mdoc (org-iso-mdoc) ✅ OpenID4VP ( openid4vp-v1-signed, openid4vp-v1-unsigned) |
Disabled (DIGITAL_CREDENTIAL_API.md) | |
| Trust Mark | EUDI Wallet Trust Mark (EC TS01 v1.2) | ✅ Static (pre-distribution) ✅ Dynamic (on-demand via provider) |
|
| Trust Mark resource fetching | ✅ |
The library is written in Kotlin and is compatible with Java. It is distributed as a Maven package and can be included in any Android project that uses Android 8 (API level 26) or higher.
This monorepo contains three Gradle modules, all published under the same version:
| Module | Maven Artifact |
|---|---|
:wallet-core |
eu.europa.ec.eudi:eudi-lib-android-wallet-core |
:document-manager |
eu.europa.ec.eudi:eudi-lib-android-wallet-document-manager |
:transfer-manager |
eu.europa.ec.eudi:eudi-lib-android-iso18013-data-transfer |
The released software is an initial development release version:
- The initial development release is an early endeavor reflecting the efforts of a short timeboxed period, and by no means can be considered as the final product.
- The initial development release may be changed substantially over time, might introduce new features but also may change or remove existing ones, potentially breaking compatibility with your existing code.
- The initial development release is limited in functional scope.
- The initial development release may contain errors or design flaws and other problems that could cause system or other failures and data loss.
- The initial development release has reduced security, privacy, availability, and reliability standards relative to future releases. This could make the software slower, less reliable, or more vulnerable to attacks than mature software.
- The initial development release is not yet comprehensively documented.
- Users of the software must perform sufficient engineering and additional testing in order to properly evaluate their application and determine whether any of the open-sourced components is suitable for use in that application.
- We strongly recommend not putting this version of the software into production use.
- Only the latest version of the software will be supported
- Android 8 (API level 26) or higher
To use snapshot versions add the following to your project's settings.gradle file:
dependencyResolutionManagement {
repositories {
// ...
maven {
url = uri("https://central.sonatype.com/repository/maven-snapshots/")
mavenContent { snapshotsOnly() }
}
// ...
}
}To include the library in your project, add the following dependencies to your app's build.gradle file.
dependencies {
implementation "eu.europa.ec.eudi:eudi-lib-android-wallet-core:0.32.0"
// required when using the built-in AndroidKeystoreSecureArea implementation provided by the library
// for user authentication with biometrics
implementation "androidx.biometric:biometric-ktx:1.2.0-alpha05"
}To use the Digital Credential API, also add the runtime dependency described in DIGITAL_CREDENTIAL_API.md.
To use configureEtsiTrust, also add etsi-119602-consultation (see Trusted Lists › Dependencies).
Use this checklist before releasing a wallet that uses the library.
| Area | Required outcome |
|---|---|
| Trusted lists | configureEtsiTrust uses the production lists of trusted entities (LoTE) for each check: the PID and attestation provider lists for issuer trust, wrpacProviders for reader authentication and signed issuer metadata, wrprcProviders for registration certificates. The list signers are trusted with loteSignerTrustAnchors() or jwtSignatureVerifier(); relaxCertificateProfiles() and pkixRevocationPolicy(PkixRevocationPolicy.Disabled) (or the deprecated relaxPkixRevocation()) are not used. See Centralized Trust Configuration. |
| Issuer trust | Every credential type that the wallet accepts is classified (with ENFORCE, types that are not classified are rejected), and issuance managers are created with wallet.createOpenId4VciManager(). The signed issuer metadata policy is RequireSigned (the default); with preferSignedMetadata() or ignoreSignedMetadata(), the issuer's registration certificate is not validated. See Issuer Trust Verification, Creating an OpenId4VciManager and Signed Issuer Metadata Verification. |
| DPoP | DPopConfig.Disabled is not used, and the authorization servers that the wallet uses support DPoP. DPoP is used only when the authorization server advertises it; otherwise the access token is issued without DPoP. See DPoP Support. |
| Revocation status | resolveStatus is called wherever the status of a document is needed; the wallet does not check revocation on its own. The signature of a status list token is always verified; whether its signer is trusted is checked only when configureDocumentStatusResolver { } (the block form) is used, with configureEtsiTrust or with a trust source in configureTrust. See Resolving document status and Revocation Status Trust Verification. |
| Registration certificates | Trust for registration certificates comes from configureEtsiTrust, or from configureWrpRegistrationTrust and configureIssuerRegistrationTrust; without it, building the wallet fails while the registration policies are Enabled (the default). The result (wrpRegistration, issuerRegistration) is shown to the user, who is asked for approval when requiresExplicitApproval is true. The result does not block the interaction, with one exception: when the issuer's registration certificate is validated, issuance stops if the signed issuer metadata carries no registration certificate or more than one. See REGISTRATION_CERTIFICATE.md. |
| Document keys | Building the wallet fails with KeyProtectionUnsupportedException on a device without a screen lock while user authentication is Required (the default), and the app handles it. A policy other than Required is chosen deliberately; the protections that apply are in wallet.keyProtectionState. See Document Key Protection. |
| Dependencies | etsi-119602-consultation is declared in the app when configureEtsiTrust is used (wallet-core does not add it), and registry-provider-play-services when the Digital Credential API is enabled. See Dependencies. |
For a production deployment based on the reference wallet app, see also the EUDI Android Wallet Go-Live Guide.
To instantiate a EudiWallet use the EudiWallet.Builder class or the EudiWallet.invoke method,
from the EudiWallet companion object.
The minimum requirements to initialize the library is to provide a EudiWalletConfig object that
will be used to configure the library's built-in components.
The built-in components are:
AndroidKeystoreSecureAreafor storing and managing the documents' keysAndroidStoragefor storing the documents' dataReaderTrustStoreimplementation for validating the reader's certificatesPresentationManagerimplementation for managing both proximity and remote presentation of documentsLoggerimplementation for loggingDocumentStatusResolverimplementation for checking document revocation status
The following example demonstrates how to initialize the library for using the built-in components:
// configuring the wallet
val storageFile = File(applicationContext.noBackupFilesDir.path, "main.db")
val config = EudiWalletConfig()
// configure the document storage
// the noBackupFilesDir is used to store the documents by default
.configureDocumentManager(storageFile.absolutePath)
// configure the built-in logger
.configureLogging(
// set log level to info
level = Logger.LEVEL_INFO
)
// configure the built-in key creation settings
.configureDocumentKeyCreation(
// require user authentication; building the wallet fails if the device
// is not secured with a PIN, pattern or password
userAuthentication = KeyProtectionPolicy.Required,
// use the device's StrongBox if available to store the keys
strongBox = KeyProtectionPolicy.IfSupported,
// set userAuthenticationTimeout to 30 seconds
userAuthenticationTimeout = 30_000.milliseconds
)
.configureReaderAuthentication {
// set the reader trusted certificates
trustedCertificates(readerCertificate)
// configure the reader authentication enforcement policy
// default is EnforceIfPresent
enforceIfPresent()
}
// configure the issuer trust verification, which is on by default
// the trust source can also come from configureEtsiTrust
.configureIssuerTrust {
trustSource(issuerChainTrust)
classifications(issuerClassifications)
}
// set the trust anchors (CA certificates) of the providers of registration certificates for
// relying parties and credential issuers (see REGISTRATION_CERTIFICATE.md)
.configureWrpRegistrationTrust(listOf(registrationCertificateProviderCa))
.configureIssuerRegistrationTrust(listOf(registrationCertificateProviderCa))
// configure the OpenId4Vci service
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
withParUsage(OpenId4VciManager.Config.ParUsage.Companion.IF_SUPPORTED)
// Configure DPoP (Demonstrating Proof-of-Possession)
// By default, DPoP is enabled with DPopConfig.Default
// You can also provide a custom configuration or disable it
// withDPopConfig(DPopConfig.Default) // This is the default
// withDPopConfig(DPopConfig.Disabled) // To disable DPoP
// withDPopConfig(customDPopConfig) // To use custom configuration
// Configure credential response encryption
// By default, encryption is REQUIRED with EC P-256 and RSA 2048
// withResponseEncryptionConfig(EncryptionSupportConfig(...))
}
// configuration for proximity presentation
// the values below are the default values
.configureProximityPresentation(
// ble mode: peripheral and/or central
enableBlePeripheralMode = true,
enableBleCentralMode = false,
clearBleCache = true,
// registered application service for handling NFC device engagement
nfcEngagementServiceClass = MyNfcEngagementService::class.java
)
// configure the OpenId4Vp service
.configureOpenId4Vp {
withClientIdSchemes(
ClientIdScheme.X509SanDns
)
withSchemes(
"openid4vp",
"eudi-openid4vp",
"mdoc-openid4vp"
)
withFormats(
Format.MsoMdoc.ES256,
Format.SdJwtVc.ES256
)
// Encryption policy — defaults to EncryptionPolicy.HAIP, which accepts only
// encrypted response modes (`direct_post.jwt` for OpenID4VP, `dc_api.jwt` for DC-API).
// Override via withEncryptionPolicy(...) if a different profile is needed.
withEncryptionPolicy(EncryptionPolicy.HAIP)
}
// configure document status resolver with 5 minutes clock skew tolerance
.configureDocumentStatusResolver {
clockSkew(5)
}
// Create the wallet instance with default components
val wallet = EudiWallet(context, config)
// Or create the wallet with custom component implementations
val customWallet = EudiWallet(context, config) {
// custom Storage to store documents' data
withStorage(myStorage)
// a list of SecureArea implementations to be used
withSecureAreas(listOf(deviceSecureArea, cloudSecureArea))
// custom logger to be used
withLogger(myLogger)
// custom HTTP client for network operations
withKtorHttpClientFactory { HttpClient(OkHttp) { /* custom config */ } }
// custom transaction logger for auditing
withTransactionLogger(myTransactionLogger)
// custom document status resolver
withDocumentStatusResolver(myDocumentStatusResolver)
// custom wallet key manager
withWalletKeyManager(myWalletKeyManager)
}See the CustomizeSecureArea.md for more information on how to use the wallet-core library with custom SecureArea implementations.
configureDocumentKeyCreation sets a KeyProtectionPolicy for user authentication and for StrongBox.
The policies apply to the keys that getDefaultCreateKeySettings and getDefaultCreateDocumentSettings
create in AndroidKeystoreSecureArea. Keys in other secure areas (see
CustomizeSecureArea.md), or created with a configure block, use the
settings given by the app.
The device support is checked once, when the wallet is built, for the whole wallet:
| Policy | The device supports the protection | The device does not support it |
|---|---|---|
Required |
Applied | Building the wallet fails |
IfSupported |
Applied | The keys are created without it |
Disabled |
Not applied | Not applied |
When building fails, the exception is a KeyProtectionUnsupportedException, whose protection is the
protection that the device does not support (UserAuthentication or StrongBox):
val wallet = try {
EudiWallet(context, config)
} catch (e: KeyProtectionUnsupportedException) {
when (e.protection) {
KeyProtectionUnsupportedException.Protection.UserAuthentication -> {
// ask the user to set up a screen lock
}
KeyProtectionUnsupportedException.Protection.StrongBox -> {
// the device cannot be used with this configuration
}
}
return
}The defaults are Required for user authentication and IfSupported for StrongBox. The protections
that apply are in wallet.keyProtectionState:
val state = wallet.keyProtectionState
if (!state.useStrongBox) {
// the keys are created outside StrongBox on this device
}The reader authentication policy controls how reader authentication results affect document
disclosure during proximity (BLE/NFC), remote (OpenID4VP), and DCAPI presentations. Trust sources
and enforcement intent are configured together via configureReaderAuthentication:
val config = EudiWalletConfig {
configureReaderAuthentication {
trustedCertificates(cert1, cert2)
enforceIfPresent() // default — can be omitted
}
}When a verifier's request includes reader authentication, the wallet verifies the reader's certificate chain against the configured trust sources. The enforcement policy determines what happens based on the verification result:
| Policy | Behavior |
|---|---|
doNotEnforce() |
Reader authentication is evaluated but never blocks document disclosure. Documents are always included in the response. |
enforceIfPresent() |
(Default) Documents are excluded from the response when reader authentication is present but fails verification. Documents without reader authentication are included normally. |
alwaysRequire() |
Documents are excluded unless reader authentication is present and verified successfully. |
Per ISO 18013-5, when all documents are excluded due to reader authentication failure, the wallet returns a DeviceResponse with status 10 (General Error) instead of an empty success response.
With ETSI trust (trust source inherited from configureEtsiTrust):
val config = EudiWalletConfig {
configureEtsiTrust { /* ... */ }
configureReaderAuthentication {
alwaysRequire()
// trust source resolved from configureEtsiTrust at build time
}
}With static certificates:
val config = EudiWalletConfig {
configureReaderAuthentication {
trustedCertificates(trustedCert1, trustedCert2)
revocationPolicy(RevocationPolicy.SoftFail)
enforceIfPresent()
}
}Note:
enforceIfPresent()andalwaysRequire()require trust sources. If no trust source is configured (and no central ETSI trust source is available), anIllegalArgumentExceptionis thrown at build time. CalldoNotEnforce()to explicitly opt out.
Note: If a verifier includes reader authentication in its request but its certificate is not in the configured trust store, the document will be excluded from the response when using
enforceIfPresent()oralwaysRequire(). To allow presentations to verifiers whose certificates are not in the trust store, usedoNotEnforce().
Note: The reader authentication trust is not used for relying-party registration certificates. Without
configureEtsiTrust, callconfigureWrpRegistrationTrust(...)orconfigureWrpRegistrationPolicy(WrpRegistrationPolicy.Disabled); otherwise building the wallet fails. See REGISTRATION_CERTIFICATE.md.
This interface is responsible for managing Attestation Keys used during Attestation Based Client Authentication with OpenId4Vci.
The library provides SecureAreaWalletKeyManager, an extensible SecureArea based implementation of this interface.
If no configuration is provided for a custom WalletKeyManager the default implementation of the library will be used based on AndroidKeystoreSecureArea.
You can provide your custom WalletKeyManager by configuring the EudiWallet instance:
val customWallet = EudiWallet(context, config) {
// rest of configurations
// ......................
// custom wallet key manager
withWalletKeyManager(myWalletKeyManager)
}Configure EudiWallet for Attestation Based Client Authentication(WIA) and Wallet Unit Attestation(WUA) with a Wallet Provider
The wallet-core supports Wallet Instance Attestation (WIA) that attests the integrity of the app & Wallet Unit Attestation (WUA) that attests the security of keys stored in the Wallet Unit.
You can optionally configure your wallet with this capability by implementing the core's WalletAttestationsProvider interface which bridges your wallet-specific Wallet Provider to the core.
Example usage is documented below:
val walletAttestationsProvider = object : WalletAttestationsProvider {
/**
* WIA (Wallet Instance Attestation)
* Used for Client Authentication (OAuth 2.0).
*/
override suspend fun getWalletAttestation(keyInfo: KeyInfo) : Result<String> {
// Make a network call to your Wallet Provider Service.
// Send the public key from 'keyInfo' (PoP key).
// Prove app integrity
// Return the "Client Attestation JWT" signed by your Provider.
return Result.success("ey...<The_WIA_JWT>")
}
/**
* WUA (Wallet Unit Attestation)
* Used to authorize Credential Issuance.
*/
override suspend fun getKeyAttestation(keys: List<KeyInfo>, nonce: Nonce?) : Result<String> {
// Make a network call to your Wallet Provider Service.
// Send the public keys (from 'keys') intended for the new Credential.
// Provide the 'nonce' if required by the Issuer.
// Return the "Wallet Unit Attestation" (or Key Attestation) JWT.
// This certifies that these specific keys are hardware-bound and trusted.
return Result.success("ey...<The_WUA_JWT>")
}
}So the configuration of the EudiWallet documented in the above section would now be:
val wallet = EudiWallet(
context,
config,
walletAttestationsProvider
)NOTE: When Attestation Based Client Authentication is configured for OpendId4Vci, the EudiWallet must also be instantiated with a WalletProvider
The library supports the EUDI Wallet Trust Mark as defined in EC TS01 v1.2 (2026-06). The Trust Mark is a visible, verifiable indicator displayed in certified Wallet Solutions to inform users that the wallet has been certified under EU Regulation 2024/1183.
The TrustMarkManager provides access to:
TrustMarkInformation: URLs for the Trust Mark resource, list of certified wallets, and the wallet solution's own information page.TrustMarkResource: The official Trust Mark logo and localised user information text, fetched from the EC-hosted resource endpoint.
Trust Mark delivery is configured via a single TrustMarkSource parameter matching the
specification's two delivery mechanisms:
For trust mark data compiled into the app at build time:
val wallet = EudiWallet(
context = context,
config = config,
trustMarkSource = TrustMarkSource.Static(
TrustMarkInformation(
trustMarkResourceURL = "https://eidas.ec.europa.eu/efda/wallet/trust-mark/resources",
listOfCertifiedWalletsURL = "https://eidas.ec.europa.eu/efda/wallet/certified",
walletSolutionInfoPageURL = "https://eidas.ec.europa.eu/efda/wallet/certified?id=WALLET_123",
)
),
)For trust mark data fetched from a Wallet Provider backend at runtime:
val wallet = EudiWallet(
context = context,
config = config,
trustMarkSource = TrustMarkSource.Dynamic(
TrustMarkProvider {
// Fetch trust mark configuration from your Wallet Provider backend
myBackendService.getTrustMarkInformation()
}
),
)When trust mark data is supplied (via either method above), a TrustMarkManager is created
internally and exposed via wallet.trustMarkManager. It is null when neither a provider
nor static information was supplied.
A single getTrustMark() call resolves the trust mark information and fetches the resource
(logo + text) from the EC endpoint in one operation:
wallet.trustMarkManager?.getTrustMark()?.fold(
onSuccess = { trustMark ->
// Trust Mark information (URLs, optional QR codes)
val info = trustMark.information
// info.trustMarkResourceURL
// info.listOfCertifiedWalletsURL
// info.walletSolutionInfoPageURL
// info.listOfCertifiedWalletsQRCode (optional, base64)
// info.walletSolutionInfoPageQRCode (optional, base64)
// info.walletVerifierToolURL (optional)
// Trust Mark resource (logo + localised text)
val resource = trustMark.resource
// resource.image.name — e.g. "eudi-wallet-trustmark-logo.png"
// resource.image.url — URL to the logo image
// resource.text.localisations — Map<String, String> of language code to text
val localizedText = resource.text.localisations["en"]
},
onFailure = { error ->
// Handle error (provider failure, network failure, parse error, etc.)
}
)Note:
getTrustMark()performs an HTTP GET to thetrustMarkResourceURL. The image URL in the response is returned as-is for the UI layer to render.
The library provides a set of methods to work with documents.
The following snippet shows how to retrieve all documents:
// Get all documents in the wallet
val documents = wallet.getDocuments()You can also retrieve documents based on a predicate. The following snippet shows how to retrieve documents of mso_mdoc format of a specific docType:
// Get documents filtered by a specific docType
val documents = wallet.getDocuments { document ->
(document.format as? MsoMdocFormat)?.docType == "eu.europa.ec.eudi.pid.1"
}
// Get only issued documents (excluding deferred documents)
val issuedDocuments = wallet.getDocuments { document ->
document is IssuedDocument
}
// Combine multiple conditions
val specificDocuments = wallet.getDocuments { document ->
document is IssuedDocument &&
(document.format as? SdJwtVcFormat)?.vct == "IdentityCredential"
}The following snippet shows how to retrieve a document by its id:
val documentId = "some_document_id"
val document: Document? = wallet.getDocumentById(documentId)
// You can also cast to a specific document type if needed
val issuedDocument = wallet.getDocumentById(documentId) as? IssuedDocument
val deferredDocument = wallet.getDocumentById(documentId) as? DeferredDocumentIssued documents provide methods to work with individual credentials:
val issuedDocument = documentManager.getDocumentById("document_id") as? IssuedDocument
requireNotNull(issuedDocument)
// Get the number of valid credentials for the document
val numberOfValidCredentials = issuedDocument.credentialsCount()
// Get the initial number of credentials for the document
val initialNumberOfCredentials = issuedDocument.initialCredentialsCount()
// Get a list of all valid credentials for the document
val validCredentials = issuedDocument.getCredentials()
// Find an available credential (automatically selects the best one based on policy)
val credential = issuedDocument?.findCredential()
// Use a credential and apply the policy (e.g., delete if OnceOnly, increment usage if RotatingBatch)
issuedDocument?.consumingCredential {
// Use the credential for presentation or other operations
// The credential policy will be applied automatically after this block
performPresentationWithCredential(this)
}The findCredential() method intelligently selects credentials based on:
- Credential policy (e.g., ETSI reuse policies such as
OnceOnly,LimitedTime,RotatingBatch) - Usage count (selecting least-used credentials first in rotation-based policies)
- Validity period (ensuring the credential is currently valid)
- Availability (excluding deleted or invalidated credentials)
findCredential() does not check the revocation status of a credential. To check it, call
resolveStatus (see Resolving document status).
To delete a document, use the following code snippet:
try {
val documentId = "some_document_id"
val deleteResult = wallet.deleteDocumentById(documentId)
deleteResult.getOrThrow()
} catch (e: Throwable) {
// Handle the exception
}The wallet-core library provides functionality to check the revocation status of documents. This is useful to verify if a document is still valid or has been revoked.
To check the status of a document, you can use the resolveStatusById method on the EudiWallet
instance:
// Get a document's ID
val documentId = "some_document_id"
// Check the document's status
wallet.resolveStatusById(documentId).fold(
onSuccess = { status ->
when (status) {
Status.Valid -> println("Document is valid")
Status.Invalid -> println("Document is invalid")
Status.Suspended -> println("Document is suspended")
is Status.ApplicationSpecific -> println("Application-specific status: ${status.value}")
is Status.Reserved -> println("Reserved status: ${status.value}")
}
},
onFailure = { error ->
// Handle errors (network issues, document not found, etc.)
}
)You can also check the status of a document directly if you have an IssuedDocument instance:
val document = wallet.getDocumentById(documentId) as? IssuedDocument
if (document != null) {
wallet.resolveStatus(document).fold(
onSuccess = { status ->
// Handle the status
},
onFailure = { error ->
// Handle errors
}
)
}For more details on document management, see the Document Manager repository.
By default, the library uses a built-in implementation of DocumentStatusResolver that works with
token status lists as specified in various credential formats. The resolver supports both MSO MDOC
and SD-JWT VC document formats.
You can configure the default implementation using EudiWalletConfig:
val config = EudiWalletConfig()
// Configure a clock skew allowance (in minutes) for token verification
.configureDocumentStatusResolver {
clockSkew(5)
}
// ... other configurationsThe default clock skew is zero (Duration.ZERO). The signature of a status list token is always
verified (x5c). Whether its signer is trusted is checked only with the block form, with
configureEtsiTrust or a trust source in configureTrust (see
Revocation Status Trust Verification); the
configureDocumentStatusResolver(clockSkewInMinutes) overload sets only the clock skew.
For more advanced customization, you can provide your own custom implementation of
DocumentStatusResolver during wallet initialization:
val wallet = EudiWallet(context, config) {
// Custom HTTP client factory for status resolution if needed
withKtorHttpClientFactory { HttpClient(OkHttp) { /* custom configuration */ } }
// Or a completely custom document status resolver
withDocumentStatusResolver(myCustomDocumentStatusResolver)
}You can also create your own DocumentStatusResolver using the builder:
// Create a custom DocumentStatusResolver
val customResolver = DocumentStatusResolver {
// Configure verification mechanism
withVerifyJwtSignature(VerifyStatusListTokenJwtSignature.x5c)
// Configure clock skew tolerance
withAllowedClockSkew(5.minutes)
// Custom HTTP client factory
withKtorHttpClientFactory {
HttpClient(CIO) {
// Custom client configuration
}
}
// Custom status reference extractor if needed
withExtractor(MyCustomStatusReferenceExtractor)
}
// Use the custom resolver during wallet initialization
val wallet = EudiWallet(context, config) {
withDocumentStatusResolver(customResolver)
}The library supports trust verification using ETSI Trusted Lists for credential issuance (issuer trust), credential presentation (reader/verifier authentication), revocation status (status list token signer trust), and signed issuer metadata verification. This enables dynamic trust anchor resolution from LoTE (ETSI TS 119 602) instead of static certificate lists.
The recommended approach is to use configureEtsiTrust to centralize the LoTE trust
infrastructure in the core. This builds the entire trust pipeline internally — HTTP client,
file cache, JWT signature verification, trust anchor provisioning, and caching — from a
small set of high-level configuration knobs. Each trust area (configureIssuerTrust,
configureDocumentStatusResolver, configureReaderAuthentication) inherits the shared trust
source automatically and only needs area-specific settings (policies, clock skew, etc.).
Each trust verification feature is independently configurable. Issuer trust, including signed issuer metadata, is verified by default (see Issuer Trust Verification). The other features are opt-in; when not configured, the library behaves as before (status resolved with standard signature verification, reader authentication via static certificate lists or disabled).
For advanced use cases, the design remains protocol-agnostic — the per-area builders still
accept explicit trustSource() calls, allowing developers to compose trust validation using the
eudi-lib-kmp-etsi1196x2
library directly (or any other trust framework).
The etsi-1196x2-consultation module is exposed as an api dependency from wallet-core,
so consumers can reference its types directly (SupportedLists, AttestationClassifications,
IsChainTrustedForEUDIW, etc.).
The etsi-119602-consultation module (which provides the Uri type used in configureEtsiTrust
DSL) is not transitively available due to an upstream packaging issue. Consumers must
declare it explicitly, with the version that wallet-core uses (the eudi-lib-kmp-etsi1196x2
version in gradle/libs.versions.toml):
dependencies {
implementation "eu.europa.ec.eudi:eudi-lib-android-wallet-core:0.32.0"
// Required explicitly — Uri type is not transitive from wallet-core
implementation "eu.europa.ec.eudi:etsi-119602-consultation:0.5.0-alpha.1"
}The configureEtsiTrust DSL centralizes the entire LoTE pipeline setup into a few high-level
knobs. The core builds the HTTP client, file cache, JWT signature verifier, trust anchor
provisioner, and in-memory cache internally. Each trust area inherits the shared trust source
and classifications automatically.
val config = EudiWalletConfig {
configureEtsiTrust {
// Required: LoTE download URLs
loteLocations(SupportedLists(
pidProviders = Uri("https://trust.example.eu/pid-providers.jwt"),
wrpacProviders = Uri("https://trust.example.eu/wrpac-providers.jwt"),
pubEaaProviders = Uri("https://trust.example.eu/pub-eaa-providers.jwt")
))
// Required: map credential types to ETSI verification contexts
classifications(AttestationClassifications(
pids = AttestationIdentifierPredicate.any(setOf(
AttestationIdentifier.MDoc("eu.europa.ec.eudi.pid.1"),
AttestationIdentifier.SDJwtVc("urn:eudi:pid:1"),
)),
pubEAAs = AttestationIdentifierPredicate.equalsTo(
AttestationIdentifier.MDoc("org.iso.18013.5.1.mDL")
),
))
// Required unless jwtSignatureVerifier() is set: the signing certificates of the LoTEs,
// or the CA certificates that issue them
loteSignerTrustAnchors(loteSignerCertificate)
// Optional: all have sensible defaults
fileCacheExpiration(24.hours) // how long LoTE files are cached on disk
cacheTtl(20.minutes) // how long trust anchors are cached in memory
relaxCertificateProfiles() // strip endEntityProfile constraints (DEV/testing)
// pkixRevocationPolicy(PkixRevocationPolicy.CRLPriority) // default if omitted
// jwtSignatureVerifier(custom) // override built-in JWT verifier
// loteConstraints(...) // control LoTE pointer following
}
// Each area inherits trust source + classifications from configureEtsiTrust.
// Only area-specific settings are needed:
configureIssuerTrust {
policy { default(TrustPolicy.Action.ENFORCE) }
}
configureDocumentStatusResolver {
clockSkew(5)
}
configureReaderAuthentication {
alwaysRequire()
}
}LoTE JWT Verification: The built-in
LoteJwtVerifieraccepts a LoTE only when its signing certificate, the first certificate of thex5cheader, is valid now and is one of the certificates passed toloteSignerTrustAnchors()or chains to one of them (PKIX), and the JWS signature verifies with its public key. Revocation checking of a signer chain to a CA certificate followsrelaxPkixRevocation().configureEtsiTrustfails when neitherloteSignerTrustAnchors()norjwtSignatureVerifier()is set.DEV/Testing knobs:
relaxCertificateProfiles()stripsendEntityProfileconstraints from all provider types, useful when DEV certificates don't fully conform to ETSI profile requirements.PKIX Revocation Policy: Controls how CRL and OCSP revocation data is validated during certificate chain verification. When
pkixRevocationPolicy()is not explicitly called, the default isPkixRevocationPolicy.CRLPriority. Available policies:
PkixRevocationPolicy.CRLPriority(default) — CRL primary, OCSP fallback. Attempts CRL first; if CRL fetch succeeds, uses CRL. If CRL fetch fails, falls back to OCSP. If both fail, validation fails.
PkixRevocationPolicy.CRLOnly— CRL only, no OCSP fallback. Only uses Certificate Revocation Lists (CRL) for revocation checking. If CRL fetch fails, validation fails (no OCSP fallback).
PkixRevocationPolicy.OCSPPriority— OCSP primary, CRL fallback. Java's default behavior. Attempts OCSP first; if OCSP succeeds, uses OCSP. If OCSP fails, falls back to CRL. If both fail, validation fails.
PkixRevocationPolicy.SoftFail— CRL only, no OCSP fallback, tolerating network errors. The revocation check succeeds if the CRL cannot be obtained because of a network error. A revoked certificate is still rejected.
PkixRevocationPolicy.Disabled— No revocation checking. Equivalent to deprecatedrelaxPkixRevocation().IMPORTANT: Only HTTPS CRL/OCSP endpoints are supported. HTTP endpoints are not supported.
For advanced use cases where you need full control over the LoTE pipeline, you can build
the trust source manually using the ETSI library directly and pass it to the per-area
builders via trustSource():
// 1. Set up LoTE loading with file cache
val httpClient = HttpClient()
val loadLoTE = LoadSingleLoTEWithFileCache(
cacheDirectory = Path(context.cacheDir.path, "lote-cache"),
downloadSingleLoTE = DownloadSingleLoTE(httpClient),
fileCacheExpiration = 24.hours,
)
// 2. Configure LoTE pointer loading and JWT verification
val loadLoTEAndPointers = LoadLoTEAndPointers(
constraints = LoadLoTEAndPointers.Constraints.DoNotLoadOtherPointers,
verifyJwtSignature = myJwtVerifier, // Your VerifyJwtSignature implementation, which authenticates the LoTE signer
loadLoTE = loadLoTE,
)
// 3. Build trust anchor provisioner with EU defaults
val provisionTrustAnchors = ProvisionTrustAnchorsFromLoTEs.eudiwJvm(loadLoTEAndPointers)
// 4. Create cached trust validator
val disposableScope = DisposableContainer()
val isChainTrusted = provisionTrustAnchors.cached(disposableScope, loteLocations, ttl = 10.minutes)
// 5. Pass to each area explicitly
val config = EudiWalletConfig {
configureIssuerTrust {
trustSource(isChainTrusted)
classifications(myClassifications)
policy { default(TrustPolicy.Action.ENFORCE) }
}
configureDocumentStatusResolver {
clockSkew(5)
configureTrust {
trustSource(isChainTrusted)
classifications(myClassifications)
}
}
configureReaderAuthentication {
trustSource(isChainTrusted)
enforceIfPresent()
}
// registration certificates take their trust from configureEtsiTrust or from these methods,
// not from trustSource(); see REGISTRATION_CERTIFICATE.md
configureWrpRegistrationTrust(registrarCas)
configureIssuerRegistrationTrust(registrarCas)
}
// On shutdown:
// disposableScope.dispose()Lifecycle: When building the pipeline manually,
DisposableContainermanages cached resources. Create it at Application scope and calldispose()during shutdown. When usingconfigureEtsiTrust, the core manages the lifecycle internally.HTTP Client:
HttpClient()with no explicit engine auto-discoversktor-client-androidat runtime (already included as aruntimeOnlydependency by wallet-core).
For deployments that ship trust anchors with the app (offline, air-gapped, or pinned trust), a trust source can be built from local certificate files or a Java KeyStore with no HTTP client and no LoTE URL involved. The per-area builders accept the same ETSI types regardless of where the anchors come from.
Read STATIC_CERTIFICATE_TRUST_CONFIGURATION.md for a step-by-step guide covering all trust areas
Trust verification runs after the credential is received from the issuer and before it is stored.
This verification covers the issuer's signature and certificate chain, not the revocation status
of the credential. The revocation status is checked separately with resolveStatus (see
Resolving document status).
Built-in verifiers handle both MsoMdoc and SD-JWT VC formats, and custom verifiers can be
registered for additional formats.
Issuer trust is verified by default. Without configureIssuerTrust, the wallet uses the trust
source and classifications of configureEtsiTrust with the ENFORCE policy and requires signed
issuer metadata; building the wallet fails when no trust source is available. To turn
verification off, call doNotVerify():
configureIssuerTrust {
doNotVerify()
}A credential is then checked only for its integrity (issuer signature, binding to the device key
and, for mdoc, the digests and docType); the issuer's certificate chain is not verified, only
unsigned issuer metadata is used, and issuerTrustResult is null.
Configure issuer trust verification via the configureIssuerTrust DSL on EudiWalletConfig.
When configureEtsiTrust is also used, trustSource() and classifications() are inherited
automatically — only policy and metadata settings are needed:
val walletConfig = EudiWalletConfig {
configureEtsiTrust { /* ... */ }
configureIssuerTrust {
// trustSource() and classifications() inherited from configureEtsiTrust
policy {
default(TrustPolicy.Action.ENFORCE)
forContext(VerificationContext.EAA("experimental"), TrustPolicy.Action.INFORM)
forDocType("org.example.test", TrustPolicy.Action.INFORM)
}
// Signed metadata verification defaults to RequireSigned (see below)
// override by calling preferSignedMetadata() or ignoreSignedMetadata()
}
}When not using configureEtsiTrust, provide the trust source explicitly:
configureIssuerTrust {
trustSource(isChainTrusted) // manually built IsChainTrustedForEUDIW
classifications(myClassifications) // AttestationClassifications from ETSI library
policy { default(TrustPolicy.Action.ENFORCE) }
}trustSource-- sets the trust anchor source. Accepts aComposeChainTrust,IsChainTrustedForEUDIW, or a pre-builtIsChainTrustedForAttestation. Optional whenconfigureEtsiTrustis configured.classifications-- required when usingComposeChainTrustorIsChainTrustedForEUDIWas the trust source. Maps credential types to verification contexts.policy-- configures how the wallet acts on trust results (see below).preferSignedMetadata()/ignoreSignedMetadata()-- relaxes the defaultRequireSignedmetadata policy (see Signed Issuer Metadata Verification).doNotVerify()-- turns issuer trust verification off; the other settings are ignored.
Without configureEtsiTrust, a wallet that requires signed issuer metadata (the default) with
IssuerRegistrationPolicy.Enabled (the default) also needs configureIssuerRegistrationTrust(...) or
configureIssuerRegistrationPolicy(IssuerRegistrationPolicy.Disabled); otherwise building the wallet
fails. See REGISTRATION_CERTIFICATE.md.
A TrustPolicy determines the action taken when an issuer is not trusted:
| Action | Behaviour |
|---|---|
ENFORCE |
Reject the credential -- delete it and emit IssueEvent.DocumentFailed. |
INFORM |
Store the credential regardless and attach the result to DocumentIssued. |
A credential whose issuer signature does not verify with its certificate is rejected under both policies.
The default policy is ENFORCE for all credentials. Use the policy DSL to override per
verification context or per attestation type. Resolution order (highest priority first):
- Per-attestation overrides (
forDocType,forVct,forAttestation) - Per-context overrides (
forContext) - Default action (
default)
The trust verification result is available on IssueEvent.DocumentIssued and
IssueEvent.DocumentFailed:
manager.issueDocumentByOfferUri(offerUri) { event ->
when (event) {
is IssueEvent.DocumentIssued -> {
when (event.issuerTrustResult) {
is CertificationChainValidation.Trusted -> {
// Issuer is trusted
}
is CertificationChainValidation.NotTrusted -> {
// INFORM policy: credential stored, but issuer was not trusted
}
null -> {
// Issuer not verified: doNotVerify(), or not evaluated under INFORM
}
}
}
is IssueEvent.DocumentFailed -> {
if (event.cause is IssuerNotTrustedException) {
// ENFORCE policy: credential rejected because issuer was not trusted
Log.w("Trust", "Issuer not trusted", event.cause)
}
}
else -> Unit
}
}The library includes built-in verifiers for MsoMdoc and SD-JWT VC formats. To support
additional credential formats, implement the CredentialTrustVerifier interface and register
it during configuration:
class MyCustomVerifier(
private val isChainTrusted: IsChainTrustedForAttestation<List<X509Certificate>, TrustAnchor>,
) : CredentialTrustVerifier {
override suspend fun verify(
credentialValue: String,
attestationIdentifier: AttestationIdentifier,
): CertificationChainValidation<TrustAnchor>? {
// Extract certificate chain from the credential and evaluate trust
// Return null if the chain cannot be extracted
}
}
// Register during configuration
configureIssuerTrust {
trustSource(myComposeChainTrust)
classifications(myClassifications)
credentialTrustVerifier(MyCustomFormat::class, MyCustomVerifier(isChainTrusted))
}The library supports verifying signed issuer metadata (JWT type openidvci-issuer-metadata+jwt)
as defined in OpenID4VCI. When an issuer provides signed metadata, the library extracts the x5c
certificate chain from the JWT header and validates it against the configured trust source.
Three metadata policies are available:
| Policy | Behaviour |
|---|---|
RequireSigned |
(Default) Signed metadata must be available and its certificate chain must be trusted. Otherwise issuance fails. |
PreferSigned |
Attempts to fetch signed metadata first. Falls back to unsigned if signed is not available. When signed metadata is served but the certificate chain is untrusted, issuance fails. |
IgnoreSigned |
Signed metadata is ignored; only unsigned metadata is used. Must be set explicitly via ignoreSignedMetadata(). |
When configureIssuerTrust is used with an IsChainTrustedForEUDIW trust source (the
standard LoTE setup), signed metadata verification defaults to RequireSigned. The library
automatically creates the trust adapter using
VerificationContext.WalletRelyingPartyAccessCertificate.
The metadata policy applies to issuance from a credential offer, to wallet-initiated issuance and
to re-issuance. Validation of the credential issuer's registration certificate requires
RequireSigned, because the certificate is carried in the signed metadata; with PreferSigned or
IgnoreSigned it is skipped.
To override the default metadata policy:
configureIssuerTrust {
trustSource(isChainTrusted)
classifications(myClassifications)
policy { default(TrustPolicy.Action.ENFORCE) }
// Prefer signed, but fall back to unsigned if not available
preferSignedMetadata()
// Or explicitly disable signed metadata verification
// ignoreSignedMetadata()
}Note: Metadata verification is a separate check from credential trust verification. Metadata trust runs before credential issuance (during offer resolution / issuer metadata fetch), while credential trust runs after the credential is received. Both are independent and can be configured separately.
The document status resolver can optionally verify that the signer of status list tokens (JWT or CWT) is trusted according to ETSI trusted lists. This adds an additional layer of trust beyond the default cryptographic signature verification (x5c/COSE_X509).
Configure status list trust within the configureDocumentStatusResolver DSL. When
configureEtsiTrust is used, the trust source and classifications are inherited — only
clock skew and optional policy overrides are needed:
val walletConfig = EudiWalletConfig {
configureEtsiTrust { /* ... */ }
configureDocumentStatusResolver {
clockSkew(5) // minutes
// Trust source and classifications inherited from configureEtsiTrust.
// Optionally override policy:
configureTrust {
policy {
default(TrustPolicy.Action.INFORM)
}
}
}
}When not using configureEtsiTrust, provide the trust source explicitly inside configureTrust:
configureDocumentStatusResolver {
clockSkew(5)
configureTrust {
trustSource(isChainTrusted) // manually built trust source
classifications(myClassifications)
policy { default(TrustPolicy.Action.INFORM) }
}
}The configureTrust block accepts the same DSL as issuer trust (trustSource,
classifications, policy). The trust policy determines the action when the status list
token signer is not trusted:
| Action | Behaviour |
|---|---|
ENFORCE |
Reject the status result — treat the document's revocation status as unknown. |
INFORM |
Accept the status result regardless and let the application decide. |
When status list trust is not configured, the resolver falls back to standard x5c / COSE_X509 signature verification without ETSI trust chain validation.
Reader certificate chain validation can be delegated to the ETSI library's
IsChainTrustedForEUDIW using the WalletRelyingPartyAccessCertificate (WRPAC)
verification context. All trust sources and enforcement are configured through the unified
configureReaderAuthentication DSL.
Using centralized ETSI trust (recommended): The trust source is inherited from
configureEtsiTrust — only the enforcement policy needs to be set:
val config = EudiWalletConfig {
configureEtsiTrust { /* ... */ }
configureReaderAuthentication {
alwaysRequire()
// trust source resolved from configureEtsiTrust at build time
}
}Using a manually built trust source: Pass IsChainTrustedForEUDIW directly via
trustSource():
val config = EudiWalletConfig {
configureReaderAuthentication {
trustSource(isChainTrusted)
alwaysRequire()
}
}Using static certificates: Pass certificates directly and configure the revocation
checking policy (defaults to RevocationPolicy.HardFail):
val config = EudiWalletConfig {
configureReaderAuthentication {
trustedCertificates(trustedCert1, trustedCert2)
revocationPolicy(RevocationPolicy.SoftFail)
enforceIfPresent()
}
}The available revocation policies are:
| Policy | Behavior |
|---|---|
RevocationPolicy.HardFail |
(Default) Validation fails if a certificate is revoked or if the CRL/OCSP responder cannot be reached. |
RevocationPolicy.SoftFail |
Validation fails if a certificate is revoked, but tolerates CRL/OCSP unavailability. |
RevocationPolicy.NoCheck |
No revocation checking is performed. |
Note:
RevocationPolicyonly applies to the static certificate-basedtrustedCertificates()overloads and toconfigureWrpRegistrationTrust/configureIssuerRegistrationTrust. When using ETSI/LoTE-based trust (viaconfigureEtsiTrust), revocation checking is controlled bypkixRevocationPolicy()inside theconfigureEtsiTrustblock instead. See Trusted Lists for details onPkixRevocationPolicyoptions.
For advanced use cases requiring a specific verification context, create an
EtsiReaderTrustStore explicitly and pass it as a custom trust source:
val readerTrustStore = EtsiReaderTrustStore(
isChainTrusted = isChainTrusted,
verificationContext = VerificationContext.WalletRelyingPartyAccessCertificate,
)
val config = EudiWalletConfig {
configureReaderAuthentication {
trustSource(readerTrustStore)
alwaysRequire()
}
}Note: For best performance during presentations, pre-warm the ETSI cache on app startup. This ensures that trust anchors are already resolved and cached before the first reader authentication occurs.
The following example shows a complete EudiWallet setup with issuer trust verification,
signed metadata verification, revocation status trust, and reader authentication — all
using configureEtsiTrust to centralize the shared LoTE infrastructure:
val config = EudiWalletConfig {
configureOpenId4Vci {
withIssuerUrl("https://issuer.example.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
}
configureOpenId4Vp {
withClientIdSchemes(ClientIdScheme.X509SanDns)
withSchemes("openid4vp", "eudi-openid4vp", "mdoc-openid4vp")
// Encryption policy — defaults to EncryptionPolicy.HAIP, which accepts only
// encrypted response modes (`direct_post.jwt` for OpenID4VP, `dc_api.jwt` for DC-API).
// Override via .withEncryptionPolicy(...) if a different profile is needed.
withEncryptionPolicy(EncryptionPolicy.HAIP)
}
// Centralized ETSI trust — builds the full LoTE pipeline internally
configureEtsiTrust {
loteLocations(SupportedLists(
pidProviders = Uri("https://trust.example.eu/pid-providers.jwt"),
wrpacProviders = Uri("https://trust.example.eu/wrpac-providers.jwt"),
))
classifications(AttestationClassifications(
pids = AttestationIdentifierPredicate.any(setOf(
AttestationIdentifier.MDoc("eu.europa.ec.eudi.pid.1"),
AttestationIdentifier.SDJwtVc("urn:eudi:pid:1"),
)),
pubEAAs = AttestationIdentifierPredicate.equalsTo(
AttestationIdentifier.MDoc("org.iso.18013.5.1.mDL")
),
))
// DEV/testing relaxations (omit in production):
// relaxCertificateProfiles()
// pkixRevocationPolicy(PkixRevocationPolicy.Disabled) // or SoftFail for testing
}
// Issuer trust — trust source + classifications inherited from configureEtsiTrust
// Signed metadata verification defaults to RequireSigned
configureIssuerTrust {
policy {
default(TrustPolicy.Action.ENFORCE)
}
}
// Revocation status trust — trust source + classifications inherited
configureDocumentStatusResolver {
clockSkew(5)
}
// Reader authentication — trust source inherited, enforcement set inline
configureReaderAuthentication {
enforceIfPresent()
}
}The library provides issuing documents using OpenID4VCI protocol. To issue a document
using this functionality, EudiWallet must be initialized with the openId4VciConfig configuration,
during configuration. See the Initialize the library section.
To validate issuer trust before storing credentials, see Trusted Lists.
First, you need an instance of the OpenId4VciManager class. You can create an instance of the
class by calling the EudiWallet.createOpenId4VciManager method:
// Create an instance of OpenId4VciManager using wallet-wide configuration
val openId4VciManager = wallet.createOpenId4VciManager()
// Or provide a specific configuration for this instance
val customConfig = OpenId4VciManager.Config.Builder()
.withIssuerUrl("https://custom-issuer.com")
.withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
.withAuthFlowRedirectionURI("eudi-openid4ci://custom-authorize")
.withIssuanceProofProfile(OpenId4VciManager.IssuanceProofProfile.Standard)
.withSupportedCredentialReusePolicies(
CredentialReusePolicies.Supported(
setOf(EudiReusePolicyType.OnceOnly, EudiReusePolicyType.LimitedTime)
)
)
.build()
val openId4VciManagerWithCustomConfig = wallet.createOpenId4VciManager(customConfig)
// You can also provide a custom HTTP client factory
val openId4VciManagerWithCustomHttpClient = wallet.createOpenId4VciManager(
config = customConfig,
ktorHttpClientFactory = {
HttpClient(OkHttp) {
// Custom HTTP client configuration
}
}
)The issuer trust, signed metadata and issuer registration settings of EudiWalletConfig apply to
managers created with createOpenId4VciManager, also when a custom OpenId4VciManager.Config is
passed. A manager created with OpenId4VciManager.Builder or OpenId4VciManager(context) { } does
not use signed issuer metadata, does not verify the issuer against trusted lists, and does not
validate the issuer's registration certificate.
NOTE: When withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased) is configured, the EudiWallet must also be instantiated with a WalletProvider
The createOpenId4VciManager method can accept an optional OpenId4VciManager.Config parameter:
- If you provide a configuration parameter, that configuration will be used for the created manager instance.
- If you don't provide a configuration parameter, the method will attempt to use the configuration
from
EudiWalletConfig.openId4VciConfig. - If neither are provided, the method will throw an
IllegalStateExceptionwith a message indicating that you need to provide configuration either as a method parameter or in theEudiWalletConfig.
This flexibility allows you to:
- Use a single global configuration for all OpenId4VCI operations by configuring it once in
EudiWalletConfig - Override the global configuration for specific operations by passing a custom configuration
- Provide a custom HTTP client for specific operations while using the global configuration
The library provides the OpenId4VciManager.resolveDocumentOffer method that resolves the
credential offer URI.
The method returns the resolved
Offer object that
contains the offer's data. The offer's data can be displayed to the user.
The following example shows how to resolve a credential offer:
val offerUri = "https://issuer.com/?credential_offer=..."
// Create an instance of OpenId4VciManager
val openId4VciManager = wallet.createOpenId4VciManager()
openId4VciManager.resolveDocumentOffer(offerUri) { result ->
when (result) {
is OfferResult.Success -> {
val offer: Offer = result.offer
// display the offer's data to the user
val issuerName = offer.issuerName
val offeredDocuments: List<OfferedDocument> = offer.offeredDocuments
val txCodeSpec: Offer.TxCodeSpec? =
offer.txCodeSpec // information about pre-authorized flow
// ...
}
is OfferResult.Failure -> {
val error = result.cause
// handle error while resolving the offer
}
}
}There is also the availability for the OpenId4VciManager.resolveDocumentOffer method to specify
the executor in which the onResolvedOffer callback is executed, by assigning the executor
parameter. If the executor parameter is null, the callback will be executed on the main thread.
val executor = Executors.newSingleThreadExecutor()
openId4VciManager.resolveDocumentOffer(offerUri, executor) { result ->
// ...
}First, you need an instance of the OpenId4VciManager class. You can create an instance of the
class by calling the EudiWallet.createOpenId4VciManager method.
There are two ways to issue a document using OpenID4VCI:
- Using the
OpenId4VciManager.issueDocumentByFormatmethod, when the document's format is known. In case of MsoMdoc format, the docType is required. In case of SdJwtVc format, vct is required. - Using the
OpenId4VciManager.issueDocumentByOfferorOpenId4VciManager.issueDocumentByOfferUrimethods, when an OpenId4VCI offer is given. - Using the
issueDocumentByConfigurationIdentifiersmethod, when the document's configuration identifier is known. The configuration identifiers can be retrieved from the issuer's metadata, using thegetIssuerMetadatamethod.
Important note:
- Currently, only the ES256 algorithm is supported for signing OpenId4CVI proof of possession of the publicKey.
- See the CustomizeSecureArea.md for more information on how to use the wallet-core library and OpenId4VCI with custom SecureArea implementations.
- A credential whose data is nested deeper than 64 levels is not stored, and the document fails
with
IssueEvent.DocumentFailed(DeferredIssueResult.DocumentFailedfor deferred issuance). For details, seeCBORObjectExtensions.kt(mdoc) andJsonElementExtensions.kt(SD-JWT VC).
The following example shows how to issue a document using OpenID4VCI:
val onIssueEvent = OnIssueEvent { event ->
when (event) {
is IssueEvent.Started -> {
// Process started, show progress
val numberOfDocumentsToBeIssued = event.total
}
is IssueEvent.DocumentRequiresCreateSettings.MandatoryReusePolicy -> {
// Issuer advertises a mandatory credential reuse policy (ETSI TS 119 472-3).
// The credential policy and batch size are determined by the resolved policy.
// The wallet only needs to provide key-related settings (secure area, authentication).
val resolvedPolicy = event.resolvedReusePolicy
// Resume with secure area identifier and key settings only
val (secureAreaId, keySettings) = eudiWallet.getDefaultCreateKeySettings()
event.resume(secureAreaId, keySettings)
// Or cancel
// event.cancel("User cancelled")
}
is IssueEvent.DocumentRequiresCreateSettings.OptionalReusePolicy -> {
// No issuer reuse policy — the wallet has full control over CreateDocumentSettings,
// including credential policy and number of credentials.
//
// Important: For OnceOnly and RotatingBatch policies, numberOfCredentials must not
// exceed event.offeredDocument.batchCredentialIssuanceSize (the issuer's upper limit
// for batch issuance).
val maxBatchSize = event.offeredDocument.batchCredentialIssuanceSize
val createDocumentSettings = eudiWallet.getDefaultCreateDocumentSettings(
offeredDocument = event.offeredDocument,
credentialPolicy = CreateDocumentSettings.CredentialPolicy.OnceOnly(
numberOfCredentials = minOf(5, maxBatchSize)
)
)
// Resume with full settings
event.resume(createDocumentSettings)
// Or cancel
// event.cancel("User cancelled")
}
is IssueEvent.Finished -> {
// All documents issued, show success
val issuedDocumentIds = event.issuedDocuments
}
is IssueEvent.Failure -> {
// Overall process failed
val cause = event.cause
}
is IssueEvent.DocumentIssued -> {
// Individual document issued successfully
val documentId = event.documentId
val documentName = event.name
val docType = event.docType
}
is IssueEvent.DocumentFailed -> {
// Individual document failed to issue
val documentName = event.name
val docType = event.docType
val cause = event.cause
}
is IssueEvent.DocumentRequiresUserAuth -> {
// Document requires user authentication to sign
val signingAlgorithm = event.signingAlgorithm
val document = event.document
// Create keyUnlockData (e.g., prompt for biometrics)
val keyUnlockData = event.keysRequireAuth.mapValues { (keyAlias, secureArea) ->
getDefaultKeyUnlockData(secureArea, keyAlias)
}
// Resume after authentication
event.resume(keyUnlockData)
// Or cancel the process
// event.cancel("User cancelled authentication")
}
is IssueEvent.DocumentDeferred -> {
// Issuance is deferred (will be issued later)
val documentId = event.documentId
val documentName = event.name
val docType = event.docType
}
}
}
// Create an instance of OpenId4VciManager
val openId4VciManager = wallet.createOpenId4VciManager()
// Issue by document type
openId4VciManager.issueDocumentByFormat(
format = MsoMdocFormat(docType = "eu.europa.ec.eudi.pid.1"),
txCode = "123456", // For pre-authorized flow
onIssueEvent = onIssueEvent
)
// Or by offer URI
openId4VciManager.issueDocumentByOfferUri(
offerUri = "https://issuer.com/?credential_offer=...",
txCode = "123456", // Optional
onIssueEvent = onIssueEvent
)
// Or by resolved offer
openId4VciManager.issueDocumentByOffer(
offer = offer,
txCode = "123456", // Optional
onIssueEvent = onIssueEvent
)There's also available for issueDocumentByFormat, issueDocumentByOfferUri and
issueDocumentByOffer methods to specify the executor in which the onIssueEvent callback is
executed, by assigning the executor parameter. If the executor parameter is null, the callback
will be executed on the main thread.
// Create an instance of OpenId4VciManager
val openId4VciManager = wallet.createOpenId4VciManager()
val executor = Executors.newSingleThreadExecutor()
openId4VciManager.issueDocumentByDocType(
docType = "eu.europa.ec.eudi.pid.1",
executor = executor
) { event ->
// ...
}For the authorization code flow to work, the application must handle the redirect URI. The redirect
URI is the URI that the Issuer will redirect the user to after the user has authenticated and
authorized. The redirect
URI must be handled by the application and resume the issuance process by calling the
OpenId4VciManager.resumeWithAuthorization.
Also, the redirect uri declared in the OpenId4VCI configuration must be declared in the
application's manifest file.
Important note: The resumeWithAuthorization method must be called from the same
OpenId4VciManager instance that was used to start the issuance process. You will need to keep the
reference of the OpenId4VciManager instance that was used for calling the
issueDocumentByFormat, issueDocumentByOfferUri or issueDocumentByOffer method and use this
same instance to call the resumeWithAuthorization method.
<!-- AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- rest of manifest -->
<activity android:name=".MainActivity" android:exported="true">
<!-- rest of activity -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="eudi-openid4ci" android:host="authorize" />
</intent-filter>
</activity>
</application>
</manifest> // ...
EudiWalletConfig()
// ...
.configureOpenId4Vci {
// ...
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
// ...
}
//...class SomeActivity : AppCompatActivity() {
val openId4VciManager: OpenId4VciManager
get() {
// get the OpenId4VciManager instance that was created during the issuance process
// ...
}
// ...
override fun onResume() {
super.onResume()
// check if intent is from the redirect uri to resume the issuance process
// ...
// then call
intent.data?.let { uri -> openId4VciManager.resumeWithAuthorization(uri) }
}
// ...
}By default, the library uses BrowserAuthorizationHandler which opens the system browser for user authorization during the authorization code flow. However, you can provide a custom authorization handler to implement alternative authorization flows, such as using an in-app WebView, a custom browser tab, or any other mechanism.
When no custom authorization handler is specified, the library automatically uses BrowserAuthorizationHandler. The resumeWithAuthorization method (shown in the previous section) should be used to complete the authorization flow.
Important: The resumeWithAuthorization method should only be called when using the default BrowserAuthorizationHandler. Custom authorization handlers manage their own flow completion.
To implement a custom authorization handler, create a class that implements the AuthorizationHandler interface:
class CustomAuthorizationHandler : AuthorizationHandler {
override suspend fun authorize(authorizationUrl: String): Result<AuthorizationResponse> {
// 1. Present the authorizationUrl to the user
// (e.g., open WebView, Chrome Custom Tab, or other UI)
// 2. Monitor for the redirect callback containing the authorization response
// 3. Extract the authorization code and state from the callback URI
val authorizationCode = extractAuthorizationCode()
val serverState = extractServerState()
// 4. Return the result
return if (authorizationCode != null && serverState != null) {
Result.success(AuthorizationResponse(authorizationCode, serverState))
} else {
Result.failure(IllegalStateException("Authorization failed or was cancelled"))
}
}
private suspend fun extractAuthorizationCode(): String? {
// Implementation depends on your authorization mechanism
TODO("Extract authorization code from your authorization flow")
}
private suspend fun extractServerState(): String? {
// Implementation depends on your authorization mechanism
TODO("Extract state parameter from your authorization flow")
}
}To use a custom authorization handler, provide it when configuring OpenId4VCI:
// Create your custom handler
val customAuthHandler = CustomAuthorizationHandler()
// Configure during wallet initialization
EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.example.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.None("client-id"))
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
withAuthorizationHandler(customAuthHandler)
}
// Or provide it when creating a specific OpenId4VciManager instance
val customConfig = OpenId4VciManager.Config.Builder()
.withIssuerUrl("https://issuer.example.com")
.withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.None("client-id"))
.withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
.withAuthorizationHandler(customAuthHandler)
.build()
val openId4VciManager = wallet.createOpenId4VciManager(customConfig)Important Notes:
- When using a custom
AuthorizationHandler, you are responsible for:- Presenting the authorization URL to the user
- Monitoring for the redirect URI callback
- Extracting the authorization code and state parameters from the callback
- Returning the
AuthorizationResponsewith the extracted values
- Do not call
resumeWithAuthorizationwhen using a custom handler - your handler manages the complete flow - The
authorizemethod is a suspending function that should only return when authorization is complete or has failed - Custom handlers enable use cases like in-app WebViews, Chrome Custom Tabs, or other custom authorization UIs
When Issuer supports the pre-authorization code flow, the resolved offer will also contain the
corresponding information. Specifically, the txCodeSpec field in the Offer object will contain:
- The input mode, whether it is NUMERIC or TEXT
- The expected length of the input
- The description of the input
From the user's perspective, the application must provide a way to input the transaction code.
When the transaction code is provided, the issuance process can be resumed by calling any of the following methods:
EudiWallet.issueDocumentByConfigurationIdentifiersEudiWallet.issueDocumentByFormatEudiWallet.issueDocumentByOfferUriEudiWallet.issueDocumentByOffer
passing the transaction code as in the txCode parameter.
When the document issuance is deferred, the IssueEvent.DocumentDeferred event is triggered. The
deferred document can be issued later by calling the OpenId4VciManager.issueDeferredDocument
method.
// given a deferred document, for example:
val deferredDocumentId: DocumentId = "deferred-document-id"
val deferredDocument = wallet.getDocumentById(deferredDocumentId) as DeferredDocument
val openId4VciManager: OpenId4VciManager = wallet.createOpenId4VciManager()
openId4VciManager.issueDeferredDocument(deferredDocument) { result ->
when (result) {
is DeferredIssueResult.DocumentIssued -> {
// document issued
}
is DeferredIssueResult.DocumentFailed -> {
// error
val cause = result.cause
}
is DeferredIssueResult.DocumentNotReady -> {
// The document is not issued yet; result.interval, when the issuer gave one,
// is how long it asked the wallet to wait before querying again
}
is DeferredIssueResult.DocumentExpired -> {
// The document is expired and cannot be issued
}
}
}The library supports re-issuing previously issued credentials without requiring the user to go through the full authorization flow again. After a credential is successfully issued, the library automatically stores the authorization context. This metadata enables subsequent re-issuance using the stored refresh token.
Use this when the user explicitly triggers a credential refresh. If the stored tokens have expired, the library falls back to a full OAuth authorization flow:
val openId4VciManager = wallet.createOpenId4VciManager()
openId4VciManager.reissueDocument(documentId) { event ->
when (event) {
is IssueEvent.Started -> {
// Re-issuance process started
}
is IssueEvent.DocumentIssued -> {
// New credential issued successfully
// The old document is automatically deleted
}
is IssueEvent.DocumentDeferred -> {
// Credential issuance is deferred (server-side processing)
// Old document remains until the deferred credential is issued
}
is IssueEvent.Failure -> {
// Re-issuance failed
val cause = event.cause
}
is IssueEvent.Finished -> {
// Re-issuance process completed
}
else -> {}
}
}For performing re-issuance in the background, pass allowAuthorizationFallback = false to reissueDocument() if you want
to prevent the library from triggering the authorization flow if the refresh token is no longer valid (default implementation is opening a browser). In this scenario a ReissuanceAuthorizationException is delivered via
IssueEvent.Failure:
openId4VciManager.reissueDocument(
documentId = documentId,
allowAuthorizationFallback = false,
) { event ->
when (event) {
is IssueEvent.Failure -> {
if (event.cause is ReissuanceAuthorizationException) {
// Tokens expired — ReIssuance failed
} else {
// Other error
}
}
is IssueEvent.DocumentIssued -> {
// Successfully re-issued in background
}
else -> {}
}
}DPoP (Demonstrating Proof-of-Possession) is a security mechanism that cryptographically binds OAuth 2.0 access tokens to keys, preventing token theft and replay attacks during credential issuance. The library provides flexible configuration options for DPoP, from simple default setup to fully customized implementations.
By default, DPoP is enabled with DPopConfig.Default, which uses Android Keystore with secure
defaults:
val config = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
// DPoP is enabled by default with DPopConfig.Default
// No additional configuration needed
}The default configuration automatically:
- Creates keys in hardware-backed Android Keystore when available
- Stores key metadata in the app's no-backup directory
- Uses StrongBox if the device supports it
- Negotiates the algorithm with the authorization server
- Requires no user authentication for key usage
DPoP is used when the authorization server supports it, that is, when it advertises
dpop_signing_alg_values_supported; otherwise the access token is issued without DPoP.
If you need to disable DPoP (not recommended for production):
val config = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
withDPopConfig(DPopConfig.Disabled)
}For advanced use cases, you can fully customize how DPoP keys are created and used with
DPopConfig.Custom. This gives you control over:
- The secure area used for key storage
- Key creation settings per algorithm
- User authentication requirements
- Key unlock mechanisms
Example:
val walletConfig = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.example.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
// Custom DPoP configuration
withDPopConfig(
DPopConfig.Custom(
secureArea = myCustomSecureArea,
createKeySettings = { algorithm ->
when (algorithm) {
Algorithm.ES256 -> MyCreateKeySettings(
useStrongBox = true,
userAuthenticationRequired = true
)
else -> MyCreateKeySettings()
}
},
keyUnlockData = { keyAlias ->
MyKeyUnlockData(keyAlias)
}
)
)
}The library supports encrypting credential responses from the issuer, as defined in the
OpenID4VCI specification.
This is configured via the responseEncryptionConfig property of OpenId4VciManager.Config.
By default, credential response encryption is required (CredentialResponseEncryptionPolicy.REQUIRED)
with EC P-256 and RSA 2048.
val config = EudiWalletConfig()
.configureOpenId4Vci {
// ..............................
// Use encryption only if the issuer supports it (instead of requiring it)
withResponseEncryptionConfig(
EncryptionSupportConfig(
credentialResponseEncryptionPolicy = CredentialResponseEncryptionPolicy.SUPPORTED,
ecConfig = EcConfig(ecKeyCurve = Curve.P_256),
rsaConfig = RsaConfig(rcaKeySize = 2048),
)
)
}The available policies are:
CredentialResponseEncryptionPolicy.REQUIRED(default) -- encryption must be used; issuance fails if the issuer does not support it.CredentialResponseEncryptionPolicy.SUPPORTED-- encryption is used when the issuer advertises support for it, but issuance proceeds unencrypted otherwise.
The library supports configurable proof type negotiation during credential issuance via
IssuanceProofProfile. This determines which proof types the wallet advertises to issuers and the
priority order used when negotiating.
During issuance, the wallet iterates through the profile's preference order and selects the first proof type that is both supported by the issuer and can be fulfilled by the wallet.
| Profile | Preference order | Use case |
|---|---|---|
IssuanceProofProfile.Etsi (default) |
Attestation, JWT with key attestation | ETSI TS 119 472-3 / EUDI Wallet. Requires WalletAttestationsProvider. |
IssuanceProofProfile.Standard |
JWT without key attestation, JWT with key attestation, Attestation, No proof | Base OpenID4VCI without ETSI profiling. |
// ETSI profile (default — no configuration needed)
val config = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
// Etsi is the default — explicit call not required
// withIssuanceProofProfile(OpenId4VciManager.IssuanceProofProfile.Etsi)
}
// Standard OpenID4VCI profile
val standardConfig = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.None("client-id"))
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
withIssuanceProofProfile(OpenId4VciManager.IssuanceProofProfile.Standard)
}For full control over the proof type order and per-type algorithms:
import eu.europa.ec.eudi.wallet.issue.openid4vci.OpenId4VciManager.IssuanceProofProfile
import eu.europa.ec.eudi.wallet.issue.openid4vci.OpenId4VciManager.IssuanceProofProfile.ProofType
import eu.europa.ec.eudi.wallet.issue.openid4vci.OpenId4VciManager.IssuanceProofProfile.ProofTypeConfig
val customProfile = IssuanceProofProfile.Custom(
preferenceOrder = listOf(
ProofTypeConfig(ProofType.JWT_WITHOUT_KEY_ATTESTATION),
ProofTypeConfig(
ProofType.JWT_WITH_KEY_ATTESTATION,
algorithms = setOf(Algorithm.ESP256), // restrict to ES256 only
),
)
)
val config = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.None("client-id"))
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
withIssuanceProofProfile(customProfile)
}The previous withSupportedProofTypes(SupportedProofTypes(...)) API is deprecated.
It is automatically converted to IssuanceProofProfile.Custom internally when no explicit
withIssuanceProofProfile is set. To migrate, replace:
// Before (deprecated)
.withSupportedProofTypes(
OpenId4VciManager.SupportedProofTypes(
jwtProofAlgorithms = setOf(Algorithm.ESP256),
attestationProofAlgorithms = setOf(Algorithm.ESP256),
)
)
// After
.withIssuanceProofProfile(
OpenId4VciManager.IssuanceProofProfile.Custom(
preferenceOrder = listOf(
ProofTypeConfig(ProofType.ATTESTATION, setOf(Algorithm.ESP256)),
ProofTypeConfig(ProofType.JWT_WITH_KEY_ATTESTATION, setOf(Algorithm.ESP256)),
)
)
)The library supports credential reuse policies as defined in ETSI TS 119 472-3 and the EU Digital
Identity Wallet Architecture Reference Framework (ARF) Annex II. When an issuer advertises a
credential_reuse_policy in its credential metadata, the library resolves it against the wallet's
declared capabilities and provides the result to the application during issuance.
- Wallet declares supported policies via
withSupportedCredentialReusePolicies()on theOpenId4VciManager.Config.Builder. This is a wallet-level capability declaration, not per-document. - During issuance, the library reads the issuer's
credential_reuse_policyfrom the credential configuration metadata. It selects the first option from the issuer's prioritized list that the wallet supports. - The resolved policy is delivered to the wallet via one of two event variants:
IssueEvent.DocumentRequiresCreateSettings.MandatoryReusePolicy— the issuer mandates a reuse policy. The credential policy (including batch size) is determined by the resolved policy. The wallet only provides key-related settings (secure area identifier and key settings).IssueEvent.DocumentRequiresCreateSettings.OptionalReusePolicy— no issuer reuse policy. The wallet has full control overCreateDocumentSettings, including credential policy and number of credentials.
| Method | CredentialPolicy type |
Behavior | Batch |
|---|---|---|---|
| Once-only (Method A) | OnceOnly(reissueTriggerUnused) |
Each credential used once, then deleted | Yes |
| Limited-time (Method B) | LimitedTime(reissueTriggerLifetimeLeft) |
Single credential presented multiple times until expiry | No |
| Rotating-batch (Method C) | RotatingBatch(reissueTriggerLifetimeLeft) |
Batch of credentials, rotated per presentation | Yes |
| Per-Relying-Party (Method D) | — | Different credential per relying party, consistent for repeats. Not yet supported — planned for a future release. | — |
Each policy type carries reissuance trigger thresholds from the issuer metadata. These can be used by the application to schedule credential re-issuance before credentials run out or expire.
Declare the reuse policy types your wallet supports:
val config = EudiWalletConfig()
.configureOpenId4Vci {
withIssuerUrl("https://issuer.com")
withClientAuthenticationType(OpenId4VciManager.ClientAuthenticationType.AttestationBased)
withAuthFlowRedirectionURI("eudi-openid4ci://authorize")
withSupportedCredentialReusePolicies(
CredentialReusePolicies.Supported(
setOf(
EudiReusePolicyType.OnceOnly,
EudiReusePolicyType.LimitedTime,
)
)
)
}If withSupportedCredentialReusePolicies is not called (default), the library will not match any
issuer-advertised reuse policy options. For issuers that advertise a reuse policy, this will result
in an error. For issuers that do not advertise a reuse policy, behavior is unchanged.
IssueEvent.DocumentRequiresCreateSettings is a sealed interface with two variants:
MandatoryReusePolicy: The issuer advertises a credential reuse policy. The credential policy and batch size are determined by the resolved policy. The wallet only provides key-related settings viaevent.resume(secureAreaIdentifier, createKeySettings).OptionalReusePolicy: No issuer reuse policy. The wallet has full control and provides completeCreateDocumentSettingsviaevent.resume(createDocumentSettings).
is IssueEvent.DocumentRequiresCreateSettings.MandatoryReusePolicy -> {
// Issuer dictates credential policy and batch size.
// The wallet only provides key-related settings.
val resolvedPolicy = event.resolvedReusePolicy
val (secureAreaId, keySettings) = eudiWallet.getDefaultCreateKeySettings()
event.resume(secureAreaId, keySettings)
}
is IssueEvent.DocumentRequiresCreateSettings.OptionalReusePolicy -> {
// No issuer reuse policy — wallet decides freely.
// For OnceOnly/RotatingBatch, numberOfCredentials must not exceed
// event.offeredDocument.batchCredentialIssuanceSize.
val maxBatchSize = event.offeredDocument.batchCredentialIssuanceSize
val settings = eudiWallet.getDefaultCreateDocumentSettings(
offeredDocument = event.offeredDocument,
credentialPolicy = CreateDocumentSettings.CredentialPolicy.OnceOnly(
numberOfCredentials = minOf(5, maxBatchSize)
),
)
event.resume(settings)
}The ResolvedReusePolicy object (available on MandatoryReusePolicy) contains:
| Property | Description |
|---|---|
credentialPolicy |
The CredentialPolicy to use (e.g., OnceOnly, LimitedTime). The batch size is embedded in the policy via numberOfCredentials. |
selectedEudiReusePolicy |
The raw EudiReusePolicy option selected from the issuer's metadata |
- Rotating-batch (Method C): Credentials are issued in a batch and their usage count is incremented on use. Full random-order selection and reshuffle-after-all-presented semantics are planned for a future release.
- Per-Relying-Party (Method D): Not yet supported. If an issuer advertises only PerRelyingParty
options, they are silently skipped and the
OptionalReusePolicyevent is emitted instead, giving the wallet full control. Support is planned for a future release.
CredentialPolicy.OneTimeUseandCredentialPolicy.RotateUsehave been removed. UseCredentialPolicy.OnceOnly()andCredentialPolicy.RotatingBatch()respectively.OnceOnly()withreissueTriggerUnused = nullprovides the same behavior as the oldOneTimeUse.RotatingBatch()withreissueTriggerLifetimeLeft = nullprovides the same behavior as the oldRotateUse.numberOfCredentialsmoved fromCreateDocumentSettingstoCredentialPolicy. Instead ofCreateDocumentSettings(numberOfCredentials = 5, credentialPolicy = OnceOnly()), useCreateDocumentSettings(credentialPolicy = OnceOnly(numberOfCredentials = 5)).IssueEvent.DocumentRequiresCreateSettingsis now a sealed interface with two variants:MandatoryReusePolicy(issuer-mandated, wallet provides key settings only) andOptionalReusePolicy(no issuer reuse policy, wallet provides fullCreateDocumentSettings).ResolvedReusePolicy.numberOfCredentialsremoved. The batch size is now embedded in thecredentialPolicyitself viaCredentialPolicy.numberOfCredentials.getDefaultCreateDocumentSettingsno longer accepts anumberOfCredentialsparameter. Set it on thecredentialPolicyinstead, e.g.,credentialPolicy = RotatingBatch(numberOfCredentials = 3).- Clean install required: This is a breaking change for persisted document metadata. Applications must be uninstalled and reinstalled.
- The
withSupportedCredentialReusePoliciesconfiguration is optional. When omitted, the library will not match any issuer-advertised reuse policy options.
To authenticate readers/verifiers using ETSI Trusted Lists, see Trusted Lists.
The library supports the following 3 ways to transfer documents:
- Offline document transfer between devices over BLE, according to the ISO 18013-5 specification
- Device engagement using QR code
- NFC device engagement
- Document retrieval to a website according to the ISO 18013-7 specification
- RestAPI using app link
- Document retrieval using OpenID4VP
The transfer process is asynchronous. During the transfer, events are emitted that indicate the current state of the transfer. The following events are emitted:
TransferEvent.QrEngagementReady: The QR code is ready to be displayed. Get the QR code fromevent.qrCode.TransferEvent.Connecting: The devices are connecting. Use this event to display a progress indicator.TransferEvent.Connected: The devices are connected.TransferEvent.RequestReceived: A request is received. Get the parsed request fromevent.requestedDocumentDataand the initial request as received by the verifier fromevent.request.TransferEvent.ResponseSent: A response is sent.TransferEvent.Redirect: This event prompts to redirect the user to the given Redirect URI. Get the Redirect URI fromevent.redirectUri. This event maybe be returned when OpenId4Vp is used as a transmission channel.TransferEvent.Rejected: The verifier rejected the wallet's response. Get the optional redirect URI fromevent.redirectUri. When non-null, the application should redirect the user to the verifier's page. This event is used for the OpenId4VP protocol.TransferEvent.Disconnected: The devices are disconnected.TransferEvent.Error: An error occurred. Get theThrowableerror fromevent.error.
To receive events from the EudiWallet, you must attach a TransferEvent.Listener to it:
The following example demonstrates how to implement a TransferEvent.Listener and attach it to the
EudiWallet object.
wallet.addTransferEventListener { event ->
when (event) {
is TransferEvent.QrEngagementReady -> {
// Qr code is ready to be displayed
val qrCodeBitmap = event.qrCode.asBitmap(size = 800)
// or
val qrCodeView = event.qrCode.asView(context, size = 800)
}
TransferEvent.Connecting -> {
// Informational event that devices are connecting
}
TransferEvent.Connected -> {
// Informational event that the transfer has been connected
}
is TransferEvent.RequestReceived -> try {
// get the processed request — Success carries presentmentData / requester /
// trustMetadata; Failure carries the error
val success = event.processedRequest.getOrThrow()
as RequestProcessor.ProcessedRequest.Success
// Render the consent UI from success.presentmentData; label the verifier
// using success.requester / success.trustMetadata.
// ...
// `presentmentSelections` contains one entry per disclosable variant. The
// application renders them to the user (typically as separate pages in a
// pager) and forwards the confirmed one to `generateResponse`.
val variants: List<CredentialSelection> = success.presentmentSelections
// The index the user picked in the consent UI (e.g. the active page of
// a pager).
val userSelectedIndex = 0
val selection: CredentialSelection = variants[userSelectedIndex]
val matches = selection.matches
// Unlock data for the key of each matched credential, keyed by
// `match.credential.identifier`.
val keyUnlockData: Map<String, KeyUnlockData> = matches.mapNotNull { match ->
val credential = match.credential as SecureAreaBoundCredential
getDefaultKeyUnlockData(credential.secureArea, credential.alias)
?.let { match.credential.identifier to it }
}.toMap()
// generate the response
val response = success.generateResponse(
selection = selection,
keyUnlockData = keyUnlockData
).getOrThrow()
wallet.sendResponse(response)
} catch (e: Throwable) {
// An error occurred — handle the error
}
TransferEvent.ResponseSent -> {
// Informational event that the response has been sent
}
is TransferEvent.Redirect -> {
// A redirect is needed. Used mainly for the OpenId4VP implementation
// This is triggered when Relaying Party (RP) has accepted the response and
// the RP is redirecting the user to the given redirect URI
// If this event is triggered, then the TransferEvent.ResponseSent event will not be triggered
val redirectUri = event.redirectUri // the redirect URI
}
is TransferEvent.Rejected -> {
// The verifier rejected the wallet's response (OpenId4VP)
val redirectUri = event.redirectUri // optional redirect URI
if (redirectUri != null) {
// redirect the user to the verifier's page
}
}
TransferEvent.Disconnected -> {
// Informational event that device has been disconnected
// stop the proximity presentation
wallet.stopProximityPresentation()
}
is TransferEvent.Error -> {
// An error occurred
val cause = event.error
// stop the proximity presentation
wallet.stopProximityPresentation()
}
}
}-
BLE transfer using QR Engagement
Once a transfer event listener is attached, use the
EudiWallet.startProximityPresentation()method to start the QR code engagement.wallet.startProximityPresentation() //... other code // in event listener when the qr code is ready to be displayed when (event) { is TransferEvent.QrEngagementReady -> { // show the qr code to the user val qrCode: QrCode = event.qrCode val qrBitmap = qrCode.asBitmap(size = 512) // get the qr code as bitmap // - or - val qrView = qrCode.asView(context, size = 512) // get the qr code as view } // ... rest of the event types else -> {} }
-
BLE transfer using NFC Engagement
To use NFC for engagement, you must implement a service that extends the abstract class
NfcEngagementServiceand register it in your application's manifest file, like shown below:<application> <!-- rest of manifest --> <service android:exported="true" android:label="@string/nfc_engagement_service_desc" android:name="com.example.app.MyNfcEngagementService" android:permission="android.permission.BIND_NFC_SERVICE"> <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" /> </intent-filter> <!-- the following "@xml/nfc_engagement_apdu_service" in meta-data is provided by the library --> <meta-data android:name="android.nfc.cardemulation.host_apdu_service" android:resource="@xml/nfc_engagement_apdu_service" /> </service> </application>
Then the service class must be also declared during wallet configuration using the
EudiWalletConfig.configureProximityPresentationmethod. For example see Initialize the library section.In your application you can enable or disable the NFC engagement in your app by calling the
wallet.enableNFCEngagement(ComponentActivity)andwallet.disableNFCEngagement(ComponentActivity)methods.In the example below, the NFC engagement is enabled when activity is resumed and disabled when the activity is paused.
class MainActivity : AppCompatActivity() { lateinit var wallet: EudiWallet override fun onResume() { super.onResume() wallet.enableNFCEngagement(this) } override fun onPause() { super.onPause() wallet.disableNFCEngagement(this) } }
-
RestAPI using app link
To enable ISO 18013-7 REST API functionality, declare to your app's manifest file (AndroidManifest.xml) an Intent Filter for your MainActivity:
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="mdoc" android:host="*" /> </intent-filter>
and set
launchMode="singleTask"for this activity.To initiate the transfer using an app link (reverse engagement), use the
wallet.startRemotePresentation(Uri)method. See the example below:class MainActivity : AppCompatActivity() { lateinit var wallet: EudiWallet // ... rest of activity code override fun onResume() { super.onResume() wallet.startRemotePresentation(intent.data!!) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) wallet.startRemotePresentation(intent.data!!) } }
To cancel the remote presentation, call the
wallet.stopRemotePresentation()method. -
OpenID4VP
To use the OpenID4VP functionality, the configuration that is used to initialize the library must contain the
openId4VpConfig. See the Initialize the library section.Then, declare to your app's manifest file (AndroidManifest.xml) the following Intent Filters for your MainActivity, for the scheme:
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="mdoc-openid4vp" android:host="*" /> </intent-filter>
Also set
launchMode="singleTask"for this activity.class MainActivity : AppCompatActivity() { lateinit var wallet: EudiWallet // ... rest of activity code override fun onResume() { super.onResume() handleOpenId4VpIntent(intent) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(null) handleOpenId4VpIntent(intent) } private fun handleOpenId4VpIntent(intent: Intent) { val uri = intent.data!! wallet.startRemotePresentation(uri) } }
To cancel the remote presentation, call the
wallet.stopRemotePresentation()method.
When a TransferEvent.RequestReceived event is triggered, the processed request can be obtained
by calling event.processedRequest.getOrThrow(). On success this returns a
RequestProcessor.ProcessedRequest.Success carrying three pieces of information that the
application consumes to render its consent UI and build the response:
| Field | Purpose |
|---|---|
presentmentData: CredentialQueryResult |
The tree of candidate credentials and the claims the verifier asked for. The application traverses this tree to render the consent UI and to build the user's choice. |
presentmentSelections: List<CredentialSelection> |
Ready-to-use selection variants the consent UI can render directly. Each entry is one disclosable combination — the UI typically lets the user choose which variant to share, and the confirmed one is then passed to generateResponse. Use this instead of walking presentmentData unless you need fine-grained control. |
requester: Requester |
The verifier's transport-level identity — certificate chain when reader-auth is present, plus appId / origin if available. |
trustMetadata: TrustMetadata? |
Non-null only when the verifier's cert chain validated against the configured ReaderTrustStore. Carries displayName for trusted-verifier UI; null means the UI should render an "unknown verifier" branch. |
CredentialQueryResult is a list of CredentialPresentmentSets. Each set is a group of
alternative ways the verifier's request can be satisfied:
CredentialQueryResult
└─ List<CredentialPresentmentSet> ← one per credential set in the request
├─ optional: Boolean ← required vs optional set
└─ List<CredentialPresentmentSetOption> ← alternative options inside the set
└─ List<CredentialPresentmentSetOptionMember> ← credentials required by the option
└─ List<CredentialPresentmentSetOptionMemberMatch> ← candidate credentials in the wallet
├─ credential: Credential ← the wallet's credential
├─ claims: Map<RequestedClaim, Claim> ← claims this match would disclose
└─ source: CredentialMatchSource ← the originating request (DCQL / ISO 18013)
For each set the user accepts, the application picks exactly one option, then one match per
member of that option, and collects them into a CredentialSelection. The
match.claims map already reflects the wallet's spec-compliant resolution of the verifier's
request (DCQL claim_sets first-match per §6.4.1, hard-fail on missing claims) — the UI can
display it as-is or further narrow it down if the user opts out of specific claims.
Each match.claims map is keyed by RequestedClaim, which has two concrete subtypes depending
on the credential format:
| Subtype | Fields | Used for |
|---|---|---|
MdocRequestedClaim |
docType, namespaceName, dataElementName, intentToRetain |
ISO mdoc / mso_mdoc |
JsonRequestedClaim |
vctValues, claimPath (a JSON-pointer-style path that may include array indices and null wildcards per OpenID4VP §7.1) |
SD-JWT VC |
The corresponding value (Claim) holds the actual disclosable data from the credential, so the
UI can render previews next to each claim entry (e.g. "first name: Alice").
After the user has confirmed which match(es) to use, the application builds a
CredentialSelection, attaches any per-credential KeyUnlockData keyed by
match.credential.identifier, and calls generateResponse:
val transferEventListener = TransferEvent.Listener { event ->
when (event) {
is TransferEvent.RequestReceived -> try {
// get the processed request — Success carries presentmentData / requester /
// trustMetadata; Failure carries the error
val success = event.processedRequest.getOrThrow()
as RequestProcessor.ProcessedRequest.Success
// `presentmentSelections` contains one entry per disclosable variant. The
// application renders them to the user (e.g. as separate pages in a
// pager) and forwards the confirmed one to `generateResponse`.
val variants: List<CredentialSelection> = success.presentmentSelections
// The index the user picked in the consent UI (e.g. the active page of
// a pager).
val userSelectedIndex = 0
val selection: CredentialSelection = variants[userSelectedIndex]
val matches = selection.matches
// If any picked credential requires unlock data (e.g. PIN-locked keys),
// build a map for the key of each matched credential, keyed by
// `match.credential.identifier`.
val keyUnlockData: Map<String, KeyUnlockData> = matches.mapNotNull { match ->
val credential = match.credential as SecureAreaBoundCredential
val unlockData = getDefaultKeyUnlockData(credential.secureArea, credential.alias)
// authenticate the user using unlockData.getCryptoObjectForSigning(...)
// if biometric / device-credential gating is required
unlockData?.let { match.credential.identifier to it }
}.toMap()
// generate the response
val response = success.generateResponse(
selection = selection,
keyUnlockData = keyUnlockData,
).getOrThrow()
wallet.sendResponse(response)
} catch (e: Throwable) {
// An error occurred — handle the error
}
// handle other events
else -> {}
}
}Note: Empty matches in presentmentData.credentialSets mean the request cannot be satisfied
with the credentials currently in the wallet — render an appropriate error state and do
not call generateResponse.
To reject a remote presentation request and notify the Verifier that the user has declined, call the wallet.rejectRemotePresentation() method
This method sends a "Negative Consensus" response to the Verifier. Once the rejection is successfully sent, the wallet will emit a TransferEvent.ResponseSent event
See also, the CustomizeSecureArea.md for more information on how to use the wallet-core library for presentation with custom SecureArea implementations.
A verifier can include transaction data in a presentation request. As introduced in OpenID4VP, the mechanism binds the user's identification and authentication to the user's authorisation of a transaction: the wallet displays the transaction data before consent and binds the presentation to it, so the presentation proves not only who the user is but what they agreed to.
The binding is a hash of the transaction data string exactly as received, carried in the Key Binding JWT. A transaction data type may additionally define a claim of its own, as OpenID4VP Appendix B.3.3 recommends.
For Qualified Electronic Signatures, transaction data carry the information the user needs in order
to understand and authorise a signing operation. Two types are defined for it, in ETSI TS 119 432
V1.3.1 and CSC Data Model Bindings 1.0, and this library models both: qesApprovalRequest,
with which a trust service provider asks the user to approve a signature it has prepared, and
qesRequest, with which a relying party asks for one or more documents to be signed.
This library parses transaction data, exposes it for display, binds the presentation to it and
records it in the transaction log. Creating the signature itself — the exchange with the trust
service provider and the return of the signed document — is the responsibility of the RQES
libraries (eudi-lib-android-rqes-core, eudi-lib-android-rqes-ui).
Note: For ISO/IEC 18013-5 mdoc, the issuer must have declared the data elements of the types it supports in the
KeyAuthorizationsof the mdoc. Otherwise, the request fails: OpenID4VP requires the wallet to reject a request whose data element is not authorized, and the verifier receivesinvalid_transaction_data.
The wallet processes only the transaction data types it declares. A request carrying an undeclared
type is rejected, and the verifier receives invalid_transaction_data.
val openId4VpConfig = OpenId4VpConfig.Builder()
// ... client id schemes, formats, encryption ...
.withTransactionDataTypes(
TransactionDataType.QES_APPROVAL, // https://cloudsignatureconsortium.org/2025/qes-approval
TransactionDataType.QES // https://cloudsignatureconsortium.org/2025/qes
)
.build()Declaring a type also provides the means to read it: each type carries the parser that converts the received JSON into a typed payload, and rejects objects that do not conform to it.
| Spec type | Type identifier | Constant |
|---|---|---|
qesApprovalRequest |
https://cloudsignatureconsortium.org/2025/qes-approval |
TransactionDataType.QES_APPROVAL |
qesRequest |
https://cloudsignatureconsortium.org/2025/qes |
TransactionDataType.QES |
A presented qesApprovalRequest adds one claim to the Key Binding JWT beside
transaction_data_hashes: org.cloudsignatureconsortium.dm.1.qesApproval, the approval the trust
service provider consumes to release the signature. CSC Data Model Bindings clause 7.2.1.2 defines
it as the digest of the transaction data string as received, taken with the algorithm of
hashAlgorithmOID and base64 encoded. Only that type adds it — a Credential presented for anything
else does not carry it.
A type whose contents need not be modelled can be declared with
TransactionDataType.raw(identifier); its objects are then read as plain JSON.
To model your own type, extend TransactionType and wrap it in a TransactionDataType:
@Serializable
data class Payment(
@SerialName("type") val type: String,
@SerialName("credential_ids") val credentialIds: List<String>,
@SerialName("transaction_data_hashes_alg") val hashAlgorithms: List<String>? = null,
@SerialName("amount") val amount: String,
@SerialName("payee") val payee: String,
)
object PaymentTransactionType : TransactionType<Payment>(
displayName = "Payment",
identifier = "https://example.com/2026/payment",
) {
override fun parseOpenId4VpRequest(jsonString: String): Payment =
Json.decodeFromString(Payment.serializer(), jsonString)
override fun parseJson(serialized: ByteString): TransactionData<Payment> {
val payload = parseOpenId4VpRequest(
serialized.decodeToString().fromBase64Url().decodeToString()
)
return TransactionData(
type = this,
payload = payload,
protocol = TransactionProtocol.OPENID4VP,
rawBytes = serialized,
hashAlgorithms = parseJoseHashAlgorithms(payload.hashAlgorithms),
)
}
}Then you can declare it as follows:
.withTransactionDataTypes(
TransactionDataType(PaymentTransactionType)
)A type that defines a top-level Key Binding JWT claim of its own — as OpenID4VP B.3.3 recommends —
also implements TransactionDataKeyBinding. Its claims are added beside
transaction_data_hashes, which the wallet always sends:
object PaymentTransactionType : TransactionType<Payment>(/* ... */), TransactionDataKeyBinding {
override fun keyBindingClaims(
transactionData: List<TransactionData<*>>
): Map<String, JsonElement> = mapOf("com.example.paymentApproval" to JsonPrimitive(/* ... */))
}A claim the Key Binding JWT sets itself — sd_hash, nonce, aud, iat, exp — is refused, as
are transaction_data_hashes and transaction_data_hashes_alg, and a name another declared type
already uses.
A type that defines a data element of its own — a namespace, a data element identifier and a value,
as OpenID4VP B.2.1 recommends — also implements TransactionDataDeviceSigned. Its data elements are
added to the DeviceSigned structure of an ISO/IEC 18013-5 mdoc presentation, and are therefore
protected by mdoc authentication:
object PaymentTransactionType : TransactionType<Payment>(/* ... */), TransactionDataDeviceSigned {
override val nameSpace: String = "com.example.payment.1"
override fun deviceSignedElements(
transactionData: List<TransactionData<*>>
): Map<String, DataItem> = mapOf("paymentApproval" to Bstr(/* ... */))
}Implementing this interface is required for mso_mdoc: a type that defines no data element cannot
be bound to an mdoc presentation, and the wallet does not declare it for that format.
OpenID4VP requires that a single Credential authorizes a transaction. The wallet therefore gives
each transaction data object to one query — the first of its credential_ids with a credential able
to authorize it. Each match of the selection carries the objects the Credential it presents will
authorize:
selection.matches.forEach { match ->
match.transactionData.forEach { data ->
when (val payload = data.payload) {
is QesApprovalRequest -> {
val qualifier = payload.signatureQualifier // e.g. "eu_eidas_qes"
payload.documentDigests.forEach { digest ->
show(label = digest.label, fingerprint = digest.hash, type = digest.hashType)
}
}
else -> { /* your own payload types */ }
}
}
}A presentation that carried transaction data records it on its log entry, base64url decoded and otherwise unread. The log is not specific to any type, so resolve it again with the types the wallet is configured with:
val entry = storedJson.toTransactionEntryOrNull()
if (entry is TransactionEntry.Presentation) {
val payloads: List<Any> = entry.transactionalData
?.payloads(wallet.config.openId4VpConfig?.transactionDataTypes.orEmpty())
.orEmpty()
payloads.forEach { payload ->
when (payload) {
is QesApprovalRequest -> showSignature(payload)
is JsonObject -> showJson(payload) // a raw type, or an entry no type could read
else -> { /* your own payload types */ }
}
}
}An entry is returned as the JsonObject it was recorded as when no type claims it, when it no
longer conforms to the type that does — for example after that type's definition changed — or when
the type that claims it was declared with raw. The three cases are indistinguishable.
The library can log transactions for auditing and analytics purposes. It records presentations (both proximity and remote), credential issuance and re-issuance, and credential deletions. Other transaction types (e.g. signing/sealing) can also be added through the same funnel. Each entry follows the EUDI Wallet Technical Specification 10 (TS10) data model.
To enable transaction logging, you need to implement the TransactionLogger interface and provide
it when initializing the EudiWallet instance:
// Implement the TransactionLogger interface
class MyTransactionLogger : TransactionLogger {
override fun log(transaction: TransactionEntry) {
// Store the entry in your own storage; here, serialized to JSON.
save(transaction.toJson())
}
}
// Then provide it when creating the wallet instance
val wallet = EudiWallet(context, config) {
// other configurations
withTransactionLogger(MyTransactionLogger())
}Important — entries are updated, not only appended.
log()is called more than once for the same transaction: once when it begins, and again when it finishes or fails. A credential the issuer defers is logged when it is requested and updated when it finally arrives. Every one of those calls carries the sametransactionIdentifier, so your storage has to upsert on that identifier. Appending each call instead leaves duplicate rows, and transactions stuck in their initial state.
Each entry is a TransactionEntry — a sealed type with one subtype per kind of transaction
(Presentation, CredentialIssuance, CredentialReissuance, CredentialDeletion,
SigningSealing, and more). Common information includes:
- The transaction identifier and timestamp
- The result (
Completed, orNotCompletedwith a reason) - The interacting party (name, identifier), when available
- For presentations: which claims were requested and presented, as identifiers and paths — never their values
- For presentations that carried transaction data: the objects themselves, unread — see Transaction Data
Serialize an entry for storage with toJson(), read it back with toTransactionEntryOrNull(), and
branch on its type:
// Store
database.save(entry.toJson())
// Read back (returns null if the stored value cannot be decoded)
val entry: TransactionEntry? = storedJson.toTransactionEntryOrNull()
when (entry) {
is TransactionEntry.Presentation -> {
val time = entry.time
val result = entry.transactionResult // Completed / NotCompleted(reason)
val party = entry.interactingPartyName?.content
// ClaimInfo: the credential id and claim paths involved — no values
val presented = entry.listOfClaimsPresented
}
is TransactionEntry.CredentialIssuance -> { /* entry.details */ }
is TransactionEntry.CredentialDeletion -> { /* entry.credentialIdentifier */ }
null -> { /* the stored value could not be decoded */ }
else -> { /* other transaction kinds */ }
}You can also record your own entry e.g. an OtherTransaction as follows:
wallet.transactionLogManager?.log(
TransactionEntry.OtherTransaction(
transactionIdentifier = UUID.randomUUID().toString(),
time = Instant.now(),
transactionResult = TransactionResult.Completed,
description = listOf("Backup exported"),
)
)To export the log, use TransactionLogExport, which produces a JSON document in the TS10 §4.1
format:
val json: String = TransactionLogExport().encode(entries)Note: The export is not the full spec object. TS10 defines the Transaction Log Object as "an exportable object in JSON Web Encryption format" this library currently produces only its plain-JSON content, without the JWE encryption.
We welcome contributions to this project. To ensure that the process is smooth for everyone involved, follow the guidelines found in CONTRIBUTING.md.
See licenses.md for details.
Copyright (c) 2023 European Commission
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.