/
verifications.ts
2710 lines (2514 loc) · 105 KB
/
verifications.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2018-present evan GmbH.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see http://www.gnu.org/licenses/ or
write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from
the following URL: https://evan.network/license/
*/
import { BigNumber } from 'bignumber.js';
import {
AccountStore,
ContractLoader,
Executor,
Logger,
LoggerOptions,
NameResolver,
DfsInterface,
} from '@evan.network/dbcp';
import {
nullAddress,
nullBytes32,
} from '../common/utils';
import {
Description,
Ipfs,
SignerIdentity,
} from '../index';
import { Vc, VcDocumentTemplate, VcDocument } from '../vc/vc';
import { Did } from '../did/did';
import { IdentityKeyPurpose } from '../identity/identity';
import { Vade } from '../../libs/vade';
import crypto = require('crypto');
import prottle = require('prottle');
/**
* verification status from blockchain
*/
export enum VerificationsStatus {
/** issued by a non-issuer parent verification holder, self issued state is 0 */
Issued,
/** issued by a non-issuer parent verification holder, self issued state is 0 */
Confirmed,
/** verification rejected status */
Rejected,
}
/**
* status annotations about verification, depending on defined ``VerificationsQueryOptions``,
* this may lead to the verification to be invalid or less trustworthy
*/
export enum VerificationsStatusFlagsV2 {
/** parent verification does not allow subverifications */
disableSubVerifications = 'disableSubVerifications',
/** verification has expired */
expired = 'expired',
/** signature does not match requirements, this could be because it hasn’t been signed
* by correct account or underlying checksum does not match subject, topic and data */
invalid = 'invalid',
/** verification has been issued, but not accepted or rejected by subject */
issued = 'issued',
/** verification has not been issued */
missing = 'missing',
/** given subject has no identity */
noIdentity = 'noIdentity',
/** verification path has a trusted root verification topic, but this verification is not signed
* by a trusted instance */
notEnsRootOwner = 'notEnsRootOwner',
/** parent verification is missing in path */
parentMissing = 'parentMissing',
/** verification path cannot be traced back to a trusted root verification */
parentUntrusted = 'parentUntrusted',
/** verification has been issued and then rejected by subject */
rejected = 'rejected',
/** verification issuer is the same as the subject */
selfIssued = 'selfIssued',
}
/**
* represents the status of a requested verification topic
* after applying rules in ``VerificationsQueryOptions``
*/
export enum VerificationsStatusV2 {
/** verification is valid according to ``VerificationsQueryOptions`` */
Green = 'green',
/** verification may be valid but more checks may be required more for trusting it,
* see status flags for details */
Yellow = 'yellow',
/** verification is invalid, see status flags for details */
Red = 'red',
}
/**
* additional configuration for verifications module
*/
export interface VerificationsConfig {
/** identity used for transactions */
activeIdentity: string;
/** account, that pays for transactions */
underlyingAccount: string;
}
/**
* information for submitting a delegated transaction,
* created with ``signSetVerificationTransaction`` consumed by ``executeVerification``
*/
export interface VerificationsDelegationInfo {
/** address of identity contract, that issues verification */
sourceIdentity: string;
/** value to transfer, usually 0 */
value: number;
/** abi encoded input for transaction */
input: string;
/** signed data from transaction */
signedTransactionInfo?: string;
/** source identity contract execution nonce for this transaction */
nonce?: string;
/** address of identity contract, that receives verification;
* either this or `to` has to be given */
targetIdentity?: string;
/** address of target of transaction, either this or `targetIdentity` has to be given */
to?: string;
}
/**
* options for ``getNestedVerificationsV2``, define how to calculate status of verification
*/
export interface VerificationsQueryOptions {
/** specification of how to handle status flags of each single verification */
validationOptions?: VerificationsValidationOptions;
/** function for setting verification with custom logic */
statusComputer?: VerificationsStatusComputer;
}
/**
* result of a verification query
*/
export interface VerificationsResultV2 {
/** overall status of verification */
status: VerificationsStatusV2;
/** list of verifications on same topic and subject */
verifications?: VerificationsVerificationEntry[];
/** consolidated information about verification */
levelComputed?: {
/** identity contract address or hash of subject */
subjectIdentity: string;
/** type of subject (account/contract) */
subjectType: string;
/** topic (name) of verification */
topic: string;
/** js timestamp */
expirationDate?: number;
/** verifications of parent path, issued for all issuers of verifications on this level */
parents?: VerificationsResultV2;
/** subject accountId/contractId (if query was issued with ``isIdentity`` set to ``false``) */
subject?: string;
};
}
/**
* a single verification; usually used in ``VerificationsResultV2``
*/
export interface VerificationsVerificationEntry {
/** details about verification */
details: {
/** js timestamp of verification creation */
creationDate: number;
/** ens address of description for this verification */
ensAddress: string;
/** expiration date of verification (js timestamp) */
expirationDate?: number;
/** id in verification holder / verifications registry */
id: string;
/** account id of verification issuer */
issuer: string;
/** issuers identity contract id */
issuerIdentity: string;
/** identity (contract or identity hash) of subject */
subjectIdentity: string;
/** type of subject (account/contract) */
subjectType: string;
/** topic of identity (name) */
topic: string;
/** 32B data hash string of identity */
data?: any;
/** only if actually set */
description?: any;
/** if applicable, reason for verification rejection */
rejectReason?: string;
/** status of verification, is optional during result computation and required when done */
status?: VerificationsStatusV2;
/** subject accountId/contractId (if query was issued with ``isIdentity`` set to ``false``) */
subject?: string;
};
/** raw data about verification from contract */
raw?: {
/** block in which verification was issued */
creationBlock: string;
/** unix timestamp is s when verification was issued */
creationDate: string;
/** 32B data hash string of identity, bytes32 zero if unset */
data: string;
/** true if subverification are not allowed */
disableSubVerifications: boolean;
/** signature over verification data */
signature: string;
/** status of verification, (issued, accepted, rejected, etc.) */
status: number;
/** uint string of verification name (topic), is uint representation of sha3 of name */
topic: string;
};
/** all found flags, those may not have impact on statusm
* depends on ``VerificationsStatusFlagsV2`` */
statusFlags?: string[];
}
/**
* Computes status for a single verification. verification, partialResult
*
* @param {Partial<VerificationsVerificationEntry>} verification current verification result
* (without status)
* @param {Partial<VerificationsResultV2>} partialResult options for verifications
* query
* @return {Promise<VerificationsStatusV2>} status for this verification
*/
export interface VerificationsVerificationEntryStatusComputer {
(
verification: Partial<VerificationsVerificationEntry>,
partialResult: Partial<VerificationsResultV2>,
): Promise<VerificationsStatusV2>;
}
/**
* Computes status from overall verifications result.
* This function is applied after each verification has received an own computed status.
*
* @param {Partial<VerificationsResultV2>} partialResult current verification result
* (without status)
* @param {VerificationsQueryOptions} queryOptions options for verifications query
* @param {VerificationsStatusV2} currentStatus current status of verification
* @return {Promise<VerificationsStatusV2>} updated status, will be used at verification status
*/
export interface VerificationsStatusComputer {
(
partialResult: Partial<VerificationsResultV2>,
queryOptions: VerificationsQueryOptions,
currentStatus: VerificationsStatusV2,
): Promise<VerificationsStatusV2>;
}
/**
* Options for verification status computation. Keys are string representations of
* ``VerificationsStatusFlagsV2``, values can be ``VerificationsStatusV2`` or functions.
* If value is ``VerificationsStatusV2``, then finding given status flag sets verification value
* to given ``VerificationsStatusV2`` (if not already at a higher trust level).
* If value is function, pass verification to this function and set verification status to
* return value (if not already at a higher trust level).
*/
export interface VerificationsValidationOptions {
[id: string]: VerificationsStatusV2 | VerificationsVerificationEntryStatusComputer;
}
/**
* options for Verification constructor, basically a trimmed runtime
*/
export interface VerificationsOptions extends LoggerOptions {
accountStore: AccountStore;
config: any;
contractLoader: ContractLoader;
description: Description;
dfs: DfsInterface;
executor: Executor;
nameResolver: NameResolver;
did?: Did;
registry?: string;
signerIdentity?: SignerIdentity;
storage?: string;
vade?: Vade;
vc?: Vc;
}
/**
* Verifications helper
*
* @class Verifications (name)
*/
export class Verifications extends Logger {
public readonly defaultValidationOptions: VerificationsValidationOptions = {
disableSubVerifications: VerificationsStatusV2.Red,
expired: VerificationsStatusV2.Red,
invalid: VerificationsStatusV2.Red,
issued: VerificationsStatusV2.Red,
missing: VerificationsStatusV2.Red,
noIdentity: VerificationsStatusV2.Red,
notEnsRootOwner: VerificationsStatusV2.Red,
parentMissing: VerificationsStatusV2.Red,
parentUntrusted: VerificationsStatusV2.Red,
rejected: VerificationsStatusV2.Red,
selfIssued: VerificationsStatusV2.Red,
};
public readonly defaultQueryOptions: VerificationsQueryOptions = {
validationOptions: this.defaultValidationOptions,
};
public cachedAccountIdentities: any = { };
public cachedIdentities: any = { };
public config: VerificationsConfig;
public contracts: any = { };
public encodingEnvelope = 'utf8';
/** cache all the ens owners */
public ensOwners: any = { };
public options: VerificationsOptions;
/** check if currently the storage is ensuring, if yes, don't run it twice */
public storageEnsuring: Promise<any>;
public subjectTypes: any = { };
/** cache all the verifications using an object of promises, to be sure, that the verification is
* loaded only once */
public verificationCache: any = { };
/** backup already loaded verification descriptions */
public verificationDescriptions: any = { };
/**
* Creates a new Verifications instance.
*
* Note, that the option properties ``registry`` and ``resolver`` are optional but should be
* provided in most cases. As the module allows to create an own ENS structure, that includes an
* own ENS registry and an own default resolver for it, setting them beforehand is optional.
*
* @param {VerificationsOptions} options
*/
public constructor(options: VerificationsOptions, config?: VerificationsConfig) {
super(options);
this.updateConfig(options, config);
}
/**
* Takes an array of verifications and combines all the states for one quick view.
*
* {
* verifications: verifications,
* creationDate: null,
* displayName: topic.split('/').pop() || 'evan',
* loading: verifications.filter(verification => verification.loading).length > 0,
* name: topic,
* status: -1,
* subjects: [ ],
* warnings: [ ], // have a look at getNestedVerifications
* }
*
* @param {string} topic topic of all the verifications
* @param {Array<any>} verifications all verifications of a specific topic
* @return {any} computed verification including latest creationDate, combined color,
* displayName
*/
public async computeVerifications(topic: string, verifications: any[]) {
const computed: any = {
creationDate: null,
disableSubVerifications: verifications.filter(
(verification) => verification.disableSubVerifications,
).length > 0,
displayName: topic.split('/').pop() || 'evan',
loading: verifications.filter((verification) => verification.loading).length > 0,
name: topic,
status: -1,
subjects: [],
verifications,
warnings: [],
};
// load the description for the given topic
await this.ensureVerificationDescription(computed);
// keep creationDates of all verifications, so we can check after the final combined status was
// set, which creation date should be used
const creationDates = {
'-1': [], 0: [], 1: [], 2: [],
};
const expirationDates = {
'-1': [], 0: [], 1: [], 2: [],
};
// iterate through all verifications and check for warnings and the latest creation date of an
// verification
for (const verification of verifications) {
// concatenate all warnings
computed.warnings = computed.warnings.concat(verification.warnings);
// use the highest status (-1 missing, 0 issued, 1 valid, 2 rejected)
if (verification.status === 2) {
if (computed.status === -1) {
computed.status = 2;
}
} else if (computed.status === 2) {
computed.status = verification.status;
} else {
computed.status = computed.status < verification.status
? verification.status : computed.status;
}
// search one subject of all
if (computed.subjects.indexOf(verification.subject) === -1) {
computed.subjects.push(verification.subject);
}
// save all creation dates for later usage
if (typeof verification.creationDate !== 'undefined') {
creationDates[verification.status].push(verification.creationDate);
}
// save all creation dates for later usage
if (typeof verification.expirationDate !== 'undefined') {
expirationDates[verification.status].push(verification.expirationDate);
}
}
// use the latest creationDate for the specific status
if (creationDates[computed.status].length > 0) {
[computed.creationDate] = creationDates[computed.status].sort();
}
// use the latest creationDate for the specific status
if (expirationDates[computed.status].length > 0) {
const curExpiration = expirationDates[computed.status].sort();
computed.expirationDate = curExpiration[curExpiration.length - 1];
}
return computed;
}
/**
* confirms a verification; this can be done, if a verification has been issued for a subject and
* the subject wants to confirm it
*
* @param {string} confirmer identity or account to confirm the verification
* @param {string} subject verification subject
* @param {string} verificationId id of a verification to confirm
* @param {boolean} isIdentity (optional): ``true`` if given ``subject`` is an
* identity, defaults to ``false``
* @return {Promise<void>} resolved when done
*/
public async confirmVerification(
confirmer: string,
subject: string,
verificationId: string,
isIdentity = false,
): Promise<void> {
if (this.options.vade && subject.length === 66) {
throw new Error('alias/contract DIDs on substrate currently do not support VCs');
}
await this.executeOnIdentity(
subject,
isIdentity,
'approveVerification',
{ from: confirmer },
verificationId,
);
// clear cache for this verification
this.deleteFromVerificationCache(subject, '/');
}
/**
* Creates a new identity for account or contract and registers them on the storage. Returned
* identity is either a 20B contract address (for account identities) or a 32B identity hash
* contract identities
*
* @param {string} creator identity or account that runs transaction, receiver of
* identity when omitting the other arguments
* @param {string} contractId (optional) contract address to create the identity
* for, creates identity for ``creator`` if omitted
* @param {bool} updateDescription (optional) update description of contract, defaults to
* ``true``
* @param {bool} linkContract link contract address to its identity
* @return {Promise<string>} new identity (20Bytes for accounts, 32Bytes for other)
*/
public async createIdentity(
creator: string,
contractId?: string,
updateDescription = true,
linkContract = true,
): Promise<string> {
await this.ensureStorage();
let identity;
// create account ids, if no contract id given and if this identity should not be linked
if (!contractId && linkContract) {
// create Identity contract
const identityContract = await this.options.executor.createContract(
'VerificationHolder', [creator], { from: creator, gas: 3000000 },
);
const identityStorage = this.contracts.storage.options.address !== nullAddress
? this.options.contractLoader.loadContract(
'V00_UserRegistry', this.contracts.storage.options.address,
)
: null;
// register the new user in the registry
await this.options.executor.executeContractTransaction(
identityStorage,
'registerUser',
{ from: creator },
identityContract.options.address,
);
identity = identityContract.options.address;
} else {
if (this.options.vade) {
identity = (await this.options.vade.didCreate(
'did:evan:testcore',
JSON.stringify({
privateKey: await this.options.accountStore.getPrivateKey(
this.options.signerIdentity.underlyingAccount,
),
identity: await this.options.did.convertIdentityToDid(this.config.activeIdentity),
}),
'',
)).replace(/^.*0x/, '0x');
} else if (creator === this.config.activeIdentity) {
identity = await this.options.executor.executeContractTransaction(
this.contracts.registry,
'createIdentity',
{
event: { eventName: 'IdentityCreated', target: 'VerificationsRegistry' },
from: creator,
getEventResult: (_, args) => args.identity,
},
);
} else {
identity = await this.executeAndHandleEventResult(
creator,
this.contracts.registry.methods.createIdentity().encodeABI(),
{ contract: this.contracts.registry, eventName: 'IdentityCreated' },
(_, args) => args.identity,
);
}
// write identity to description
if (updateDescription) {
const description = await this.options.description.getDescription(contractId, creator);
description.public.identity = identity;
// update to dbcpVersion 2 if 1 is selected, to support the new identity property
if (!description.public.dbcpVersion || description.public.dbcpVersion === 1) {
description.public.dbcpVersion = 2;
}
await this.options.description.setDescriptionToContract(contractId, description, creator);
}
// link contract address to its identity in global registry?
if (linkContract && !this.options.vade) {
const link = `0x${contractId.substr(2).toLowerCase().padStart(64, '0')}`;
if (creator === this.config.activeIdentity) {
await this.options.executor.executeContractTransaction(
this.contracts.registry,
'linkIdentity',
{ from: creator },
identity,
link,
);
} else {
await this.executeAndHandleEventResult(
creator,
this.contracts.registry.methods.linkIdentity(identity, link).encodeABI(),
);
}
}
}
// clear cache for this account
this.deleteFromVerificationCache(creator, '/');
return identity;
}
/**
* Delete a single entry from the verification cache object using subject and topic
*
* @param {string} subject the subject that should be removed
* @param {string} topic the topic that should be removed
* @return {void}
*/
public deleteFromVerificationCache(subject: string, topic: string) {
// prepend starting slash if it does not exists
if (topic.indexOf('/') !== 0) {
// eslint-disable-next-line no-param-reassign
topic = `/${topic}`;
}
// search for all parents, that could have links to the topic, so remove them
Object.keys(this.verificationCache).forEach((key) => {
// if the key is equal to the topic that should be checked, delete only the cache for the
// given subject
if (key === topic) {
// delete all related subjects for the given topic, or remove all, when subject is a
// wildcard
if (this.verificationCache[topic]
&& (this.verificationCache[topic][subject] || subject === '*')) {
delete this.verificationCache[topic][subject];
}
// else remove all child topics
} else if (key.indexOf(topic) !== -1) {
delete this.verificationCache[key];
}
});
}
/**
* delete a verification. This requires the accountId to have permissions for the parent
* verification (if verification name seen as a path, the parent 'folder'). Subjects of a
* verification may only delete it, if they are the issuer as well. If not, they can only react to
* it by confirming or rejecting the verification.
*
* @param {string} deletor identity or account deleting the verification
* @param {string} subject the subject of the verification
* @param {string} verificationId id of a verification to delete
* @param {boolean} isIdentity (optional): ``true`` if given ``subject`` is an
* identity, defaults to ``false``
* @return {Promise<void>} resolved when done
*/
public async deleteVerification(
deletor: string,
subject: string,
verificationId: string,
isIdentity = false,
): Promise<void> {
if (this.options.vade && subject.length === 66) {
throw new Error('alias/contract DIDs on substrate currently do not support VCs');
}
await this.executeOnIdentity(
subject,
isIdentity,
'removeVerification',
{ from: deletor },
verificationId,
);
// clear cache for this verification
this.deleteFromVerificationCache(subject, '/');
}
/**
* Gets and sets the default description for a verification if it does not exist.
*
* @param {any} verification the verification that should be checked
*/
public async ensureVerificationDescription(verification: any) {
// map the topic to the verification ens name and extract the top level verifications domain
// to check, if the user can set the verification tree
const fullDomain = this.getVerificationEnsAddress(verification.name);
const topLevelDomain = fullDomain.replace('.verifications.evan', '').split('.').reverse()[0];
const ensAddress = this.getFullDescriptionDomainWithHash(verification.name, topLevelDomain);
// if no description was set, use the latest one or load it
if (!verification.description) {
// if the description could not be loaded, the cache will set to false, so we do not need to
// load again
if (!this.verificationDescriptions[ensAddress]
&& this.verificationDescriptions[ensAddress] !== false) {
this.verificationDescriptions[ensAddress] = (async () => {
try {
// load the description
return await this.options.description.getDescriptionFromEns(ensAddress);
} catch (ex) {
return false;
}
})();
}
// eslint-disable-next-line no-param-reassign
verification.description = await this.verificationDescriptions[ensAddress];
}
if (verification.description) {
// map the properties to a flat description
if (verification.description.public) {
// eslint-disable-next-line no-param-reassign
verification.description = verification.description.public;
}
// move the img to the basic verification
if (verification.description.imgSquare) {
// eslint-disable-next-line no-param-reassign
verification.icon = verification.description.imgSquare;
}
} else {
// eslint-disable-next-line no-param-reassign
verification.description = {
author: nullAddress,
dbcpVersion: 1,
description: verification.name,
name: verification.name,
version: '1.0.0',
};
}
// eslint-disable-next-line no-param-reassign
verification.description.i18n = verification.description.i18n || { };
// eslint-disable-next-line no-param-reassign
verification.description.i18n.name = verification.description.i18n.name || { };
// eslint-disable-next-line no-param-reassign
verification.description.i18n.name.en = verification.description.i18n.name.en || verification.name.split('/').pop();
// try to load a clear name
try {
// eslint-disable-next-line no-param-reassign
verification.displayName = verification.description.i18n.name.en;
} catch (ex) {
this.log(ex, 'debug');
}
// if the top level ens owner was not loaded before, load it!
if (!this.ensOwners[topLevelDomain]) {
this.ensOwners[topLevelDomain] = (async () => {
// transform the ens domain into a namehash and load the ens top level topic owner
const namehash = this.options.nameResolver.namehash(`${topLevelDomain}.verifications.evan`);
return this.options.executor.executeContractCall(
this.options.nameResolver.ensContract, 'owner', namehash,
);
})();
}
// eslint-disable-next-line no-param-reassign
verification.ensAddress = ensAddress;
// eslint-disable-next-line no-param-reassign
verification.topLevelEnsOwner = await this.ensOwners[topLevelDomain];
}
/**
* run given data (serialized contract transaction (tx)) with given users identity
*
* @param {string} accountId account with whose identity the given tx is
* executed
* @param {string} data serialized function data
* @param {any} eventInfo (optional) object with properties: 'eventName' and
* 'contract' (web3 contract instance, that triggers
* event)
* @param {Function} getEventResults (optional) function with arguments event and
* eventArgs, that returns result of
* `executeAndHandleEventResult` call
* @return {Promise<any>} if `eventInfo` and `getEventResults`, result of `getEventResults`,
* otherwise void
*/
// eslint-disable-next-line consistent-return
public async executeAndHandleEventResult(
accountId: string,
data: string,
eventInfo?: any,
getEventResults?: Function,
sourceIdentity?: string,
value = 0,
to?: string,
signedTransactionInfo?: string,
): Promise<any> {
// get users identity
const userIdentity = sourceIdentity
? this.options.contractLoader.loadContract('VerificationHolder', sourceIdentity)
: await this.getIdentityForAccount(accountId);
const logData = {
accountId, userIdentity: userIdentity.options.address, to, data, sourceIdentity,
};
this.log(`submitting identity tx ${JSON.stringify(logData)}"`, 'debug');
// when signing with account, check if given accountId is allowed to perform tx on identity
if (!signedTransactionInfo) {
const sha3AccountId = this.options.nameResolver.soliditySha3(accountId);
const version = await this.options.executor.executeContractCall(userIdentity, 'VERSION_ID');
let hasPurpose;
if (version === null) {
hasPurpose = await this.options.executor.executeContractCall(
userIdentity,
'keyHasPurpose',
sha3AccountId,
IdentityKeyPurpose.Management,
);
} else if (version.eq('1')) {
hasPurpose = await this.options.executor.executeContractCall(
userIdentity,
'keyHasPurpose',
sha3AccountId,
IdentityKeyPurpose.Action,
);
} else {
throw new Error(`invalid identity version: ${version}`);
}
if (!hasPurpose) {
throw new Error(`account "${accountId}" is not allowed to perform transactions on identity `
+ `"${userIdentity.options.address}"`);
}
}
// convert bigNumbers to numbers
let sendingValue = value;
if ((sendingValue as any).toNumber) {
sendingValue = (sendingValue as any).toNumber();
}
// prepare success + result event handling
const options = {
event: { eventName: 'Approved', target: 'KeyHolderLibrary' },
from: accountId,
getEventResult: (event, eventArgs) => [eventArgs.executionId, event.blockNumber],
value: sendingValue,
};
// run tx
const { executor } = this.options;
const [executionId, blockNumber] = await (executor.executeContractTransaction as any)(...[
userIdentity,
signedTransactionInfo ? 'executeDelegated' : 'execute',
options,
to || this.contracts.registry.options.address,
sendingValue,
data,
].concat(signedTransactionInfo ? [signedTransactionInfo] : []));
// fetch result from event
// load user identity as a library, to retrieve library events from users identity
const keyHolderLibrary = this.options.contractLoader.loadContract(
'KeyHolderLibrary', userIdentity.options.address,
);
const [executed, failed] = await Promise.all([
keyHolderLibrary.getPastEvents(
'Executed', { fromBlock: blockNumber, toBlock: blockNumber },
),
keyHolderLibrary.getPastEvents(
'ExecutionFailed', { fromBlock: blockNumber, toBlock: blockNumber },
),
]);
// flatten and filter events on execution id from identity tx
const filtered = [...executed, ...failed].filter(
(event) => {
if (event.returnValues && event.returnValues.executionId) {
// check if executionId is a BigNumber object
if (event.returnValues.executionId.eq) {
return event.returnValues.executionId.eq(executionId);
}
// otherwise check normal equality
return event.returnValues.executionId === executionId;
}
return false;
},
);
if (filtered.length && filtered[0].event === 'Executed') {
// if execution was successful
if (eventInfo) {
// if original options had an event property for retrieving event results
let targetIdentityEvents = await eventInfo.contract.getPastEvents(
eventInfo.eventName, { fromBlock: blockNumber, toBlock: blockNumber },
);
targetIdentityEvents = targetIdentityEvents.filter(
(event) => event.transactionHash === filtered[0].transactionHash,
);
if (targetIdentityEvents.length) {
return getEventResults(targetIdentityEvents[0], targetIdentityEvents[0].returnValues);
}
}
} else if (filtered.length && filtered[0].event === 'ExecutionFailed') {
const values = filtered[0].returnValues;
throw new Error('executeOnIdentity failed; ExecutionFailed event was triggered: '
+ `executionId: "${values.executionId}", to: "${values.to}", value: "${values.value}"`);
} else {
throw new Error('executeOnIdentity failed; subject type was \'account\', '
+ 'but no proper identity tx status event could be retrieved');
}
}
/**
* Executes a pre-signed transaction from from ``signTransaction`` of an identity. This can be and
* usually is a transaction, that has been prepared by the identity owner and is now submitted to
* the chain and executed by another account.
*
* @param {string} executorAddress identity or account, that sends
* transaction to the blockchain and
* pays for it
* @param {VerificationsDelegationInfo} txInfo details about the transaction
* @param {<type>} event The event
* @param {Function} getEventResult The get event result
* @param {any} partialOptions (optional) data for handling event
* triggered by this transaction
*/
public async executeTransaction(
executorAddress: string,
txInfo: VerificationsDelegationInfo,
{ event = null, getEventResult = null }: { event?: any; getEventResult?: Function } = {},
): Promise<any> {
const {
sourceIdentity,
to,
value,
input,
signedTransactionInfo,
targetIdentity,
} = txInfo;
const transactionTarget = to || (targetIdentity.length === 42
? targetIdentity // target identity contract given
: this.contracts.registry.options.address); // contract/pseudonym identity given
return this.executeAndHandleEventResult(
executorAddress,
input,
event,
getEventResult,
sourceIdentity,
value,
transactionTarget,
signedTransactionInfo,
);
}
/**
* Executes a pre-signed verification transaction with given account.
* This account will be the origin of the transaction and not of the verification.
* Second argument is generated with ``signSetVerificationTransaction``.
*
* @param {string} executorAddress identity or account, that submits
* the transaction
* @param {VerificationsDelegationInfo} txInfo information with verification tx data
* @return {Promise<string>} id of new verification
*/
public async executeVerification(
executorAddress: string,
txInfo: VerificationsDelegationInfo,
): Promise<any> {
return this.executeTransaction(
executorAddress,
txInfo,
{
event: {
target: 'VerificationHolderLibrary',
targetAddress: txInfo.targetIdentity,
eventName: 'VerificationAdded',
contract: this.options.contractLoader.loadContract(
'VerificationHolderLibrary', txInfo.targetIdentity,
),
},
getEventResult: (_, args) => args.verificationId,
},
);
}
/**
* Loads a list of verifications for a topic and a subject and combines to a single view for a
* simple verification status check.
*
* @param {string} subject subject, that performs the description loading
* @param {string} topic topic of all the verifications
* @param {boolean} isIdentity optional indicates if the subject is already a identity
* @return {any} computed verification including latest creationDate, combined color,
* displayName
*/
public async getComputedVerification(subject: string, topic: string, isIdentity?: boolean) {
return this.computeVerifications(
topic,
await this.getNestedVerifications(subject, topic, isIdentity),
);
}
/**
* Gets current execution nonce for an identity or an accounts identity.
*
* @param {string} issuer identity or account to get execution nonce for
* @param {boolean} isIdentity optional, true if given issuer is an identity, defaults to
* ``false``
* @return {Promise<string>} execution nonce
*/
public async getExecutionNonce(issuer: string, isIdentity = false): Promise<string> {
await this.ensureStorage();
const identity = isIdentity ? issuer : await this.getIdentityForAccount(issuer, true);
const identityContract = this.options.contractLoader.loadContract(
'VerificationHolder', identity,
);
return this.options.executor.executeContractCall(identityContract, 'getExecutionNonce');
}
/**