-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathverification-controller.ts
More file actions
268 lines (228 loc) · 6.86 KB
/
Copy pathverification-controller.ts
File metadata and controls
268 lines (228 loc) · 6.86 KB
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
import {getJSON} from './helpers';
import {pexService} from '@docknetwork/wallet-sdk-wasm/src/services/pex';
import {credentialServiceRPC} from '@docknetwork/wallet-sdk-wasm/src/services/credential';
import {
createCredentialProvider,
ICredentialProvider,
} from './credential-provider';
import {IWallet} from './types';
import {EventEmitter} from 'events';
import axios from 'axios';
import assert from 'assert';
import {createDIDProvider, IDIDProvider} from './did-provider';
export enum VerificationStatus {
Started = 'Started',
LoadingTemplate = 'LoadingTemplate',
Filtering = 'Filtering',
FetchingProvingKey = 'FetchingProvingKey',
Error = 'Error',
NoCredentialsInTheWallet = 'NoCredentialsInTheWallet',
SelectingCredentials = 'SelectingCredentials',
}
function isRangeProofTemplate(templateJSON) {
return templateJSON.proving_key;
}
type CredentialId = string;
type CredentialSelection = {
credential: any;
attributesToReveal?: string[];
};
type CredentialSelectionMap = Map<CredentialId, CredentialSelection>;
export function createVerificationController({
wallet,
credentialProvider,
didProvider,
}: {
wallet: IWallet;
credentialProvider?: ICredentialProvider;
didProvider?: IDIDProvider;
}) {
const emitter = new EventEmitter();
let templateJSON = null;
let status = VerificationStatus.Started;
/**
* Extra data to give better context to the current state
* Can be used to show error messages, or more specific information about the state
*/
let statusData = null;
let filteredCredentials = [];
let selectedCredentials: CredentialSelectionMap = new Map();
let selectedDID = null;
let provingKey = null;
if (!credentialProvider) {
credentialProvider = createCredentialProvider({wallet});
}
if (!didProvider) {
didProvider = createDIDProvider({wallet});
}
async function fetchProvingKey(templateJSON: any) {
if (templateJSON.proving_key) {
setState(VerificationStatus.FetchingProvingKey);
try {
provingKey = await axios
.get(templateJSON.proving_key)
.then(res => res.data);
} catch (err) {
setState(VerificationStatus.Error, {
message: 'failed_to_fetch_proving_key',
});
throw err;
}
}
}
async function start({template}: {template: string | any}) {
setState(VerificationStatus.LoadingTemplate);
// check for dids
const dids = await didProvider.getAll();
if (!dids.length) {
setState(VerificationStatus.Error, {
message: 'no_dids_in_the_wallet',
});
throw new Error('No DIDs in the wallet');
}
// the application needs to verify if there are more DIDs available, and allow the user to change this selection before creating a presentation
selectedDID = dids[0].didDocument.id;
templateJSON = await getJSON(template);
await fetchProvingKey(templateJSON);
await loadCredentials();
setState(VerificationStatus.SelectingCredentials);
}
function setState(_status: VerificationStatus, data?: any) {
status = _status;
statusData = data;
emitter.emit(_status, data);
}
async function loadCredentials() {
setState(VerificationStatus.Filtering);
// get wallet credentials and apply pex filter
const allCredentials = await credentialProvider.getCredentials();
if (!allCredentials.length) {
setState(VerificationStatus.NoCredentialsInTheWallet);
return;
}
try {
const result = await pexService.filterCredentials({
credentials: allCredentials,
presentationDefinition: getPresentationDefinition(),
holderDIDs: [],
});
filteredCredentials = result.verifiableCredential;
} catch (err) {
console.error(
`Unable to filter credentials using the template: \n ${JSON.stringify(
templateJSON,
null,
2,
)}`,
);
console.error(err);
setState(VerificationStatus.Error);
throw err;
}
}
function getPresentationDefinition() {
return templateJSON.request;
}
async function isBBSPlusCredential(credential) {
return credentialServiceRPC.isBBSPlusCredential({credential});
}
async function isKvacCredential(credential) {
return credentialServiceRPC.isKvacCredential({credential});
}
async function createPresentation() {
assert(!!selectedDID, 'No DID selected');
assert(!!selectedCredentials.size, 'No credentials selected');
if (isRangeProofTemplate(templateJSON)) {
// TODO: Implement proving key usage for range-proofs
assert(!!provingKey, 'No proving key found');
}
const didKeyPairList = await didProvider.getDIDKeyPairs();
const keyDoc = didKeyPairList.find(doc => doc.controller === selectedDID);
assert(keyDoc, `No key pair found for the selected DID ${selectedDID}`);
const credentials = [];
const attributesToReveal = [];
const witnesses = [];
for (const credentialSelection of selectedCredentials.values()) {
credentials.push(credentialSelection.credential);
attributesToReveal.push([
...(credentialSelection.attributesToReveal || []),
'id',
]);
witnesses.push(
await credentialProvider.getMembershipWitness(
credentialSelection.credential.id,
),
);
}
const presentation = await credentialServiceRPC.createPresentation({
credentials,
attributesToReveal,
witnesses,
challenge: templateJSON.nonce,
keyDoc,
id: keyDoc.controller.startsWith('did:key:')
? keyDoc.id
: `${keyDoc.controller}#keys-1`,
domain: 'dock.io',
pexForBounds: templateJSON,
});
return presentation;
}
/**
* Filtered credentials
*/
function getFilteredCredentials() {
return filteredCredentials;
}
function getStatus() {
return status;
}
function getStatusData() {
return statusData;
}
function setSelectedDID(did: string) {
selectedDID = did;
}
/**
* Use pex to evaluate presentation
*
* @param presentation
*/
function evaluatePresentation(presentation) {
const definition = getPresentationDefinition();
const result = credentialServiceRPC.evaluatePresentation({
presentation,
presentationDefinition: definition,
});
return {
isValid: result.errors.length === 0,
errors: result.errors,
warnings: result.warnings,
};
}
function submitPresentation(presentation) {
return axios
.post(templateJSON.response_url, presentation)
.then(res => res.data);
}
return {
emitter,
selectedCredentials,
getStatus,
getStatusData,
submitPresentation,
getSelectedDID() {
return selectedDID;
},
setSelectedDID,
start,
isBBSPlusCredential,
loadCredentials,
getFilteredCredentials,
createPresentation,
evaluatePresentation,
getTemplateJSON() {
return templateJSON;
},
};
}