-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverify.ts
82 lines (69 loc) · 2.39 KB
/
verify.ts
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import type { ApiPromise } from '@polkadot/api'
import { config as envConfig } from 'dotenv'
import * as Kilt from '@kiltprotocol/sdk-js'
import { createPresentation } from './claimer/createPresentation'
import { generateKeypairs } from './claimer/generateKeypairs'
import { generateLightDid } from './claimer/generateLightDid'
function getChallenge(): string {
return Kilt.Utils.UUID.generate()
}
// Verifies validity, ownership & attestation.
async function verifyPresentation(
api: ApiPromise,
presentation: Kilt.ICredentialPresentation,
challenge: string
): Promise<boolean> {
try {
await Kilt.Credential.verifyPresentation(presentation, { challenge})
const attestationInfo = Kilt.Attestation.fromChain(
await api.query.attestation.attestations(presentation.rootHash),
presentation.rootHash
)
return !attestationInfo.revoked
} catch {
return false
}
}
export async function verificationFlow(
credential: Kilt.ICredential,
signCallback: Kilt.SignCallback
) {
const api = Kilt.ConfigService.get('api')
// Verifier sends a unique challenge to the claimer 🕊
const challenge = getChallenge()
// Create a presentation and send it to the verifier 🕊
const presentation = await createPresentation(
credential,
signCallback,
challenge
)
// The verifier checks the presentation.
const isValid = await verifyPresentation(api, presentation, challenge)
if (isValid) {
console.log('Verification successful! You are allowed to enter the club 🎉')
} else {
console.log('Verification failed! 🚫')
}
}
// Don't execute if this is imported by another file.
if (require.main === module) {
;(async () => {
envConfig()
try {
await Kilt.connect(process.env.WSS_ADDRESS as string)
const claimerDidMnemonic = process.env.CLAIMER_DID_MNEMONIC as string
const { authentication } = generateKeypairs(claimerDidMnemonic)
const claimerDid = generateLightDid(claimerDidMnemonic)
// Load credential and claimer DID
const credential = JSON.parse(process.env.CLAIMER_CREDENTIAL as string)
await verificationFlow(credential, async ({ data }) => ({
signature: authentication.sign(data),
keyType: authentication.type,
keyUri: `${claimerDid.uri}${claimerDid.authentication[0].id}`
}))
} catch (e) {
console.log('Error in the verification flow')
throw e
}
})()
}