-
Notifications
You must be signed in to change notification settings - Fork 24
/
PublicCredential.chain.ts
285 lines (258 loc) · 8.86 KB
/
PublicCredential.chain.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* Copyright (c) 2018-2023, BOTLabs GmbH.
*
* This source code is licensed under the BSD 4-Clause "Original" license
* found in the LICENSE file in the root directory of this source tree.
*/
import type {
AssetDidUri,
CTypeHash,
IDelegationNode,
IPublicCredentialInput,
IPublicCredential,
DidUri,
HexString,
} from '@kiltprotocol/types'
import type { ApiPromise } from '@polkadot/api'
import type { GenericCall, Option } from '@polkadot/types'
import type { Call } from '@polkadot/types/interfaces'
import type { BN } from '@polkadot/util'
import type {
PublicCredentialsCredentialsCredential,
PublicCredentialsCredentialsCredentialEntry,
} from '@kiltprotocol/augment-api'
import { ConfigService } from '@kiltprotocol/config'
import { fromChain as didFromChain } from '@kiltprotocol/did'
import { validateUri } from '@kiltprotocol/asset-did'
import { SDKErrors, cbor } from '@kiltprotocol/utils'
import { getIdForCredential } from './PublicCredential.js'
import {
type DidAuthorizationCall,
flattenCalls,
isBatch,
retrieveExtrinsicFromBlock,
} from '../utils.js'
export interface EncodedPublicCredential {
ctypeHash: CTypeHash
subject: AssetDidUri
claims: HexString
authorization: IDelegationNode['id'] | null
}
/**
* Format a [[IPublicCredentialInput]] to be used as a parameter for the blockchain API function.
* @param publicCredential The public credential to format.
* @returns The blockchain-formatted public credential.
*/
export function toChain(
publicCredential: IPublicCredentialInput
): EncodedPublicCredential {
const { cTypeHash, claims, subject, delegationId } = publicCredential
const cborSerializedClaims = cbor.encode(claims)
return {
ctypeHash: cTypeHash,
subject,
claims: `0x${cborSerializedClaims.toString('hex')}`,
authorization: delegationId,
}
}
// Transform a blockchain-formatted public credential [[PublicCredentialsCredentialsCredential]] into the original [[IPublicCredentialInput]].
// It throws if what was written on the chain was garbage.
function credentialInputFromChain({
claims,
ctypeHash,
authorization,
subject,
}: PublicCredentialsCredentialsCredential): IPublicCredentialInput {
const credentialSubject = subject.toUtf8()
validateUri(credentialSubject)
return {
claims: cbor.decode(claims),
cTypeHash: ctypeHash.toHex(),
delegationId: authorization.unwrapOr(undefined)?.toHex() ?? null,
subject: credentialSubject as AssetDidUri,
}
}
/**
* The details of a public credential that are stored on chain.
*/
export interface PublicCredentialEntry {
/**
* CType hash of the public credential.
*/
ctypeHash: HexString
/**
* DID URI of the attester.
*/
attester: DidUri
/**
* Flag indicating whether the credential is currently revoked.
*/
revoked: boolean
/**
* Issuance block number of the credential.
*/
blockNumber: BN
/**
* Authorization information used by the attester when issuing the credential.
*/
authorizationId: IDelegationNode['id'] | null
}
/**
* Decodes the public credential details returned by `api.query.publicCredentials.credentials(subjectId)`.
*
* @param encoded The data from the blockchain.
* @returns The decoded data.
*/
export function fromChain(
encoded: Option<PublicCredentialsCredentialsCredentialEntry>
): PublicCredentialEntry {
const { attester, authorizationId, blockNumber, ctypeHash, revoked } =
encoded.unwrap()
return {
ctypeHash: ctypeHash.toHex(),
attester: didFromChain(attester),
revoked: revoked.toPrimitive(),
authorizationId: authorizationId.isSome
? authorizationId.unwrap().toHex()
: null,
blockNumber: blockNumber.toBn(),
}
}
// Given a (nested) call, flattens them and filter by calls that are of type `api.tx.publicCredentials.add`.
function extractPublicCredentialCreationCallsFromDidCall(
api: ApiPromise,
call: Call
): Array<GenericCall<typeof api.tx.publicCredentials.add.args>> {
const extrinsicCalls = flattenCalls(api, call)
return extrinsicCalls.filter(
(c): c is GenericCall<typeof api.tx.publicCredentials.add.args> =>
api.tx.publicCredentials.add.is(c)
)
}
// Given a (nested) call, flattens them and filter by calls that are of type `api.tx.did.submitDidCall` or `api.tx.did.dispatchAs`.
function extractDidCallsFromBatchCall(
api: ApiPromise,
call: Call
): DidAuthorizationCall[] {
const extrinsicCalls = flattenCalls(api, call)
return extrinsicCalls.filter(
(c): c is DidAuthorizationCall =>
api.tx.did.submitDidCall.is(c) || api.tx.did.dispatchAs.is(c)
)
}
/**
* Retrieves from the blockchain the [[IPublicCredential]] that is identified by the provided identifier.
*
* This is the **only** secure way for users to retrieve and verify a credential.
*
* @param credentialId Credential ID to use for the query.
* @returns The [[IPublicCredential]] as the result of combining the on-chain information and the information present in the tx history.
*/
export async function fetchCredentialFromChain(
credentialId: IPublicCredential['id']
): Promise<IPublicCredential> {
const api = ConfigService.get('api')
const publicCredentialEntry = await api.call.publicCredentials.getById(
credentialId
)
const { blockNumber, revoked } = publicCredentialEntry.unwrap()
const extrinsic = await retrieveExtrinsicFromBlock(
api,
blockNumber,
({ events }) =>
events.some(
(event) =>
api.events.publicCredentials.CredentialStored.is(event) &&
event.data[1].toString() === credentialId
)
)
if (extrinsic === null) {
throw new SDKErrors.PublicCredentialError(
`The block number as specified in the provided credential entry (${blockNumber}) does not have any extrinsic that includes a credential creation.`
)
}
if (
!isBatch(api, extrinsic) &&
!api.tx.did.submitDidCall.is(extrinsic) &&
!api.tx.did.dispatchAs.is(extrinsic)
) {
throw new SDKErrors.PublicCredentialError(
'Extrinsic should be either a `did.submitDidCall` or `did.dispatchAs` extrinsic or a batch containing at least one of those'
)
}
// If we're dealing with a batch, flatten any nested `submit_did_call` calls,
// otherwise the extrinsic is itself a submit_did_call, so just take it.
const didCalls = isBatch(api, extrinsic)
? extrinsic.args[0].flatMap((batchCall) =>
extractDidCallsFromBatchCall(api, batchCall)
)
: [extrinsic]
// From the list of DID calls, only consider public_credentials::add calls, bundling each of them with their DID submitter.
// It returns a list of [reconstructedCredential, attesterDid].
const callCredentialsContent = didCalls.flatMap((didCall) => {
const publicCredentialCalls =
extractPublicCredentialCreationCallsFromDidCall(
api,
api.tx.did.submitDidCall.is(didCall)
? didCall.args[0].call
: didCall.args[1]
)
// Re-create the issued public credential for each call identified.
return publicCredentialCalls.map(
(credentialCreationCall) =>
[
credentialInputFromChain(credentialCreationCall.args[0]),
didFromChain(
api.tx.did.submitDidCall.is(didCall)
? didCall.args[0].did
: didCall.args[0]
),
] as const
)
})
// If more than one call is present, it always considers the last one as the valid one, and takes its attester.
const lastRightCredentialCreationCall = callCredentialsContent
.reverse()
.find(([credential, attester]) => {
const reconstructedId = getIdForCredential(credential, attester)
return reconstructedId === credentialId
})
if (!lastRightCredentialCreationCall) {
throw new SDKErrors.PublicCredentialError(
'Block should always contain the full credential, eventually.'
)
}
const [credentialInput, attester] = lastRightCredentialCreationCall
return {
...credentialInput,
attester,
id: getIdForCredential(credentialInput, attester),
blockNumber,
revoked: revoked.toPrimitive(),
}
}
/**
* Retrieves from the blockchain the [[IPublicCredential]]s that have been issued to the provided AssetDID.
*
* This is the **only** secure way for users to retrieve and verify all the credentials issued to a given [[AssetDidUri]].
*
* @param subject The AssetDID of the subject.
* @returns An array of [[IPublicCredential]] as the result of combining the on-chain information and the information present in the tx history.
*/
export async function fetchCredentialsFromChain(
subject: AssetDidUri
): Promise<IPublicCredential[]> {
const api = ConfigService.get('api')
const publicCredentialEntries = await api.call.publicCredentials.getBySubject(
subject,
null
)
if (publicCredentialEntries.isErr) {
throw new Error(publicCredentialEntries.asErr.toString())
}
return Promise.all(
publicCredentialEntries.asOk.map(([encodedId]) =>
fetchCredentialFromChain(encodedId.toHex())
)
)
}