@cheqd/did-provider-cheqd 4.1.2-develop.2 → 4.2.0-develop.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/build/cjs/agent/ICheqd.d.ts +1 -1
  2. package/build/cjs/agent/ICheqd.d.ts.map +1 -1
  3. package/build/cjs/agent/ICheqd.js +52 -52
  4. package/build/cjs/agent/ICheqd.js.map +1 -1
  5. package/build/cjs/did-manager/cheqd-did-provider.d.ts +1 -1
  6. package/build/cjs/did-manager/cheqd-did-provider.js +5 -5
  7. package/build/cjs/did-manager/cheqd-did-provider.js.map +1 -1
  8. package/build/cjs/dkg-threshold/index.d.ts +1 -1
  9. package/build/cjs/dkg-threshold/index.js +1 -1
  10. package/build/cjs/dkg-threshold/lit-protocol/v3.d.ts +8 -8
  11. package/build/cjs/dkg-threshold/lit-protocol/v3.d.ts.map +1 -1
  12. package/build/cjs/dkg-threshold/lit-protocol/v3.js +18 -18
  13. package/build/cjs/dkg-threshold/lit-protocol/v3.js.map +1 -1
  14. package/build/cjs/dkg-threshold/lit-protocol/v6.d.ts +86 -0
  15. package/build/cjs/dkg-threshold/lit-protocol/v6.d.ts.map +1 -0
  16. package/build/cjs/dkg-threshold/lit-protocol/v6.js +230 -0
  17. package/build/cjs/dkg-threshold/lit-protocol/v6.js.map +1 -0
  18. package/build/esm/agent/ICheqd.d.ts +1 -1
  19. package/build/esm/agent/ICheqd.d.ts.map +1 -1
  20. package/build/esm/agent/ICheqd.js +1 -1
  21. package/build/esm/agent/ICheqd.js.map +1 -1
  22. package/build/esm/did-manager/cheqd-did-provider.d.ts +1 -1
  23. package/build/esm/did-manager/cheqd-did-provider.js +3 -3
  24. package/build/esm/did-manager/cheqd-did-provider.js.map +1 -1
  25. package/build/esm/dkg-threshold/index.d.ts +1 -1
  26. package/build/esm/dkg-threshold/index.js +1 -1
  27. package/build/esm/dkg-threshold/lit-protocol/v3.d.ts +8 -8
  28. package/build/esm/dkg-threshold/lit-protocol/v3.d.ts.map +1 -1
  29. package/build/esm/dkg-threshold/lit-protocol/v3.js +15 -15
  30. package/build/esm/dkg-threshold/lit-protocol/v3.js.map +1 -1
  31. package/build/esm/dkg-threshold/lit-protocol/v6.d.ts +86 -0
  32. package/build/esm/dkg-threshold/lit-protocol/v6.d.ts.map +1 -0
  33. package/build/esm/dkg-threshold/lit-protocol/v6.js +226 -0
  34. package/build/esm/dkg-threshold/lit-protocol/v6.js.map +1 -0
  35. package/build/tsconfig.cjs.tsbuildinfo +1 -1
  36. package/build/tsconfig.esm.tsbuildinfo +1 -1
  37. package/build/tsconfig.types.tsbuildinfo +1 -1
  38. package/build/types/agent/ICheqd.d.ts +1 -1
  39. package/build/types/agent/ICheqd.d.ts.map +1 -1
  40. package/build/types/did-manager/cheqd-did-provider.d.ts +1 -1
  41. package/build/types/dkg-threshold/index.d.ts +1 -1
  42. package/build/types/dkg-threshold/lit-protocol/v3.d.ts +8 -8
  43. package/build/types/dkg-threshold/lit-protocol/v3.d.ts.map +1 -1
  44. package/build/types/dkg-threshold/lit-protocol/v6.d.ts +86 -0
  45. package/build/types/dkg-threshold/lit-protocol/v6.d.ts.map +1 -0
  46. package/package.json +5 -3
  47. package/src/agent/ICheqd.ts +1 -4
  48. package/src/did-manager/cheqd-did-provider.ts +3 -3
  49. package/src/dkg-threshold/index.ts +1 -1
  50. package/src/dkg-threshold/lit-protocol/v3.ts +20 -20
  51. package/src/dkg-threshold/lit-protocol/v6.ts +348 -0
@@ -0,0 +1,348 @@
1
+ import { OfflineAminoSigner, Secp256k1HdWallet, StdSignDoc } from '@cosmjs/amino';
2
+ import { toString } from 'uint8arrays/to-string';
3
+ import { sha256 } from '@cosmjs/crypto';
4
+ import { LitNodeClientNodeJs, LitNodeClient } from '@lit-protocol/lit-node-client';
5
+ import {
6
+ AccsCOSMOSParams,
7
+ ConditionType,
8
+ DecryptResponse,
9
+ EncryptResponse,
10
+ UnifiedAccessControlConditions,
11
+ } from '@lit-protocol/types';
12
+ import { generateSymmetricKey, randomBytes } from '../../utils/helpers.js';
13
+ import { isBrowser, isNode } from '../../utils/env.js';
14
+ import { v4 } from 'uuid';
15
+ import { fromString } from 'uint8arrays';
16
+ import { LitProtocolDebugEnabled } from '../../utils/constants.js';
17
+
18
+ export type ThresholdEncryptionResult = {
19
+ encryptedString: Uint8Array;
20
+ stringHash: string;
21
+ };
22
+ export type SymmetricEncryptionResult = {
23
+ encryptedString: Blob;
24
+ stringHash: string;
25
+ symmetricKey: Uint8Array;
26
+ };
27
+ export type AuthSignature = {
28
+ sig: string;
29
+ derivedVia: 'cosmos.signArbitrary';
30
+ signedMessage: string;
31
+ address: string;
32
+ };
33
+ export type CosmosAuthSignature = {
34
+ cosmos: AuthSignature;
35
+ };
36
+ export type CosmosAccessControlCondition = AccsCOSMOSParams & {
37
+ conditionType: ConditionType;
38
+ }
39
+ export type CosmosReturnValueTest = CosmosAccessControlCondition['returnValueTest'];
40
+ export type SaveEncryptionKeyArgs = {
41
+ unifiedAccessControlConditions: CosmosAccessControlCondition[];
42
+ symmetricKey: CryptoKey;
43
+ authSig: CosmosAuthSignature;
44
+ chain: string;
45
+ };
46
+ export type GetEncryptionKeyArgs = {
47
+ unifiedAccessControlConditions: CosmosAccessControlCondition[];
48
+ toDecrypt: string;
49
+ authSig: CosmosAuthSignature;
50
+ chain: string;
51
+ };
52
+ export type EncryptStringMethodResult = EncryptResponse;
53
+ export type DecryptToStringMethodResult = DecryptResponse;
54
+ export type EncryptStringMethod = (str: string) => Promise<EncryptStringMethodResult>;
55
+ export type DecryptToStringMethod = (
56
+ encryptedString: Blob,
57
+ symmetricKey: Uint8Array
58
+ ) => Promise<DecryptToStringMethodResult>;
59
+ export type LitNetwork = (typeof LitNetworks)[keyof typeof LitNetworks];
60
+ export type LitCompatibleCosmosChain = (typeof LitCompatibleCosmosChains)[keyof typeof LitCompatibleCosmosChains];
61
+ export type LitProtocolOptions = {
62
+ cosmosAuthWallet: Secp256k1HdWallet;
63
+ litNetwork?: LitNetwork;
64
+ chain?: LitCompatibleCosmosChain;
65
+ };
66
+ export type TxNonceFormat = (typeof TxNonceFormats)[keyof typeof TxNonceFormats];
67
+
68
+ export const LitNetworks = {
69
+ datildev: 'datil-dev',
70
+ localhost: 'localhost',
71
+ custom: 'custom',
72
+ } as const;
73
+ export const LitCompatibleCosmosChains = {
74
+ cosmos: 'cosmos',
75
+ cheqdMainnet: 'cheqdMainnet',
76
+ cheqdTestnet: 'cheqdTestnet',
77
+ } as const;
78
+ export const TxNonceFormats = { entropy: 'entropy', uuid: 'uuid', timestamp: 'timestamp' } as const;
79
+
80
+ export class LitProtocol {
81
+ client: LitNodeClientNodeJs | LitNodeClient;
82
+ litNetwork: LitNetwork = LitNetworks.datildev;
83
+ chain: LitCompatibleCosmosChain = LitCompatibleCosmosChains.cosmos;
84
+ private readonly cosmosAuthWallet: Secp256k1HdWallet;
85
+
86
+ private constructor(options: LitProtocolOptions) {
87
+ // validate options
88
+ if (options.litNetwork && !Object.values(LitNetworks).includes(options.litNetwork))
89
+ throw new Error(`[did-provider-cheqd]: lit-protocol: Invalid LitNetwork: ${options.litNetwork}`);
90
+ if (options.chain && !Object.values(LitCompatibleCosmosChains).includes(options.chain))
91
+ throw new Error(`[did-provider-cheqd]: lit-protocol: Invalid LitCompatibleCosmosChain: ${options.chain}`);
92
+
93
+ // set options
94
+ if (options.litNetwork) this.litNetwork = options.litNetwork;
95
+ if (options.chain) this.chain = options.chain;
96
+ this.cosmosAuthWallet = options.cosmosAuthWallet;
97
+
98
+ // set client as per environment
99
+ this.client = (function (that: LitProtocol) {
100
+ if (isNode) return new LitNodeClientNodeJs({ litNetwork: that.litNetwork, debug: LitProtocolDebugEnabled });
101
+ if (isBrowser) return new LitNodeClient({ litNetwork: that.litNetwork, debug: LitProtocolDebugEnabled });
102
+ throw new Error('[did-provider-cheqd]: lit-protocol: Unsupported runtime environment');
103
+ })(this);
104
+ }
105
+
106
+ async connect(): Promise<void> {
107
+ return await this.client.connect();
108
+ }
109
+
110
+ async encrypt(
111
+ secret: Uint8Array,
112
+ unifiedAccessControlConditions: NonNullable<UnifiedAccessControlConditions>
113
+ ): Promise<ThresholdEncryptionResult> {
114
+ // generate auth signature
115
+ const authSig = await LitProtocol.generateAuthSignature(this.cosmosAuthWallet);
116
+
117
+ // encrypt
118
+ const { ciphertext: encryptedString, dataToEncryptHash: stringHash } = (await this.client.encrypt({
119
+ dataToEncrypt: secret,
120
+ unifiedAccessControlConditions,
121
+ })) satisfies EncryptStringMethodResult;
122
+
123
+ return {
124
+ encryptedString: fromString(encryptedString, 'base64'),
125
+ stringHash,
126
+ };
127
+ }
128
+
129
+ async decrypt(
130
+ encryptedString: string,
131
+ stringHash: string,
132
+ unifiedAccessControlConditions: NonNullable<UnifiedAccessControlConditions>
133
+ ): Promise<string> {
134
+ // generate auth signature
135
+ const authSig = await LitProtocol.generateAuthSignature(this.cosmosAuthWallet);
136
+
137
+ // decrypt
138
+ const { decryptedData } = (await this.client.decrypt({
139
+ chain: this.chain,
140
+ ciphertext: encryptedString,
141
+ dataToEncryptHash: stringHash,
142
+ unifiedAccessControlConditions,
143
+ authSig,
144
+ })) satisfies DecryptToStringMethodResult;
145
+
146
+ return toString(decryptedData, 'utf-8');
147
+ }
148
+
149
+ static async encryptDirect(data: Uint8Array): Promise<SymmetricEncryptionResult> {
150
+ try {
151
+ // generate symmetric key
152
+ const symmetricKey = await generateSymmetricKey();
153
+
154
+ // generate iv
155
+ const iv = crypto.getRandomValues(new Uint8Array(12));
156
+
157
+ // encrypt
158
+ const encrypted = await crypto.subtle.encrypt(
159
+ {
160
+ name: 'AES-GCM',
161
+ iv,
162
+ },
163
+ symmetricKey,
164
+ data
165
+ );
166
+
167
+ // export symmetric key
168
+ const exportedSymmetricKey = await crypto.subtle.exportKey('raw', symmetricKey);
169
+
170
+ return {
171
+ encryptedString: new Blob([iv, new Uint8Array(encrypted)]),
172
+ stringHash: toString(new Uint8Array(await crypto.subtle.digest('SHA-256', data)), 'hex'),
173
+ symmetricKey: new Uint8Array(exportedSymmetricKey),
174
+ } satisfies SymmetricEncryptionResult;
175
+ } catch (error) {
176
+ // standardize error
177
+ throw new Error(
178
+ `[did-provider-cheqd]: symmetric-encryption: Encryption failed: ${(error as Error).message || error}`
179
+ );
180
+ }
181
+ }
182
+
183
+ static async decryptDirect(encryptedString: Blob, symmetricKey: Uint8Array): Promise<Uint8Array> {
184
+ try {
185
+ // import symmetric key
186
+ const importedSymmetricKey = await crypto.subtle.importKey(
187
+ 'raw',
188
+ symmetricKey,
189
+ {
190
+ name: 'AES-GCM',
191
+ },
192
+ true,
193
+ ['encrypt', 'decrypt']
194
+ );
195
+
196
+ // extract iv and encrypted data
197
+ const [iv, encryptedData] = await Promise.all([
198
+ encryptedString.slice(0, 12).arrayBuffer(),
199
+ encryptedString.slice(12).arrayBuffer(),
200
+ ]);
201
+
202
+ // decrypt
203
+ const decrypted = await crypto.subtle.decrypt(
204
+ {
205
+ name: 'AES-GCM',
206
+ iv: new Uint8Array(iv),
207
+ },
208
+ importedSymmetricKey,
209
+ encryptedData
210
+ );
211
+
212
+ return new Uint8Array(decrypted);
213
+ } catch (error) {
214
+ // standardize error
215
+ throw new Error(
216
+ `[did-provider-cheqd]: symmetric-decryption: Decryption failed: ${(error as Error).message || error}`
217
+ );
218
+ }
219
+ }
220
+
221
+ static async create(options: Partial<LitProtocolOptions>): Promise<LitProtocol> {
222
+ // instantiate underlying cosmos auth wallet
223
+ if (!options.cosmosAuthWallet)
224
+ options.cosmosAuthWallet = await Secp256k1HdWallet.generate(24, {
225
+ prefix: await LitProtocol.getCosmosWalletPrefix(options?.chain),
226
+ });
227
+
228
+ // validate top-level options chain
229
+ if (!options?.chain) options.chain = LitCompatibleCosmosChains.cheqdTestnet;
230
+
231
+ // validate top-level options litNetwork
232
+ if (!options?.litNetwork) options.litNetwork = LitNetworks.datildev;
233
+
234
+ const litProtocol = new LitProtocol(options as LitProtocolOptions);
235
+ await litProtocol.connect();
236
+ return litProtocol;
237
+ }
238
+
239
+ static async getCosmosWalletPrefix(chain?: LitCompatibleCosmosChain): Promise<string> {
240
+ switch (chain) {
241
+ case LitCompatibleCosmosChains.cosmos:
242
+ return 'cosmos';
243
+ case LitCompatibleCosmosChains.cheqdMainnet:
244
+ return 'cheqd';
245
+ case LitCompatibleCosmosChains.cheqdTestnet:
246
+ return 'cheqd';
247
+ default:
248
+ return 'cheqd';
249
+ }
250
+ }
251
+
252
+ static async generateAuthSignature(wallet: OfflineAminoSigner): Promise<AuthSignature> {
253
+ const signerAddress = (await wallet.getAccounts())[0].address;
254
+ const signData = await LitProtocol.generateSignData();
255
+ const signDoc = await LitProtocol.generateSignDoc(signerAddress, signData);
256
+ const result = await wallet.signAmino(signerAddress, signDoc);
257
+ return {
258
+ address: signerAddress,
259
+ derivedVia: 'cosmos.signArbitrary',
260
+ sig: result.signature.signature,
261
+ signedMessage: toString(sha256(new TextEncoder().encode(JSON.stringify(signDoc))), 'hex'), // <-- hex encoded sha256 hash of the json stringified signDoc
262
+ };
263
+ }
264
+
265
+ static async generateSignDoc(address: string, data: Uint8Array): Promise<StdSignDoc> {
266
+ return {
267
+ account_number: '0',
268
+ chain_id: '',
269
+ fee: {
270
+ amount: [],
271
+ gas: '0',
272
+ },
273
+ memo: '',
274
+ msgs: [
275
+ {
276
+ type: 'sign/MsgSignData',
277
+ value: {
278
+ data: toString(data, 'base64'),
279
+ signer: address,
280
+ },
281
+ },
282
+ ],
283
+ sequence: '0',
284
+ }; // <-- should be sorted alphabetically
285
+ }
286
+
287
+ static async generateSignData(): Promise<Uint8Array> {
288
+ return new TextEncoder().encode(`I am creating an account to use Lit Protocol at 2023-02-21T16:40:15.305Z`); // <-- lit nodes search for this string in the signData
289
+ }
290
+
291
+ static async generateTxNonce(format?: TxNonceFormat, entropyLength?: number): Promise<string> {
292
+ switch (format) {
293
+ case TxNonceFormats.entropy:
294
+ return toString(await randomBytes(entropyLength || 64), 'hex');
295
+ case TxNonceFormats.uuid:
296
+ return v4();
297
+ case TxNonceFormats.timestamp:
298
+ return new Date().toISOString();
299
+ default:
300
+ return v4();
301
+ }
302
+ }
303
+
304
+ static async generateCosmosAccessControlConditionBalance(
305
+ returnValueTest: CosmosReturnValueTest,
306
+ chain: LitCompatibleCosmosChain = LitCompatibleCosmosChains.cheqdTestnet,
307
+ address = ':userAddress'
308
+ ): Promise<CosmosAccessControlCondition> {
309
+ return {
310
+ conditionType: 'cosmos',
311
+ path: `/cosmos/bank/v1beta1/balances/${address}`,
312
+ chain,
313
+ returnValueTest,
314
+ };
315
+ }
316
+
317
+ static async generateCosmosAccessControlConditionTransactionMemo(
318
+ returnValueTest: CosmosReturnValueTest,
319
+ amount: string,
320
+ sender: string,
321
+ recipient = ':userAddress',
322
+ chain: LitCompatibleCosmosChain = LitCompatibleCosmosChains.cheqdTestnet
323
+ ): Promise<CosmosAccessControlCondition> {
324
+ return {
325
+ conditionType: 'cosmos',
326
+ path: `/cosmos/tx/v1beta1/txs?events=transfer.recipient='${recipient}'&events=transfer.sender='${sender}'&events=transfer.amount='${amount}'&order_by=2`,
327
+ chain,
328
+ returnValueTest,
329
+ };
330
+ }
331
+
332
+ static async generateCosmosAccessControlConditionInverseTimelock(
333
+ returnValueTest: CosmosReturnValueTest,
334
+ amount: string,
335
+ recipient = ':userAddress',
336
+ blockHeight = 'latest',
337
+ chain: LitCompatibleCosmosChain = LitCompatibleCosmosChains.cheqdTestnet
338
+ ): Promise<CosmosAccessControlCondition> {
339
+ return {
340
+ conditionType: 'cosmos',
341
+ path: `/cosmos/tx/v1beta1/txs?events=transfer.recipient='${recipient}'&events=transfer.amount='${amount}'&order_by=2&pagination.limit=1`,
342
+ chain,
343
+ method: 'timelock',
344
+ parameters: [blockHeight],
345
+ returnValueTest,
346
+ };
347
+ }
348
+ }