Common Workflows

This guide documents common workflows for using TrustWeave in real-world applications.

Credential Issuance Workflow

Complete workflow for issuing a verifiable credential:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import com.trustweave.trust.TrustLayer
import com.trustweave.core.TrustWeaveError
import kotlinx.coroutines.runBlocking

suspend fun issueCredentialWorkflow(
    trustLayer: TrustLayer,
    issuerDid: String,
    holderDid: String,
    claims: Map<String, Any>
): Result<VerifiableCredential> {
    return try {
        // 1. Verify issuer DID is resolvable
        val context = trustLayer.getDslContext()
        val resolver = context.getDidResolver()
        val issuerResolution = resolver?.resolve(issuerDid)

        if (issuerResolution?.document == null) {
            return Result.failure(
                TrustWeaveError.DidNotFound(
                    did = issuerDid,
                    availableMethods = emptyList()
                )
            )
        }

        // 2. Get issuer key ID
        val issuerKeyId = "$issuerDid#key-1"

        // 3. Issue credential
        import com.trustweave.trust.types.IssuanceResult
        
        val issuanceResult = trustLayer.issue {
            credential {
                type("VerifiableCredential", "PersonCredential")
                issuer(issuerDid.value)
                subject {
                    id(holderDid.value)
                    claims.forEach { (key, value) ->
                        key to value
                    }
                }
            }
            signedBy(issuerDid = issuerDid.value, keyId = issuerKeyId)
        }
        
        val credential = when (issuanceResult) {
            is IssuanceResult.Success -> issuanceResult.credential
            else -> {
                return Result.failure(IllegalStateException("Failed to issue credential: ${issuanceResult.reason}"))
            }
        }

        Result.success(credential)
    } catch (error: TrustWeaveError) {
        Result.failure(error)
    }
}

Credential Verification Workflow

Complete workflow for verifying a verifiable credential:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
suspend fun verifyCredentialWorkflow(
    trustLayer: TrustLayer,
    credential: VerifiableCredential,
    checkTrust: Boolean = false
): CredentialVerificationResult {
    return try {
        val verification = trustLayer.verify {
            credential(credential)
            checkExpiration(true)
            checkRevocation(true)
            checkTrust(checkTrust)
        }

        // Log verification result
        if (verification.valid) {
            logger.info("Credential verified successfully", mapOf(
                "credentialId" to credential.id,
                "issuer" to credential.issuer
            ))
        } else {
            logger.warn("Credential verification failed", mapOf(
                "credentialId" to credential.id,
                "errors" to verification.errors
            ))
        }

        verification
    } catch (error: TrustWeaveError) {
        logger.error("Verification error", error)
        CredentialVerificationResult(
            valid = false,
            proofValid = false,
            issuerValid = false,
            notExpired = false,
            notRevoked = false,
            errors = listOf(error.message ?: "Unknown error"),
            warnings = emptyList()
        )
    }
}

Credential Revocation Workflow

Complete workflow for revoking a credential:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import com.trustweave.credential.revocation.*

suspend fun revokeCredentialWorkflow(
    statusListManager: StatusListManager,
    credentialId: String,
    statusListId: String,
    reason: String? = null
): Result<Boolean> {
    return try {
        // 1. Check if credential is already revoked
        val status = statusListManager.checkStatus(credentialId, statusListId)
        if (status.revoked) {
            return Result.success(false) // Already revoked
        }

        // 2. Revoke credential
        val revoked = statusListManager.revoke(
            credentialId = credentialId,
            statusListId = statusListId,
            reason = reason
        )

        if (revoked) {
            logger.info("Credential revoked", mapOf(
                "credentialId" to credentialId,
                "statusListId" to statusListId,
                "reason" to reason
            ))
        }

        Result.success(revoked)
    } catch (error: Exception) {
        logger.error("Revocation failed", error)
        Result.failure(error)
    }
}

Key Rotation Workflow

Complete workflow for rotating keys in a DID document:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
suspend fun rotateKeyWorkflow(
    trustLayer: TrustLayer,
    did: String,
    oldKeyId: String,
    newKeyId: String
): Result<DidDocument> {
    return try {
        // 1. Verify current DID document
        val context = trustLayer.getDslContext()
        val resolver = context.getDidResolver()
        val currentResolution = resolver?.resolve(did)

        if (currentResolution?.document == null) {
            return Result.failure(
                TrustWeaveError.DidNotFound(
                    did = did,
                    availableMethods = emptyList()
                )
            )
        }

        // 2. Verify old key exists
        val oldKey = currentResolution.document.verificationMethod
            .find { it.id == oldKeyId }

        if (oldKey == null) {
            return Result.failure(
                TrustWeaveError.ValidationFailed(
                    field = "oldKeyId",
                    reason = "Old key not found in DID document",
                    value = oldKeyId
                )
            )
        }

        // 3. Rotate key
        val updated = trustLayer.rotateKey {
            did(did)
            oldKeyId(oldKeyId)
            newKeyId(newKeyId)
        }

        logger.info("Key rotated successfully", mapOf(
            "did" to did,
            "oldKeyId" to oldKeyId,
            "newKeyId" to newKeyId
        ))

        Result.success(updated as DidDocument)
    } catch (error: TrustWeaveError) {
        logger.error("Key rotation failed", error)
        Result.failure(error)
    }
}

Trust Anchor Management Workflow

Complete workflow for managing trust anchors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
suspend fun manageTrustAnchorWorkflow(
    trustLayer: TrustLayer,
    anchorDid: String,
    credentialTypes: List<String>,
    description: String
): Result<Boolean> {
    return try {
        // 1. Verify anchor DID is resolvable
        val context = trustLayer.getDslContext()
        val resolver = context.getDidResolver()
        val resolution = resolver?.resolve(anchorDid)

        if (resolution?.document == null) {
            return Result.failure(
                TrustWeaveError.DidNotFound(
                    did = anchorDid,
                    availableMethods = emptyList()
                )
            )
        }

        // 2. Add trust anchor
        val added = trustLayer.addTrustAnchor(anchorDid) {
            credentialTypes(*credentialTypes.toTypedArray())
            description(description)
        }

        if (added) {
            logger.info("Trust anchor added", mapOf(
                "anchorDid" to anchorDid,
                "credentialTypes" to credentialTypes
            ))
        } else {
            logger.info("Trust anchor already exists", mapOf(
                "anchorDid" to anchorDid
            ))
        }

        Result.success(added)
    } catch (error: TrustWeaveError) {
        logger.error("Failed to add trust anchor", error)
        Result.failure(error)
    }
}

Wallet Management Workflow

Complete workflow for managing credentials in a wallet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
suspend fun walletManagementWorkflow(
    trustLayer: TrustLayer,
    holderDid: String
): Result<Wallet> {
    return try {
        // 1. Create or get wallet
        import com.trustweave.trust.types.WalletCreationResult
        import com.trustweave.trust.types.IssuanceResult
        
        val walletResult = trustLayer.wallet {
            holder(holderDid)
            enableOrganization()
            enablePresentation()
        }
        
        val wallet = when (walletResult) {
            is WalletCreationResult.Success -> walletResult.wallet
            else -> {
                return Result.failure(IllegalStateException("Failed to create wallet: ${walletResult.reason}"))
            }
        }

        // 2. Store credential
        val issuanceResult = trustLayer.issue {
            credential {
                type("VerifiableCredential", "PersonCredential")
                issuer("did:key:issuer")
                subject {
                    id(holderDid)
                    "name" to "Alice"
                }
            }
            signedBy(issuerDid = "did:key:issuer", keyId = "did:key:issuer#key-1")
        }
        
        val credential = when (issuanceResult) {
            is IssuanceResult.Success -> issuanceResult.credential
            else -> {
                return Result.failure(IllegalStateException("Failed to issue credential: ${issuanceResult.reason}"))
            }
        }

        val credentialId = wallet.store(credential)
        logger.info("Credential stored", mapOf(
            "credentialId" to credentialId,
            "holderDid" to holderDid
        ))

        // 3. Retrieve credential
        val retrieved = wallet.get(credentialId)
        if (retrieved != null) {
            logger.info("Credential retrieved", mapOf(
                "credentialId" to credentialId
            ))
        }

        // 4. List all credentials
        val allCredentials = wallet.list()
        logger.info("Wallet contains ${allCredentials.size} credentials")

        Result.success(wallet)
    } catch (error: TrustWeaveError) {
        logger.error("Wallet management failed", error)
        Result.failure(error)
    }
}

Batch Operations Workflow

Complete workflow for batch operations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll

suspend fun batchIssuanceWorkflow(
    trustLayer: TrustLayer,
    requests: List<CredentialRequest>
): Result<List<VerifiableCredential>> {
    return try {
        // Issue credentials concurrently
        import com.trustweave.trust.types.IssuanceResult
        
        val issuanceResults = requests.map { request ->
            async {
                trustLayer.issue {
                    credential {
                        type("VerifiableCredential", request.type)
                        issuer(request.issuerDid)
                        subject {
                            id(request.holderDid)
                            request.claims.forEach { (key, value) ->
                                key to value
                            }
                        }
                    }
                    signedBy(issuerDid = request.issuerDid, keyId = request.keyId)
                }
            }
        }.awaitAll()
        
        val credentials = issuanceResults.mapNotNull { result ->
            when (result) {
                is IssuanceResult.Success -> result.credential
                else -> {
                    logger.warn("Failed to issue credential: ${result.reason}")
                    null
                }
            }
        }

        logger.info("Batch issuance completed", mapOf(
            "count" to credentials.size
        ))

        Result.success(credentials)
    } catch (error: TrustWeaveError) {
        logger.error("Batch issuance failed", error)
        Result.failure(error)
    }
}

data class CredentialRequest(
    val type: String,
    val issuerDid: String,
    val holderDid: String,
    val keyId: String,
    val claims: Map<String, Any>
)