@mysten/seal 0.4.9 → 0.4.11
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.
- package/CHANGELOG.md +19 -0
- package/dist/cjs/bcs.d.ts +14 -4
- package/dist/cjs/bcs.js +10 -3
- package/dist/cjs/bcs.js.map +2 -2
- package/dist/cjs/client.js +4 -0
- package/dist/cjs/client.js.map +2 -2
- package/dist/cjs/key-server.js +23 -17
- package/dist/cjs/key-server.js.map +2 -2
- package/dist/cjs/session-key.d.ts +13 -3
- package/dist/cjs/session-key.js +22 -0
- package/dist/cjs/session-key.js.map +2 -2
- package/dist/cjs/types.d.ts +4 -2
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/version.js.map +1 -1
- package/dist/esm/bcs.d.ts +14 -4
- package/dist/esm/bcs.js +10 -3
- package/dist/esm/bcs.js.map +2 -2
- package/dist/esm/client.js +5 -0
- package/dist/esm/client.js.map +2 -2
- package/dist/esm/key-server.js +26 -26
- package/dist/esm/key-server.js.map +2 -2
- package/dist/esm/session-key.d.ts +13 -3
- package/dist/esm/session-key.js +23 -0
- package/dist/esm/session-key.js.map +2 -2
- package/dist/esm/types.d.ts +4 -2
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/dist/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @mysten/seal
|
|
2
2
|
|
|
3
|
+
## 0.4.11
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c15d220: Use versioned key server objects
|
|
8
|
+
- Updated dependencies [1ff4e57]
|
|
9
|
+
- Updated dependencies [550e2e3]
|
|
10
|
+
- Updated dependencies [550e2e3]
|
|
11
|
+
- @mysten/sui@1.31.0
|
|
12
|
+
|
|
13
|
+
## 0.4.10
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- 5bd6ca3: Accept SealCompatibleClient for SealClient and SessionKey
|
|
18
|
+
- 5bd6ca3: fix(seal): throw error early if package is not first version
|
|
19
|
+
- Updated dependencies [5bd6ca3]
|
|
20
|
+
- @mysten/sui@1.30.5
|
|
21
|
+
|
|
3
22
|
## 0.4.9
|
|
4
23
|
|
|
5
24
|
### Patch Changes
|
package/dist/cjs/bcs.d.ts
CHANGED
|
@@ -113,16 +113,14 @@ export declare const EncryptedObject: import("@mysten/bcs").BcsType<{
|
|
|
113
113
|
}>;
|
|
114
114
|
}>;
|
|
115
115
|
/**
|
|
116
|
-
* The Move struct for the
|
|
116
|
+
* The Move struct for the KeyServerV1 object.
|
|
117
117
|
*/
|
|
118
|
-
export declare const
|
|
119
|
-
id: string;
|
|
118
|
+
export declare const KeyServerMoveV1: import("@mysten/bcs").BcsType<{
|
|
120
119
|
name: string;
|
|
121
120
|
url: string;
|
|
122
121
|
keyType: number;
|
|
123
122
|
pk: number[];
|
|
124
123
|
}, {
|
|
125
|
-
id: string | Uint8Array<ArrayBufferLike>;
|
|
126
124
|
name: string;
|
|
127
125
|
url: string;
|
|
128
126
|
keyType: number;
|
|
@@ -130,3 +128,15 @@ export declare const KeyServerMove: import("@mysten/bcs").BcsType<{
|
|
|
130
128
|
length: number;
|
|
131
129
|
};
|
|
132
130
|
}>;
|
|
131
|
+
/**
|
|
132
|
+
* The Move struct for the parent object.
|
|
133
|
+
*/
|
|
134
|
+
export declare const KeyServerMove: import("@mysten/bcs").BcsType<{
|
|
135
|
+
id: string;
|
|
136
|
+
firstVersion: string;
|
|
137
|
+
lastVersion: string;
|
|
138
|
+
}, {
|
|
139
|
+
id: string | Uint8Array<ArrayBufferLike>;
|
|
140
|
+
firstVersion: string | number | bigint;
|
|
141
|
+
lastVersion: string | number | bigint;
|
|
142
|
+
}>;
|
package/dist/cjs/bcs.js
CHANGED
|
@@ -21,7 +21,8 @@ __export(bcs_exports, {
|
|
|
21
21
|
Ciphertext: () => Ciphertext,
|
|
22
22
|
EncryptedObject: () => EncryptedObject,
|
|
23
23
|
IBEEncryptions: () => IBEEncryptions,
|
|
24
|
-
KeyServerMove: () => KeyServerMove
|
|
24
|
+
KeyServerMove: () => KeyServerMove,
|
|
25
|
+
KeyServerMoveV1: () => KeyServerMoveV1
|
|
25
26
|
});
|
|
26
27
|
module.exports = __toCommonJS(bcs_exports);
|
|
27
28
|
var import_bcs = require("@mysten/bcs");
|
|
@@ -57,11 +58,17 @@ const EncryptedObject = import_bcs2.bcs.struct("EncryptedObject", {
|
|
|
57
58
|
encryptedShares: IBEEncryptions,
|
|
58
59
|
ciphertext: Ciphertext
|
|
59
60
|
});
|
|
60
|
-
const
|
|
61
|
-
id: import_bcs2.bcs.Address,
|
|
61
|
+
const KeyServerMoveV1 = import_bcs2.bcs.struct("KeyServerV1", {
|
|
62
62
|
name: import_bcs2.bcs.string(),
|
|
63
63
|
url: import_bcs2.bcs.string(),
|
|
64
64
|
keyType: import_bcs2.bcs.u8(),
|
|
65
65
|
pk: import_bcs2.bcs.vector(import_bcs2.bcs.u8())
|
|
66
66
|
});
|
|
67
|
+
const KeyServerMove = import_bcs2.bcs.struct("KeyServer", {
|
|
68
|
+
id: import_bcs2.bcs.Address,
|
|
69
|
+
firstVersion: import_bcs2.bcs.u64(),
|
|
70
|
+
// latest version
|
|
71
|
+
lastVersion: import_bcs2.bcs.u64()
|
|
72
|
+
// oldest version
|
|
73
|
+
});
|
|
67
74
|
//# sourceMappingURL=bcs.js.map
|
package/dist/cjs/bcs.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/bcs.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex, toHex } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\n\nexport const IBEEncryptions = bcs.enum('IBEEncryptions', {\n\tBonehFranklinBLS12381: bcs.struct('BonehFranklinBLS12381', {\n\t\tnonce: bcs.bytes(96),\n\t\tencryptedShares: bcs.vector(bcs.bytes(32)),\n\t\tencryptedRandomness: bcs.bytes(32),\n\t}),\n});\n\nexport const Ciphertext = bcs.enum('Ciphertext', {\n\tAes256Gcm: bcs.struct('Aes256Gcm', {\n\t\tblob: bcs.vector(bcs.U8),\n\t\taad: bcs.option(bcs.vector(bcs.U8)),\n\t}),\n\tHmac256Ctr: bcs.struct('Hmac256Ctr', {\n\t\tblob: bcs.vector(bcs.U8),\n\t\taad: bcs.option(bcs.vector(bcs.U8)),\n\t\tmac: bcs.bytes(32),\n\t}),\n\tPlain: bcs.struct('Plain', {}),\n});\n\n/**\n * The encrypted object format. Should be aligned with the Rust implementation.\n */\nexport const EncryptedObject = bcs.struct('EncryptedObject', {\n\tversion: bcs.U8,\n\tpackageId: bcs.Address,\n\tid: bcs.vector(bcs.U8).transform({\n\t\toutput: (val) => toHex(new Uint8Array(val)),\n\t\tinput: (val: string) => fromHex(val),\n\t}),\n\tservices: bcs.vector(bcs.tuple([bcs.Address, bcs.U8])),\n\tthreshold: bcs.U8,\n\tencryptedShares: IBEEncryptions,\n\tciphertext: Ciphertext,\n});\n\n/**\n * The Move struct for the
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAA+B;AAC/B,IAAAA,cAAoB;AAEb,MAAM,iBAAiB,gBAAI,KAAK,kBAAkB;AAAA,EACxD,uBAAuB,gBAAI,OAAO,yBAAyB;AAAA,IAC1D,OAAO,gBAAI,MAAM,EAAE;AAAA,IACnB,iBAAiB,gBAAI,OAAO,gBAAI,MAAM,EAAE,CAAC;AAAA,IACzC,qBAAqB,gBAAI,MAAM,EAAE;AAAA,EAClC,CAAC;AACF,CAAC;AAEM,MAAM,aAAa,gBAAI,KAAK,cAAc;AAAA,EAChD,WAAW,gBAAI,OAAO,aAAa;AAAA,IAClC,MAAM,gBAAI,OAAO,gBAAI,EAAE;AAAA,IACvB,KAAK,gBAAI,OAAO,gBAAI,OAAO,gBAAI,EAAE,CAAC;AAAA,EACnC,CAAC;AAAA,EACD,YAAY,gBAAI,OAAO,cAAc;AAAA,IACpC,MAAM,gBAAI,OAAO,gBAAI,EAAE;AAAA,IACvB,KAAK,gBAAI,OAAO,gBAAI,OAAO,gBAAI,EAAE,CAAC;AAAA,IAClC,KAAK,gBAAI,MAAM,EAAE;AAAA,EAClB,CAAC;AAAA,EACD,OAAO,gBAAI,OAAO,SAAS,CAAC,CAAC;AAC9B,CAAC;AAKM,MAAM,kBAAkB,gBAAI,OAAO,mBAAmB;AAAA,EAC5D,SAAS,gBAAI;AAAA,EACb,WAAW,gBAAI;AAAA,EACf,IAAI,gBAAI,OAAO,gBAAI,EAAE,EAAE,UAAU;AAAA,IAChC,QAAQ,CAAC,YAAQ,kBAAM,IAAI,WAAW,GAAG,CAAC;AAAA,IAC1C,OAAO,CAAC,YAAgB,oBAAQ,GAAG;AAAA,EACpC,CAAC;AAAA,EACD,UAAU,gBAAI,OAAO,gBAAI,MAAM,CAAC,gBAAI,SAAS,gBAAI,EAAE,CAAC,CAAC;AAAA,EACrD,WAAW,gBAAI;AAAA,EACf,iBAAiB;AAAA,EACjB,YAAY;AACb,CAAC;AAKM,MAAM,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex, toHex } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\n\nexport const IBEEncryptions = bcs.enum('IBEEncryptions', {\n\tBonehFranklinBLS12381: bcs.struct('BonehFranklinBLS12381', {\n\t\tnonce: bcs.bytes(96),\n\t\tencryptedShares: bcs.vector(bcs.bytes(32)),\n\t\tencryptedRandomness: bcs.bytes(32),\n\t}),\n});\n\nexport const Ciphertext = bcs.enum('Ciphertext', {\n\tAes256Gcm: bcs.struct('Aes256Gcm', {\n\t\tblob: bcs.vector(bcs.U8),\n\t\taad: bcs.option(bcs.vector(bcs.U8)),\n\t}),\n\tHmac256Ctr: bcs.struct('Hmac256Ctr', {\n\t\tblob: bcs.vector(bcs.U8),\n\t\taad: bcs.option(bcs.vector(bcs.U8)),\n\t\tmac: bcs.bytes(32),\n\t}),\n\tPlain: bcs.struct('Plain', {}),\n});\n\n/**\n * The encrypted object format. Should be aligned with the Rust implementation.\n */\nexport const EncryptedObject = bcs.struct('EncryptedObject', {\n\tversion: bcs.U8,\n\tpackageId: bcs.Address,\n\tid: bcs.vector(bcs.U8).transform({\n\t\toutput: (val) => toHex(new Uint8Array(val)),\n\t\tinput: (val: string) => fromHex(val),\n\t}),\n\tservices: bcs.vector(bcs.tuple([bcs.Address, bcs.U8])),\n\tthreshold: bcs.U8,\n\tencryptedShares: IBEEncryptions,\n\tciphertext: Ciphertext,\n});\n\n/**\n * The Move struct for the KeyServerV1 object.\n */\nexport const KeyServerMoveV1 = bcs.struct('KeyServerV1', {\n\tname: bcs.string(),\n\turl: bcs.string(),\n\tkeyType: bcs.u8(),\n\tpk: bcs.vector(bcs.u8()),\n});\n\n/**\n * The Move struct for the parent object.\n */\nexport const KeyServerMove = bcs.struct('KeyServer', {\n\tid: bcs.Address,\n\tfirstVersion: bcs.u64(), // latest version\n\tlastVersion: bcs.u64(), // oldest version\n});\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAA+B;AAC/B,IAAAA,cAAoB;AAEb,MAAM,iBAAiB,gBAAI,KAAK,kBAAkB;AAAA,EACxD,uBAAuB,gBAAI,OAAO,yBAAyB;AAAA,IAC1D,OAAO,gBAAI,MAAM,EAAE;AAAA,IACnB,iBAAiB,gBAAI,OAAO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AAA,EACpD,IAAI,gBAAI;AAAA,EACR,cAAc,gBAAI,IAAI;AAAA;AAAA,EACtB,aAAa,gBAAI,IAAI;AAAA;AACtB,CAAC;",
|
|
6
6
|
"names": ["import_bcs"]
|
|
7
7
|
}
|
package/dist/cjs/client.js
CHANGED
|
@@ -98,6 +98,10 @@ const _SealClient = class _SealClient {
|
|
|
98
98
|
data,
|
|
99
99
|
aad = new Uint8Array()
|
|
100
100
|
}) {
|
|
101
|
+
const packageObj = await __privateGet(this, _suiClient).core.getObject({ objectId: packageId });
|
|
102
|
+
if (String(packageObj.object.version) !== "1") {
|
|
103
|
+
throw new import_error.InvalidPackageError(`Package ${packageId} is not the first version`);
|
|
104
|
+
}
|
|
101
105
|
return (0, import_encrypt.encrypt)({
|
|
102
106
|
keyServers: await __privateMethod(this, _SealClient_instances, getWeightedKeyServers_fn).call(this),
|
|
103
107
|
kemType,
|
package/dist/cjs/client.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { EncryptedObject } from './bcs.js';\nimport { G1Element, G2Element } from './bls12381.js';\nimport { decrypt } from './decrypt.js';\nimport type { EncryptionInput } from './dem.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { DemType, encrypt, KemType } from './encrypt.js';\nimport {\n\tInconsistentKeyServersError,\n\tInvalidClientOptionsError,\n\tInvalidKeyServerError,\n\tInvalidThresholdError,\n\ttoMajorityError,\n\tTooManyFailedFetchKeyRequestsError,\n} from './error.js';\nimport { BonehFranklinBLS12381Services } from './ibe.js';\nimport {\n\tBonehFranklinBLS12381DerivedKey,\n\tKeyServerType,\n\tretrieveKeyServers,\n\tverifyKeyServer,\n} from './key-server.js';\nimport type { DerivedKey, KeyServer } from './key-server.js';\nimport { fetchKeysForAllIds } from './keys.js';\nimport type { SessionKey } from './session-key.js';\nimport type { KeyCacheKey, SealCompatibleClient } from './types.js';\nimport { createFullId, count } from './utils.js';\n\n/**\n * Configuration options for initializing a SealClient\n * @property serverConfigs: Array of key server configs consisting of objectId, weight, optional API key name and API key.\n * @property verifyKeyServers: Whether to verify the key servers' authenticity.\n * \t Should be false if servers are pre-verified (e.g., getAllowlistedKeyServers).\n * \t Defaults to true.\n * @property timeout: Timeout in milliseconds for network requests. Defaults to 10 seconds.\n */\nexport interface SealClientExtensionOptions {\n\tserverConfigs: KeyServerConfig[];\n\tverifyKeyServers?: boolean;\n\ttimeout?: number;\n}\n\nexport interface KeyServerConfig {\n\tobjectId: string;\n\tweight: number;\n\tapiKeyName?: string;\n\tapiKey?: string;\n}\n\nexport interface SealClientOptions extends SealClientExtensionOptions {\n\tsuiClient: SealCompatibleClient;\n}\n\nexport class SealClient {\n\t#suiClient: SealCompatibleClient;\n\t#configs: Map<string, KeyServerConfig>;\n\t#keyServers: Promise<Map<string, KeyServer>> | null = null;\n\t#verifyKeyServers: boolean;\n\t// A caching map for: fullId:object_id -> partial key.\n\t#cachedKeys = new Map<KeyCacheKey, G1Element>();\n\t#timeout: number;\n\t#totalWeight: number;\n\n\tconstructor(options: SealClientOptions) {\n\t\tthis.#suiClient = options.suiClient;\n\n\t\tif (\n\t\t\tnew Set(options.serverConfigs.map((s) => s.objectId)).size !== options.serverConfigs.length\n\t\t) {\n\t\t\tthrow new InvalidClientOptionsError('Duplicate object IDs');\n\t\t}\n\n\t\tif (\n\t\t\toptions.serverConfigs.some((s) => (s.apiKeyName && !s.apiKey) || (!s.apiKeyName && s.apiKey))\n\t\t) {\n\t\t\tthrow new InvalidClientOptionsError(\n\t\t\t\t'Both apiKeyName and apiKey must be provided or not provided for all key servers',\n\t\t\t);\n\t\t}\n\n\t\tthis.#configs = new Map(options.serverConfigs.map((server) => [server.objectId, server]));\n\t\tthis.#totalWeight = options.serverConfigs\n\t\t\t.map((server) => server.weight)\n\t\t\t.reduce((sum, term) => sum + term, 0);\n\n\t\tthis.#verifyKeyServers = options.verifyKeyServers ?? true;\n\t\tthis.#timeout = options.timeout ?? 10_000;\n\t}\n\n\tstatic experimental_asClientExtension(options: SealClientExtensionOptions) {\n\t\treturn {\n\t\t\tname: 'seal' as const,\n\t\t\tregister: (client: SealCompatibleClient) => {\n\t\t\t\treturn new SealClient({\n\t\t\t\t\tsuiClient: client,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Return an encrypted message under the identity.\n\t *\n\t * @param kemType - The type of KEM to use.\n\t * @param demType - The type of DEM to use.\n\t * @param threshold - The threshold for the TSS encryption.\n\t * @param packageId - the packageId namespace.\n\t * @param id - the identity to use.\n\t * @param data - the data to encrypt.\n\t * @param aad - optional additional authenticated data.\n\t * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.\n\t * \tSince the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.\n\t */\n\tasync encrypt({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tdemType = DemType.AesGcm256,\n\t\tthreshold,\n\t\tpackageId,\n\t\tid,\n\t\tdata,\n\t\taad = new Uint8Array(),\n\t}: {\n\t\tkemType?: KemType;\n\t\tdemType?: DemType;\n\t\tthreshold: number;\n\t\tpackageId: string;\n\t\tid: string;\n\t\tdata: Uint8Array;\n\t\taad?: Uint8Array;\n\t}) {\n\t\t// TODO: Verify that packageId is first version of its package (else throw error).\n\t\treturn encrypt({\n\t\t\tkeyServers: await this.#getWeightedKeyServers(),\n\t\t\tkemType,\n\t\t\tthreshold,\n\t\t\tpackageId,\n\t\t\tid,\n\t\t\tencryptionInput: this.#createEncryptionInput(demType, data, aad),\n\t\t});\n\t}\n\n\t#createEncryptionInput(type: DemType, data: Uint8Array, aad: Uint8Array): EncryptionInput {\n\t\tswitch (type) {\n\t\t\tcase DemType.AesGcm256:\n\t\t\t\treturn new AesGcm256(data, aad);\n\t\t\tcase DemType.Hmac256Ctr:\n\t\t\t\treturn new Hmac256Ctr(data, aad);\n\t\t}\n\t}\n\n\t/**\n\t * Decrypt the given encrypted bytes using cached keys.\n\t * Calls fetchKeys in case one or more of the required keys is not cached yet.\n\t * The function throws an error if the client's key servers are not a subset of\n\t * the encrypted object's key servers or if the threshold cannot be met.\n\t *\n\t * @param data - The encrypted bytes to decrypt.\n\t * @param sessionKey - The session key to use.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt({\n\t\tdata,\n\t\tsessionKey,\n\t\ttxBytes,\n\t}: {\n\t\tdata: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\ttxBytes: Uint8Array;\n\t}) {\n\t\tconst encryptedObject = EncryptedObject.parse(data);\n\n\t\tthis.#validateEncryptionServices(\n\t\t\tencryptedObject.services.map((s) => s[0]),\n\t\t\tencryptedObject.threshold,\n\t\t);\n\n\t\tawait this.fetchKeys({\n\t\t\tids: [encryptedObject.id],\n\t\t\ttxBytes,\n\t\t\tsessionKey,\n\t\t\tthreshold: encryptedObject.threshold,\n\t\t});\n\n\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys });\n\t}\n\n\t#weight(objectId: string) {\n\t\treturn this.#configs.get(objectId)?.weight ?? 0;\n\t}\n\n\t#validateEncryptionServices(services: string[], threshold: number) {\n\t\t// Check that the client's key servers are a subset of the encrypted object's key servers.\n\t\tif (\n\t\t\tservices.some((objectId) => {\n\t\t\t\tconst countInClient = this.#weight(objectId);\n\t\t\t\treturn countInClient > 0 && countInClient !== count(services, objectId);\n\t\t\t})\n\t\t) {\n\t\t\tthrow new InconsistentKeyServersError(\n\t\t\t\t`Client's key servers must be a subset of the encrypted object's key servers`,\n\t\t\t);\n\t\t}\n\t\t// Check that the threshold can be met with the client's key servers.\n\t\tif (threshold > this.#totalWeight) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${this.#totalWeight} servers`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync getKeyServers(): Promise<Map<string, KeyServer>> {\n\t\tif (!this.#keyServers) {\n\t\t\tthis.#keyServers = this.#loadKeyServers().catch((error) => {\n\t\t\t\tthis.#keyServers = null;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn this.#keyServers;\n\t}\n\n\t/**\n\t * Returns a list of key servers with multiplicity according to their weights.\n\t * The list is used for encryption.\n\t */\n\tasync #getWeightedKeyServers() {\n\t\tconst keyServers = await this.getKeyServers();\n\t\tconst keyServersWithMultiplicity = [];\n\t\tfor (const [objectId, config] of this.#configs) {\n\t\t\tconst keyServer = keyServers.get(objectId)!;\n\t\t\tfor (let i = 0; i < config.weight; i++) {\n\t\t\t\tkeyServersWithMultiplicity.push(keyServer);\n\t\t\t}\n\t\t}\n\t\treturn keyServersWithMultiplicity;\n\t}\n\n\tasync #loadKeyServers(): Promise<Map<string, KeyServer>> {\n\t\tconst keyServers = await retrieveKeyServers({\n\t\t\tobjectIds: [...this.#configs].map(([objectId]) => objectId),\n\t\t\tclient: this.#suiClient,\n\t\t});\n\n\t\tif (keyServers.length === 0) {\n\t\t\tthrow new InvalidKeyServerError('No key servers found');\n\t\t}\n\n\t\tif (this.#verifyKeyServers) {\n\t\t\tawait Promise.all(\n\t\t\t\tkeyServers.map(async (server) => {\n\t\t\t\t\tconst config = this.#configs.get(server.objectId);\n\t\t\t\t\tif (!(await verifyKeyServer(server, this.#timeout, config?.apiKeyName, config?.apiKey))) {\n\t\t\t\t\t\tthrow new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn new Map(keyServers.map((server) => [server.objectId, server]));\n\t}\n\n\t/**\n\t * Fetch keys from the key servers and update the cache.\n\t *\n\t * It is recommended to call this function once for all ids of all encrypted objects if\n\t * there are multiple, then call decrypt for each object. This avoids calling fetchKey\n\t * individually for each decrypt.\n\t *\n\t * @param ids - The ids of the encrypted objects.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @param sessionKey - The session key to use.\n\t * @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.\n\t */\n\tasync fetchKeys({\n\t\tids,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: {\n\t\tids: string[];\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\tthreshold: number;\n\t}) {\n\t\tif (threshold > this.#totalWeight || threshold < 1) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} servers with weights ${this.#configs}`,\n\t\t\t);\n\t\t}\n\t\tconst keyServers = await this.getKeyServers();\n\t\tconst fullIds = ids.map((id) => createFullId(sessionKey.getPackageId(), id));\n\n\t\t// Count a server as completed if it has keys for all fullIds.\n\t\t// Duplicated key server ids will be counted towards the threshold.\n\t\tlet completedWeight = 0;\n\t\tconst remainingKeyServers = [];\n\t\tlet remainingKeyServersWeight = 0;\n\t\tfor (const objectId of keyServers.keys()) {\n\t\t\tif (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${objectId}`))) {\n\t\t\t\tcompletedWeight += this.#weight(objectId);\n\t\t\t} else {\n\t\t\t\tremainingKeyServers.push(objectId);\n\t\t\t\tremainingKeyServersWeight += this.#weight(objectId);\n\t\t\t}\n\t\t}\n\n\t\t// Return early if we have enough keys from cache.\n\t\tif (completedWeight >= threshold) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check server validities.\n\t\tfor (const objectId of remainingKeyServers) {\n\t\t\tconst server = keyServers.get(objectId)!;\n\t\t\tif (server.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\tthrow new InvalidKeyServerError(\n\t\t\t\t\t`Server ${server.objectId} has invalid key type: ${server.keyType}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst cert = await sessionKey.getCertificate();\n\t\tconst signedRequest = await sessionKey.createRequestParams(txBytes);\n\n\t\tconst controller = new AbortController();\n\t\tconst errors: Error[] = [];\n\n\t\tconst keyFetches = remainingKeyServers.map(async (objectId) => {\n\t\t\tconst server = keyServers.get(objectId)!;\n\t\t\ttry {\n\t\t\t\tconst config = this.#configs.get(objectId);\n\t\t\t\tconst allKeys = await fetchKeysForAllIds(\n\t\t\t\t\tserver.url,\n\t\t\t\t\tsignedRequest.requestSignature,\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsignedRequest.decryptionKey,\n\t\t\t\t\tcert,\n\t\t\t\t\tthis.#timeout,\n\t\t\t\t\tconfig?.apiKeyName,\n\t\t\t\t\tconfig?.apiKey,\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\t// Check validity of the keys and add them to the cache.\n\t\t\t\tfor (const { fullId, key } of allKeys) {\n\t\t\t\t\tconst keyElement = G1Element.fromBytes(key);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!BonehFranklinBLS12381Services.verifyUserSecretKey(\n\t\t\t\t\t\t\tkeyElement,\n\t\t\t\t\t\t\tfullId,\n\t\t\t\t\t\t\tG2Element.fromBytes(server.pk),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconsole.warn('Received invalid key from key server ' + server.objectId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.#cachedKeys.set(`${fullId}:${server.objectId}`, keyElement);\n\t\t\t\t}\n\n\t\t\t\t// Check if all the receivedIds are consistent with the requested fullIds.\n\t\t\t\t// If so, consider the key server got all keys and mark as completed.\n\t\t\t\tif (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${server.objectId}`))) {\n\t\t\t\t\tcompletedWeight += this.#weight(objectId);\n\n\t\t\t\t\t// Return early if the completed servers is more than the threshold.\n\t\t\t\t\tif (completedWeight >= threshold) {\n\t\t\t\t\t\tcontroller.abort();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\terrors.push(error as Error);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// If there are too many errors that the threshold is not attainable, return early with error.\n\t\t\t\tremainingKeyServersWeight -= this.#weight(objectId);\n\t\t\t\tif (remainingKeyServersWeight < threshold - completedWeight) {\n\t\t\t\t\tcontroller.abort(new TooManyFailedFetchKeyRequestsError());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.allSettled(keyFetches);\n\n\t\tif (completedWeight < threshold) {\n\t\t\tthrow toMajorityError(errors);\n\t\t}\n\t}\n\n\t/**\n\t * Get derived keys from the given services.\n\t *\n\t * @param id - The id of the encrypted object.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @param sessionKey - The session key to use.\n\t * @param threshold - The threshold.\n\t * @returns - Derived keys for the given services that are in the cache as a \"service object ID\" -> derived key map. If the call is succesful, exactly threshold keys will be returned.\n\t */\n\tasync getDerivedKeys({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tid,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: {\n\t\tkemType?: KemType;\n\t\tid: string;\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\tthreshold: number;\n\t}): Promise<Map<string, DerivedKey>> {\n\t\tswitch (kemType) {\n\t\t\tcase KemType.BonehFranklinBLS12381DemCCA:\n\t\t\t\tconst keyServers = await this.getKeyServers();\n\t\t\t\tif (threshold > this.#totalWeight) {\n\t\t\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t\t\t`Invalid threshold ${threshold} for ${this.#totalWeight} servers`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait this.fetchKeys({\n\t\t\t\t\tids: [id],\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsessionKey,\n\t\t\t\t\tthreshold,\n\t\t\t\t});\n\n\t\t\t\t// After calling fetchKeys, we can be sure that there are at least `threshold` of the required keys in the cache.\n\t\t\t\t// It is also checked there that the KeyServerType is BonehFranklinBLS12381 for all services.\n\n\t\t\t\tconst fullId = createFullId(sessionKey.getPackageId(), id);\n\n\t\t\t\tconst derivedKeys = new Map();\n\t\t\t\tlet weight = 0;\n\t\t\t\tfor (const objectId of keyServers.keys()) {\n\t\t\t\t\t// The code below assumes that the KeyServerType is BonehFranklinBLS12381.\n\t\t\t\t\tconst cachedKey = this.#cachedKeys.get(`${fullId}:${objectId}`);\n\t\t\t\t\tif (cachedKey) {\n\t\t\t\t\t\tderivedKeys.set(objectId, new BonehFranklinBLS12381DerivedKey(cachedKey));\n\t\t\t\t\t\tweight += this.#weight(objectId);\n\t\t\t\t\t\tif (weight >= threshold) {\n\t\t\t\t\t\t\t// We have enough keys, so we can stop.\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn derivedKeys;\n\t\t}\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAgC;AAChC,sBAAqC;AACrC,qBAAwB;AAExB,iBAAsC;AACtC,qBAA0C;AAC1C,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { EncryptedObject } from './bcs.js';\nimport { G1Element, G2Element } from './bls12381.js';\nimport { decrypt } from './decrypt.js';\nimport type { EncryptionInput } from './dem.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { DemType, encrypt, KemType } from './encrypt.js';\nimport {\n\tInconsistentKeyServersError,\n\tInvalidClientOptionsError,\n\tInvalidKeyServerError,\n\tInvalidPackageError,\n\tInvalidThresholdError,\n\ttoMajorityError,\n\tTooManyFailedFetchKeyRequestsError,\n} from './error.js';\nimport { BonehFranklinBLS12381Services } from './ibe.js';\nimport {\n\tBonehFranklinBLS12381DerivedKey,\n\tKeyServerType,\n\tretrieveKeyServers,\n\tverifyKeyServer,\n} from './key-server.js';\nimport type { DerivedKey, KeyServer } from './key-server.js';\nimport { fetchKeysForAllIds } from './keys.js';\nimport type { SessionKey } from './session-key.js';\nimport type { KeyCacheKey, SealCompatibleClient } from './types.js';\nimport { createFullId, count } from './utils.js';\n\n/**\n * Configuration options for initializing a SealClient\n * @property serverConfigs: Array of key server configs consisting of objectId, weight, optional API key name and API key.\n * @property verifyKeyServers: Whether to verify the key servers' authenticity.\n * \t Should be false if servers are pre-verified (e.g., getAllowlistedKeyServers).\n * \t Defaults to true.\n * @property timeout: Timeout in milliseconds for network requests. Defaults to 10 seconds.\n */\nexport interface SealClientExtensionOptions {\n\tserverConfigs: KeyServerConfig[];\n\tverifyKeyServers?: boolean;\n\ttimeout?: number;\n}\n\nexport interface KeyServerConfig {\n\tobjectId: string;\n\tweight: number;\n\tapiKeyName?: string;\n\tapiKey?: string;\n}\n\nexport interface SealClientOptions extends SealClientExtensionOptions {\n\tsuiClient: SealCompatibleClient;\n}\n\nexport class SealClient {\n\t#suiClient: SealCompatibleClient;\n\t#configs: Map<string, KeyServerConfig>;\n\t#keyServers: Promise<Map<string, KeyServer>> | null = null;\n\t#verifyKeyServers: boolean;\n\t// A caching map for: fullId:object_id -> partial key.\n\t#cachedKeys = new Map<KeyCacheKey, G1Element>();\n\t#timeout: number;\n\t#totalWeight: number;\n\n\tconstructor(options: SealClientOptions) {\n\t\tthis.#suiClient = options.suiClient;\n\n\t\tif (\n\t\t\tnew Set(options.serverConfigs.map((s) => s.objectId)).size !== options.serverConfigs.length\n\t\t) {\n\t\t\tthrow new InvalidClientOptionsError('Duplicate object IDs');\n\t\t}\n\n\t\tif (\n\t\t\toptions.serverConfigs.some((s) => (s.apiKeyName && !s.apiKey) || (!s.apiKeyName && s.apiKey))\n\t\t) {\n\t\t\tthrow new InvalidClientOptionsError(\n\t\t\t\t'Both apiKeyName and apiKey must be provided or not provided for all key servers',\n\t\t\t);\n\t\t}\n\n\t\tthis.#configs = new Map(options.serverConfigs.map((server) => [server.objectId, server]));\n\t\tthis.#totalWeight = options.serverConfigs\n\t\t\t.map((server) => server.weight)\n\t\t\t.reduce((sum, term) => sum + term, 0);\n\n\t\tthis.#verifyKeyServers = options.verifyKeyServers ?? true;\n\t\tthis.#timeout = options.timeout ?? 10_000;\n\t}\n\n\tstatic experimental_asClientExtension(options: SealClientExtensionOptions) {\n\t\treturn {\n\t\t\tname: 'seal' as const,\n\t\t\tregister: (client: SealCompatibleClient) => {\n\t\t\t\treturn new SealClient({\n\t\t\t\t\tsuiClient: client,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Return an encrypted message under the identity.\n\t *\n\t * @param kemType - The type of KEM to use.\n\t * @param demType - The type of DEM to use.\n\t * @param threshold - The threshold for the TSS encryption.\n\t * @param packageId - the packageId namespace.\n\t * @param id - the identity to use.\n\t * @param data - the data to encrypt.\n\t * @param aad - optional additional authenticated data.\n\t * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.\n\t * \tSince the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.\n\t */\n\tasync encrypt({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tdemType = DemType.AesGcm256,\n\t\tthreshold,\n\t\tpackageId,\n\t\tid,\n\t\tdata,\n\t\taad = new Uint8Array(),\n\t}: {\n\t\tkemType?: KemType;\n\t\tdemType?: DemType;\n\t\tthreshold: number;\n\t\tpackageId: string;\n\t\tid: string;\n\t\tdata: Uint8Array;\n\t\taad?: Uint8Array;\n\t}) {\n\t\tconst packageObj = await this.#suiClient.core.getObject({ objectId: packageId });\n\t\tif (String(packageObj.object.version) !== '1') {\n\t\t\tthrow new InvalidPackageError(`Package ${packageId} is not the first version`);\n\t\t}\n\n\t\treturn encrypt({\n\t\t\tkeyServers: await this.#getWeightedKeyServers(),\n\t\t\tkemType,\n\t\t\tthreshold,\n\t\t\tpackageId,\n\t\t\tid,\n\t\t\tencryptionInput: this.#createEncryptionInput(demType, data, aad),\n\t\t});\n\t}\n\n\t#createEncryptionInput(type: DemType, data: Uint8Array, aad: Uint8Array): EncryptionInput {\n\t\tswitch (type) {\n\t\t\tcase DemType.AesGcm256:\n\t\t\t\treturn new AesGcm256(data, aad);\n\t\t\tcase DemType.Hmac256Ctr:\n\t\t\t\treturn new Hmac256Ctr(data, aad);\n\t\t}\n\t}\n\n\t/**\n\t * Decrypt the given encrypted bytes using cached keys.\n\t * Calls fetchKeys in case one or more of the required keys is not cached yet.\n\t * The function throws an error if the client's key servers are not a subset of\n\t * the encrypted object's key servers or if the threshold cannot be met.\n\t *\n\t * @param data - The encrypted bytes to decrypt.\n\t * @param sessionKey - The session key to use.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt({\n\t\tdata,\n\t\tsessionKey,\n\t\ttxBytes,\n\t}: {\n\t\tdata: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\ttxBytes: Uint8Array;\n\t}) {\n\t\tconst encryptedObject = EncryptedObject.parse(data);\n\n\t\tthis.#validateEncryptionServices(\n\t\t\tencryptedObject.services.map((s) => s[0]),\n\t\t\tencryptedObject.threshold,\n\t\t);\n\n\t\tawait this.fetchKeys({\n\t\t\tids: [encryptedObject.id],\n\t\t\ttxBytes,\n\t\t\tsessionKey,\n\t\t\tthreshold: encryptedObject.threshold,\n\t\t});\n\n\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys });\n\t}\n\n\t#weight(objectId: string) {\n\t\treturn this.#configs.get(objectId)?.weight ?? 0;\n\t}\n\n\t#validateEncryptionServices(services: string[], threshold: number) {\n\t\t// Check that the client's key servers are a subset of the encrypted object's key servers.\n\t\tif (\n\t\t\tservices.some((objectId) => {\n\t\t\t\tconst countInClient = this.#weight(objectId);\n\t\t\t\treturn countInClient > 0 && countInClient !== count(services, objectId);\n\t\t\t})\n\t\t) {\n\t\t\tthrow new InconsistentKeyServersError(\n\t\t\t\t`Client's key servers must be a subset of the encrypted object's key servers`,\n\t\t\t);\n\t\t}\n\t\t// Check that the threshold can be met with the client's key servers.\n\t\tif (threshold > this.#totalWeight) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${this.#totalWeight} servers`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync getKeyServers(): Promise<Map<string, KeyServer>> {\n\t\tif (!this.#keyServers) {\n\t\t\tthis.#keyServers = this.#loadKeyServers().catch((error) => {\n\t\t\t\tthis.#keyServers = null;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn this.#keyServers;\n\t}\n\n\t/**\n\t * Returns a list of key servers with multiplicity according to their weights.\n\t * The list is used for encryption.\n\t */\n\tasync #getWeightedKeyServers() {\n\t\tconst keyServers = await this.getKeyServers();\n\t\tconst keyServersWithMultiplicity = [];\n\t\tfor (const [objectId, config] of this.#configs) {\n\t\t\tconst keyServer = keyServers.get(objectId)!;\n\t\t\tfor (let i = 0; i < config.weight; i++) {\n\t\t\t\tkeyServersWithMultiplicity.push(keyServer);\n\t\t\t}\n\t\t}\n\t\treturn keyServersWithMultiplicity;\n\t}\n\n\tasync #loadKeyServers(): Promise<Map<string, KeyServer>> {\n\t\tconst keyServers = await retrieveKeyServers({\n\t\t\tobjectIds: [...this.#configs].map(([objectId]) => objectId),\n\t\t\tclient: this.#suiClient,\n\t\t});\n\n\t\tif (keyServers.length === 0) {\n\t\t\tthrow new InvalidKeyServerError('No key servers found');\n\t\t}\n\n\t\tif (this.#verifyKeyServers) {\n\t\t\tawait Promise.all(\n\t\t\t\tkeyServers.map(async (server) => {\n\t\t\t\t\tconst config = this.#configs.get(server.objectId);\n\t\t\t\t\tif (!(await verifyKeyServer(server, this.#timeout, config?.apiKeyName, config?.apiKey))) {\n\t\t\t\t\t\tthrow new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn new Map(keyServers.map((server) => [server.objectId, server]));\n\t}\n\n\t/**\n\t * Fetch keys from the key servers and update the cache.\n\t *\n\t * It is recommended to call this function once for all ids of all encrypted objects if\n\t * there are multiple, then call decrypt for each object. This avoids calling fetchKey\n\t * individually for each decrypt.\n\t *\n\t * @param ids - The ids of the encrypted objects.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @param sessionKey - The session key to use.\n\t * @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.\n\t */\n\tasync fetchKeys({\n\t\tids,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: {\n\t\tids: string[];\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\tthreshold: number;\n\t}) {\n\t\tif (threshold > this.#totalWeight || threshold < 1) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} servers with weights ${this.#configs}`,\n\t\t\t);\n\t\t}\n\t\tconst keyServers = await this.getKeyServers();\n\t\tconst fullIds = ids.map((id) => createFullId(sessionKey.getPackageId(), id));\n\n\t\t// Count a server as completed if it has keys for all fullIds.\n\t\t// Duplicated key server ids will be counted towards the threshold.\n\t\tlet completedWeight = 0;\n\t\tconst remainingKeyServers = [];\n\t\tlet remainingKeyServersWeight = 0;\n\t\tfor (const objectId of keyServers.keys()) {\n\t\t\tif (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${objectId}`))) {\n\t\t\t\tcompletedWeight += this.#weight(objectId);\n\t\t\t} else {\n\t\t\t\tremainingKeyServers.push(objectId);\n\t\t\t\tremainingKeyServersWeight += this.#weight(objectId);\n\t\t\t}\n\t\t}\n\n\t\t// Return early if we have enough keys from cache.\n\t\tif (completedWeight >= threshold) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check server validities.\n\t\tfor (const objectId of remainingKeyServers) {\n\t\t\tconst server = keyServers.get(objectId)!;\n\t\t\tif (server.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\tthrow new InvalidKeyServerError(\n\t\t\t\t\t`Server ${server.objectId} has invalid key type: ${server.keyType}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst cert = await sessionKey.getCertificate();\n\t\tconst signedRequest = await sessionKey.createRequestParams(txBytes);\n\n\t\tconst controller = new AbortController();\n\t\tconst errors: Error[] = [];\n\n\t\tconst keyFetches = remainingKeyServers.map(async (objectId) => {\n\t\t\tconst server = keyServers.get(objectId)!;\n\t\t\ttry {\n\t\t\t\tconst config = this.#configs.get(objectId);\n\t\t\t\tconst allKeys = await fetchKeysForAllIds(\n\t\t\t\t\tserver.url,\n\t\t\t\t\tsignedRequest.requestSignature,\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsignedRequest.decryptionKey,\n\t\t\t\t\tcert,\n\t\t\t\t\tthis.#timeout,\n\t\t\t\t\tconfig?.apiKeyName,\n\t\t\t\t\tconfig?.apiKey,\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\t// Check validity of the keys and add them to the cache.\n\t\t\t\tfor (const { fullId, key } of allKeys) {\n\t\t\t\t\tconst keyElement = G1Element.fromBytes(key);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!BonehFranklinBLS12381Services.verifyUserSecretKey(\n\t\t\t\t\t\t\tkeyElement,\n\t\t\t\t\t\t\tfullId,\n\t\t\t\t\t\t\tG2Element.fromBytes(server.pk),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconsole.warn('Received invalid key from key server ' + server.objectId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.#cachedKeys.set(`${fullId}:${server.objectId}`, keyElement);\n\t\t\t\t}\n\n\t\t\t\t// Check if all the receivedIds are consistent with the requested fullIds.\n\t\t\t\t// If so, consider the key server got all keys and mark as completed.\n\t\t\t\tif (fullIds.every((fullId) => this.#cachedKeys.has(`${fullId}:${server.objectId}`))) {\n\t\t\t\t\tcompletedWeight += this.#weight(objectId);\n\n\t\t\t\t\t// Return early if the completed servers is more than the threshold.\n\t\t\t\t\tif (completedWeight >= threshold) {\n\t\t\t\t\t\tcontroller.abort();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\terrors.push(error as Error);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// If there are too many errors that the threshold is not attainable, return early with error.\n\t\t\t\tremainingKeyServersWeight -= this.#weight(objectId);\n\t\t\t\tif (remainingKeyServersWeight < threshold - completedWeight) {\n\t\t\t\t\tcontroller.abort(new TooManyFailedFetchKeyRequestsError());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.allSettled(keyFetches);\n\n\t\tif (completedWeight < threshold) {\n\t\t\tthrow toMajorityError(errors);\n\t\t}\n\t}\n\n\t/**\n\t * Get derived keys from the given services.\n\t *\n\t * @param id - The id of the encrypted object.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @param sessionKey - The session key to use.\n\t * @param threshold - The threshold.\n\t * @returns - Derived keys for the given services that are in the cache as a \"service object ID\" -> derived key map. If the call is succesful, exactly threshold keys will be returned.\n\t */\n\tasync getDerivedKeys({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tid,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: {\n\t\tkemType?: KemType;\n\t\tid: string;\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\tthreshold: number;\n\t}): Promise<Map<string, DerivedKey>> {\n\t\tswitch (kemType) {\n\t\t\tcase KemType.BonehFranklinBLS12381DemCCA:\n\t\t\t\tconst keyServers = await this.getKeyServers();\n\t\t\t\tif (threshold > this.#totalWeight) {\n\t\t\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t\t\t`Invalid threshold ${threshold} for ${this.#totalWeight} servers`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait this.fetchKeys({\n\t\t\t\t\tids: [id],\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsessionKey,\n\t\t\t\t\tthreshold,\n\t\t\t\t});\n\n\t\t\t\t// After calling fetchKeys, we can be sure that there are at least `threshold` of the required keys in the cache.\n\t\t\t\t// It is also checked there that the KeyServerType is BonehFranklinBLS12381 for all services.\n\n\t\t\t\tconst fullId = createFullId(sessionKey.getPackageId(), id);\n\n\t\t\t\tconst derivedKeys = new Map();\n\t\t\t\tlet weight = 0;\n\t\t\t\tfor (const objectId of keyServers.keys()) {\n\t\t\t\t\t// The code below assumes that the KeyServerType is BonehFranklinBLS12381.\n\t\t\t\t\tconst cachedKey = this.#cachedKeys.get(`${fullId}:${objectId}`);\n\t\t\t\t\tif (cachedKey) {\n\t\t\t\t\t\tderivedKeys.set(objectId, new BonehFranklinBLS12381DerivedKey(cachedKey));\n\t\t\t\t\t\tweight += this.#weight(objectId);\n\t\t\t\t\t\tif (weight >= threshold) {\n\t\t\t\t\t\t\t// We have enough keys, so we can stop.\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn derivedKeys;\n\t\t}\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAgC;AAChC,sBAAqC;AACrC,qBAAwB;AAExB,iBAAsC;AACtC,qBAA0C;AAC1C,mBAQO;AACP,iBAA8C;AAC9C,wBAKO;AAEP,kBAAmC;AAGnC,mBAAoC;AA7BpC;AAwDO,MAAM,cAAN,MAAM,YAAW;AAAA,EAUvB,YAAY,SAA4B;AAVlC;AACN;AACA;AACA,oCAAsD;AACtD;AAEA;AAAA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AAa,MAAM,KAAK,cAAc;AAC5C,QAAM,6BAA6B,CAAC;AACpC,aAAW,CAAC,UAAU,MAAM,KAAK,mBAAK,WAAU;AAC/C,UAAM,YAAY,WAAW,IAAI,QAAQ;AACzC,aAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACvC,iCAA2B,KAAK,SAAS;AAAA,IAC1C;AAAA,EACD;AACA,SAAO;AACR;AAEM,oBAAe,iBAAoC;AACxD,QAAM,aAAa,UAAM,sCAAmB;AAAA,IAC3C,WAAW,CAAC,GAAG,mBAAK,SAAQ,EAAE,IAAI,CAAC,CAAC,QAAQ,MAAM,QAAQ;AAAA,IAC1D,QAAQ,mBAAK;AAAA,EACd,CAAC;AAED,MAAI,WAAW,WAAW,GAAG;AAC5B,UAAM,IAAI,mCAAsB,sBAAsB;AAAA,EACvD;AAEA,MAAI,mBAAK,oBAAmB;AAC3B,UAAM,QAAQ;AAAA,MACb,WAAW,IAAI,OAAO,WAAW;AAChC,cAAM,SAAS,mBAAK,UAAS,IAAI,OAAO,QAAQ;AAChD,YAAI,CAAE,UAAM,mCAAgB,QAAQ,mBAAK,WAAU,QAAQ,YAAY,QAAQ,MAAM,GAAI;AACxF,gBAAM,IAAI,mCAAsB,cAAc,OAAO,QAAQ,eAAe;AAAA,QAC7E;AAAA,MACD,CAAC;AAAA,IACF;AAAA,EACD;AACA,SAAO,IAAI,IAAI,WAAW,IAAI,CAAC,WAAW,CAAC,OAAO,UAAU,MAAM,CAAC,CAAC;AACrE;AAlNM,IAAM,aAAN;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/key-server.js
CHANGED
|
@@ -34,6 +34,7 @@ var import_error = require("./error.js");
|
|
|
34
34
|
var import_ibe = require("./ibe.js");
|
|
35
35
|
var import_version = require("./version.js");
|
|
36
36
|
var import_utils = require("./utils.js");
|
|
37
|
+
const EXPECTED_SERVER_VERSION = 1;
|
|
37
38
|
var KeyServerType = /* @__PURE__ */ ((KeyServerType2) => {
|
|
38
39
|
KeyServerType2[KeyServerType2["BonehFranklinBLS12381"] = 0] = "BonehFranklinBLS12381";
|
|
39
40
|
return KeyServerType2;
|
|
@@ -42,8 +43,8 @@ const SERVER_VERSION_REQUIREMENT = new import_utils.Version("0.4.1");
|
|
|
42
43
|
function getAllowlistedKeyServers(network) {
|
|
43
44
|
if (network === "testnet") {
|
|
44
45
|
return [
|
|
45
|
-
"
|
|
46
|
-
"
|
|
46
|
+
"0x73d05d62c18d9374e3ea529e8e0ed6161da1a141a94d3f76ae3fe4e99356db75",
|
|
47
|
+
"0xf5d14a81a982144ae441cd7d64b09027f116a468bd36e7eca494f750591623c8"
|
|
47
48
|
];
|
|
48
49
|
} else {
|
|
49
50
|
throw new import_error.UnsupportedNetworkError(`Unsupported network ${network}`);
|
|
@@ -55,31 +56,36 @@ async function retrieveKeyServers({
|
|
|
55
56
|
}) {
|
|
56
57
|
return await Promise.all(
|
|
57
58
|
objectIds.map(async (objectId) => {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
objectId
|
|
62
|
-
});
|
|
63
|
-
} catch (e) {
|
|
64
|
-
throw new import_error.InvalidGetObjectError(`KeyServer ${objectId} not found; ${e.message}`);
|
|
65
|
-
}
|
|
59
|
+
const res = await client.core.getObject({
|
|
60
|
+
objectId
|
|
61
|
+
});
|
|
66
62
|
const ks = import_bcs2.KeyServerMove.parse(res.object.content);
|
|
67
|
-
if (ks.
|
|
68
|
-
throw new import_error.
|
|
63
|
+
if (EXPECTED_SERVER_VERSION < Number(ks.firstVersion) || EXPECTED_SERVER_VERSION > Number(ks.lastVersion)) {
|
|
64
|
+
throw new import_error.InvalidKeyServerVersionError(
|
|
65
|
+
`Key server ${objectId} supports versions between ${ks.firstVersion} and ${ks.lastVersion} (inclusive), but SDK expects version ${EXPECTED_SERVER_VERSION}`
|
|
66
|
+
);
|
|
69
67
|
}
|
|
68
|
+
const resVersionedKs = await client.core.getDynamicField({
|
|
69
|
+
parentId: objectId,
|
|
70
|
+
name: {
|
|
71
|
+
type: "u64",
|
|
72
|
+
bcs: import_bcs.bcs.u64().serialize(EXPECTED_SERVER_VERSION).toBytes()
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
const ksVersioned = import_bcs2.KeyServerMoveV1.parse(resVersionedKs.dynamicField.value.bcs);
|
|
70
76
|
return {
|
|
71
77
|
objectId,
|
|
72
|
-
name:
|
|
73
|
-
url:
|
|
74
|
-
keyType:
|
|
75
|
-
pk: new Uint8Array(
|
|
78
|
+
name: ksVersioned.name,
|
|
79
|
+
url: ksVersioned.url,
|
|
80
|
+
keyType: ksVersioned.keyType,
|
|
81
|
+
pk: new Uint8Array(ksVersioned.pk)
|
|
76
82
|
};
|
|
77
83
|
})
|
|
78
84
|
);
|
|
79
85
|
}
|
|
80
86
|
async function verifyKeyServer(server, timeout, apiKeyName, apiKey) {
|
|
81
87
|
const requestId = crypto.randomUUID();
|
|
82
|
-
const response = await fetch(server.url + "/v1/service", {
|
|
88
|
+
const response = await fetch(server.url + "/v1/service?service_id=" + server.objectId, {
|
|
83
89
|
method: "GET",
|
|
84
90
|
headers: {
|
|
85
91
|
"Content-Type": "application/json",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/key-server.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, fromHex, toHex } from '@mysten/bcs';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { KeyServerMove } from './bcs.js';\nimport {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs, fromBase64, fromHex, toHex } from '@mysten/bcs';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { KeyServerMove, KeyServerMoveV1 } from './bcs.js';\nimport { InvalidKeyServerVersionError, SealAPIError, UnsupportedNetworkError } from './error.js';\nimport { DST_POP } from './ibe.js';\nimport { PACKAGE_VERSION } from './version.js';\nimport type { SealCompatibleClient } from './types.js';\nimport type { G1Element } from './bls12381.js';\nimport { flatten, Version } from './utils.js';\n\nconst EXPECTED_SERVER_VERSION = 1;\n\nexport type KeyServer = {\n\tobjectId: string;\n\tname: string;\n\turl: string;\n\tkeyType: KeyServerType;\n\tpk: Uint8Array;\n};\n\nexport enum KeyServerType {\n\tBonehFranklinBLS12381 = 0,\n}\n\nexport const SERVER_VERSION_REQUIREMENT = new Version('0.4.1');\n\n/**\n * Returns a static list of Seal key server object ids that the dapp can choose to use.\n * @param network - The network to use.\n * @returns The object id's of the key servers.\n */\nexport function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): string[] {\n\tif (network === 'testnet') {\n\t\treturn [\n\t\t\t'0x73d05d62c18d9374e3ea529e8e0ed6161da1a141a94d3f76ae3fe4e99356db75',\n\t\t\t'0xf5d14a81a982144ae441cd7d64b09027f116a468bd36e7eca494f750591623c8',\n\t\t];\n\t} else {\n\t\tthrow new UnsupportedNetworkError(`Unsupported network ${network}`);\n\t}\n}\n\n/**\n * Given a list of key server object IDs, returns a list of SealKeyServer\n * from onchain state containing name, objectId, URL and pk.\n *\n * @param objectIds - The key server object IDs.\n * @param client - The SuiClient to use.\n * @returns - An array of SealKeyServer.\n */\nexport async function retrieveKeyServers({\n\tobjectIds,\n\tclient,\n}: {\n\tobjectIds: string[];\n\tclient: SealCompatibleClient;\n}): Promise<KeyServer[]> {\n\treturn await Promise.all(\n\t\tobjectIds.map(async (objectId) => {\n\t\t\t// First get the KeyServer object and validate it.\n\t\t\tconst res = await client.core.getObject({\n\t\t\t\tobjectId,\n\t\t\t});\n\t\t\tconst ks = KeyServerMove.parse(res.object.content);\n\t\t\tif (\n\t\t\t\tEXPECTED_SERVER_VERSION < Number(ks.firstVersion) ||\n\t\t\t\tEXPECTED_SERVER_VERSION > Number(ks.lastVersion)\n\t\t\t) {\n\t\t\t\tthrow new InvalidKeyServerVersionError(\n\t\t\t\t\t`Key server ${objectId} supports versions between ${ks.firstVersion} and ${ks.lastVersion} (inclusive), but SDK expects version ${EXPECTED_SERVER_VERSION}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Then fetch the expected versioned object and parse it.\n\t\t\tconst resVersionedKs = await client.core.getDynamicField({\n\t\t\t\tparentId: objectId,\n\t\t\t\tname: {\n\t\t\t\t\ttype: 'u64',\n\t\t\t\t\tbcs: bcs.u64().serialize(EXPECTED_SERVER_VERSION).toBytes(),\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tconst ksVersioned = KeyServerMoveV1.parse(resVersionedKs.dynamicField.value.bcs);\n\n\t\t\treturn {\n\t\t\t\tobjectId,\n\t\t\t\tname: ksVersioned.name,\n\t\t\t\turl: ksVersioned.url,\n\t\t\t\tkeyType: ksVersioned.keyType,\n\t\t\t\tpk: new Uint8Array(ksVersioned.pk),\n\t\t\t};\n\t\t}),\n\t);\n}\n\n/**\n * Given a KeyServer, fetch the proof of possession (PoP) from the URL and verify it\n * against the pubkey. This should be used only rarely when the dapp uses a dynamic\n * set of key servers.\n *\n * @param server - The KeyServer to verify.\n * @returns - True if the key server is valid, false otherwise.\n */\nexport async function verifyKeyServer(\n\tserver: KeyServer,\n\ttimeout: number,\n\tapiKeyName?: string,\n\tapiKey?: string,\n): Promise<boolean> {\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(server.url! + '/v1/service?service_id=' + server.objectId, {\n\t\tmethod: 'GET',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Request-Id': requestId,\n\t\t\t'Client-Sdk-Type': 'typescript',\n\t\t\t'Client-Sdk-Version': PACKAGE_VERSION,\n\t\t\t...(apiKeyName && apiKey ? { apiKeyName: apiKey } : {}),\n\t\t},\n\t\tsignal: AbortSignal.timeout(timeout),\n\t});\n\n\tawait SealAPIError.assertResponse(response, requestId);\n\tverifyKeyServerVersion(response);\n\tconst serviceResponse = await response.json();\n\n\tif (serviceResponse.service_id !== server.objectId) {\n\t\treturn false;\n\t}\n\tconst fullMsg = flatten([DST_POP, server.pk, fromHex(server.objectId)]);\n\treturn bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);\n}\n\n/**\n * Verify the key server version. Throws an `InvalidKeyServerError` if the version is not supported.\n *\n * @param response - The response from the key server.\n */\nexport function verifyKeyServerVersion(response: Response) {\n\tconst keyServerVersion = response.headers.get('X-KeyServer-Version');\n\tif (keyServerVersion == null) {\n\t\tthrow new InvalidKeyServerVersionError('Key server version not found');\n\t}\n\tif (new Version(keyServerVersion).older_than(SERVER_VERSION_REQUIREMENT)) {\n\t\tthrow new InvalidKeyServerVersionError(\n\t\t\t`Key server version ${keyServerVersion} is not supported`,\n\t\t);\n\t}\n}\n\nexport interface DerivedKey {\n\ttoString(): string;\n}\n\n/**\n * A user secret key for the Boneh-Franklin BLS12381 scheme.\n * This is a wrapper around the G1Element type.\n */\nexport class BonehFranklinBLS12381DerivedKey implements DerivedKey {\n\trepresentation: string;\n\n\tconstructor(public key: G1Element) {\n\t\tthis.representation = toHex(key.toBytes());\n\t}\n\n\ttoString(): string {\n\t\treturn this.representation;\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,iBAAgD;AAChD,uBAA0B;AAE1B,IAAAA,cAA+C;AAC/C,mBAAoF;AACpF,iBAAwB;AACxB,qBAAgC;AAGhC,mBAAiC;AAEjC,MAAM,0BAA0B;AAUzB,IAAK,gBAAL,kBAAKC,mBAAL;AACN,EAAAA,8BAAA,2BAAwB,KAAxB;AADW,SAAAA;AAAA,GAAA;AAIL,MAAM,6BAA6B,IA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AAA,MACR,gBAAgB;AAAA,MAChB,cAAc;AAAA,MACd,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,MACtB,GAAI,cAAc,SAAS,EAAE,YAAY,OAAO,IAAI,CAAC;AAAA,IACtD;AAAA,IACA,QAAQ,YAAY,QAAQ,OAAO;AAAA,EACpC,CAAC;AAED,QAAM,0BAAa,eAAe,UAAU,SAAS;AACrD,yBAAuB,QAAQ;AAC/B,QAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,MAAI,gBAAgB,eAAe,OAAO,UAAU;AACnD,WAAO;AAAA,EACR;AACA,QAAM,cAAU,sBAAQ,CAAC,oBAAS,OAAO,QAAI,oBAAQ,OAAO,QAAQ,CAAC,CAAC;AACtE,SAAO,2BAAU,yBAAqB,uBAAW,gBAAgB,GAAG,GAAG,SAAS,OAAO,EAAE;AAC1F;AAOO,SAAS,uBAAuB,UAAoB;AAC1D,QAAM,mBAAmB,SAAS,QAAQ,IAAI,qBAAqB;AACnE,MAAI,oBAAoB,MAAM;AAC7B,UAAM,IAAI,0CAA6B,8BAA8B;AAAA,EACtE;AACA,MAAI,IAAI,qBAAQ,gBAAgB,EAAE,WAAW,0BAA0B,GAAG;AACzE,UAAM,IAAI;AAAA,MACT,sBAAsB,gBAAgB;AAAA,IACvC;AAAA,EACD;AACD;AAUO,MAAM,gCAAsD;AAAA,EAGlE,YAAmB,KAAgB;AAAhB;AAClB,SAAK,qBAAiB,kBAAM,IAAI,QAAQ,CAAC;AAAA,EAC1C;AAAA,EAEA,WAAmB;AAClB,WAAO,KAAK;AAAA,EACb;AACD;",
|
|
6
6
|
"names": ["import_bcs", "KeyServerType"]
|
|
7
7
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Signer } from '@mysten/sui/cryptography';
|
|
2
|
-
import type {
|
|
2
|
+
import type { SealCompatibleClient } from './types.js';
|
|
3
3
|
export declare const RequestFormat: import("@mysten/bcs").BcsType<{
|
|
4
4
|
ptb: number[];
|
|
5
5
|
encKey: number[];
|
|
@@ -34,14 +34,24 @@ export type SessionKeyType = {
|
|
|
34
34
|
};
|
|
35
35
|
export declare class SessionKey {
|
|
36
36
|
#private;
|
|
37
|
+
/**
|
|
38
|
+
* @deprecated - Use `await SessionKey.create()` instead.
|
|
39
|
+
*/
|
|
37
40
|
constructor({ address, packageId, mvrName, ttlMin, signer, suiClient, }: {
|
|
38
41
|
address: string;
|
|
39
42
|
packageId: string;
|
|
40
43
|
mvrName?: string;
|
|
41
44
|
ttlMin: number;
|
|
42
45
|
signer?: Signer;
|
|
43
|
-
suiClient:
|
|
46
|
+
suiClient: SealCompatibleClient;
|
|
44
47
|
});
|
|
48
|
+
static create({ address, packageId, ttlMin, signer, suiClient, }: {
|
|
49
|
+
address: string;
|
|
50
|
+
packageId: string;
|
|
51
|
+
ttlMin: number;
|
|
52
|
+
signer?: Signer;
|
|
53
|
+
suiClient: SealCompatibleClient;
|
|
54
|
+
}): Promise<SessionKey>;
|
|
45
55
|
isExpired(): boolean;
|
|
46
56
|
getAddress(): string;
|
|
47
57
|
getPackageName(): string;
|
|
@@ -61,5 +71,5 @@ export declare class SessionKey {
|
|
|
61
71
|
* Restore a SessionKey instance for the given object.
|
|
62
72
|
* @returns A new SessionKey instance with restored state
|
|
63
73
|
*/
|
|
64
|
-
static import(data: SessionKeyType, suiClient:
|
|
74
|
+
static import(data: SessionKeyType, suiClient: SealCompatibleClient, signer?: Signer): SessionKey;
|
|
65
75
|
}
|
package/dist/cjs/session-key.js
CHANGED
|
@@ -43,6 +43,9 @@ const RequestFormat = import_bcs2.bcs.struct("RequestFormat", {
|
|
|
43
43
|
encVerificationKey: import_bcs2.bcs.vector(import_bcs2.bcs.U8)
|
|
44
44
|
});
|
|
45
45
|
const _SessionKey = class _SessionKey {
|
|
46
|
+
/**
|
|
47
|
+
* @deprecated - Use `await SessionKey.create()` instead.
|
|
48
|
+
*/
|
|
46
49
|
constructor({
|
|
47
50
|
address,
|
|
48
51
|
packageId,
|
|
@@ -81,6 +84,25 @@ const _SessionKey = class _SessionKey {
|
|
|
81
84
|
__privateSet(this, _signer, signer);
|
|
82
85
|
__privateSet(this, _suiClient, suiClient);
|
|
83
86
|
}
|
|
87
|
+
static async create({
|
|
88
|
+
address,
|
|
89
|
+
packageId,
|
|
90
|
+
ttlMin,
|
|
91
|
+
signer,
|
|
92
|
+
suiClient
|
|
93
|
+
}) {
|
|
94
|
+
const packageObj = await suiClient.core.getObject({ objectId: packageId });
|
|
95
|
+
if (String(packageObj.object.version) !== "1") {
|
|
96
|
+
throw new import_error.InvalidPackageError(`Package ${packageId} is not the first version`);
|
|
97
|
+
}
|
|
98
|
+
return new _SessionKey({
|
|
99
|
+
address,
|
|
100
|
+
packageId,
|
|
101
|
+
ttlMin,
|
|
102
|
+
signer,
|
|
103
|
+
suiClient
|
|
104
|
+
});
|
|
105
|
+
}
|
|
84
106
|
isExpired() {
|
|
85
107
|
return __privateGet(this, _creationTimeMs) + __privateGet(this, _ttlMin) * 60 * 1e3 - 1e4 < Date.now();
|
|
86
108
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/session-key.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toBase64 } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Signer } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { isValidNamedPackage, isValidSuiAddress, isValidSuiObjectId } from '@mysten/sui/utils';\nimport { verifyPersonalMessageSignature } from '@mysten/sui/verify';\nimport { generateSecretKey, toPublicKey, toVerificationKey } from './elgamal.js';\nimport {\n\tExpiredSessionKeyError,\n\tInvalidPersonalMessageSignatureError,\n\tUserError,\n} from './error.js';\nimport type {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAyB;AACzB,IAAAA,cAAoB;AAEpB,qBAA+B;AAC/B,mBAA2E;AAC3E,oBAA+C;AAC/C,qBAAkE;AAClE,
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toBase64 } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Signer } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { isValidNamedPackage, isValidSuiAddress, isValidSuiObjectId } from '@mysten/sui/utils';\nimport { verifyPersonalMessageSignature } from '@mysten/sui/verify';\nimport { generateSecretKey, toPublicKey, toVerificationKey } from './elgamal.js';\nimport {\n\tExpiredSessionKeyError,\n\tInvalidPackageError,\n\tInvalidPersonalMessageSignatureError,\n\tUserError,\n} from './error.js';\nimport type { SealCompatibleClient } from './types.js';\n\nexport const RequestFormat = bcs.struct('RequestFormat', {\n\tptb: bcs.vector(bcs.U8),\n\tencKey: bcs.vector(bcs.U8),\n\tencVerificationKey: bcs.vector(bcs.U8),\n});\n\nexport type Certificate = {\n\tuser: string;\n\tsession_vk: string;\n\tcreation_time: number;\n\tttl_min: number;\n\tsignature: string;\n\tmvr_name?: string;\n};\n\nexport type SessionKeyType = {\n\taddress: string;\n\tpackageId: string;\n\tmvrName?: string;\n\tcreationTimeMs: number;\n\tttlMin: number;\n\tpersonalMessageSignature?: string;\n\tsessionKey: string;\n};\n\nexport class SessionKey {\n\t#address: string;\n\t#packageId: string;\n\t#mvrName?: string;\n\t#creationTimeMs: number;\n\t#ttlMin: number;\n\t#sessionKey: Ed25519Keypair;\n\t#personalMessageSignature?: string;\n\t#signer?: Signer;\n\t#suiClient: SealCompatibleClient;\n\n\t/**\n\t * @deprecated - Use `await SessionKey.create()` instead.\n\t */\n\tconstructor({\n\t\taddress,\n\t\tpackageId,\n\t\tmvrName,\n\t\tttlMin,\n\t\tsigner,\n\t\tsuiClient,\n\t}: {\n\t\taddress: string;\n\t\tpackageId: string;\n\t\tmvrName?: string;\n\t\tttlMin: number;\n\t\tsigner?: Signer;\n\t\tsuiClient: SealCompatibleClient;\n\t}) {\n\t\tif (mvrName && !isValidNamedPackage(mvrName)) {\n\t\t\tthrow new UserError(`Invalid package name ${mvrName}`);\n\t\t}\n\t\tif (!isValidSuiObjectId(packageId) || !isValidSuiAddress(address)) {\n\t\t\tthrow new UserError(`Invalid package ID ${packageId} or address ${address}`);\n\t\t}\n\t\tif (ttlMin > 30 || ttlMin < 1) {\n\t\t\tthrow new UserError(`Invalid TTL ${ttlMin}, must be between 1 and 30`);\n\t\t}\n\t\tif (signer && signer.getPublicKey().toSuiAddress() !== address) {\n\t\t\tthrow new UserError('Signer address does not match session key address');\n\t\t}\n\n\t\tthis.#address = address;\n\t\tthis.#packageId = packageId;\n\t\tthis.#mvrName = mvrName;\n\t\tthis.#creationTimeMs = Date.now();\n\t\tthis.#ttlMin = ttlMin;\n\t\tthis.#sessionKey = Ed25519Keypair.generate();\n\t\tthis.#signer = signer;\n\t\tthis.#suiClient = suiClient;\n\t}\n\n\tstatic async create({\n\t\taddress,\n\t\tpackageId,\n\t\tttlMin,\n\t\tsigner,\n\t\tsuiClient,\n\t}: {\n\t\taddress: string;\n\t\tpackageId: string;\n\t\tttlMin: number;\n\t\tsigner?: Signer;\n\t\tsuiClient: SealCompatibleClient;\n\t}): Promise<SessionKey> {\n\t\tconst packageObj = await suiClient.core.getObject({ objectId: packageId });\n\t\tif (String(packageObj.object.version) !== '1') {\n\t\t\tthrow new InvalidPackageError(`Package ${packageId} is not the first version`);\n\t\t}\n\n\t\treturn new SessionKey({\n\t\t\taddress,\n\t\t\tpackageId,\n\t\t\tttlMin,\n\t\t\tsigner,\n\t\t\tsuiClient,\n\t\t});\n\t}\n\tisExpired(): boolean {\n\t\t// Allow 10 seconds for clock skew\n\t\treturn this.#creationTimeMs + this.#ttlMin * 60 * 1000 - 10_000 < Date.now();\n\t}\n\n\tgetAddress(): string {\n\t\treturn this.#address;\n\t}\n\n\tgetPackageName(): string {\n\t\tif (this.#mvrName) {\n\t\t\treturn this.#mvrName;\n\t\t}\n\t\treturn this.#packageId;\n\t}\n\n\tgetPackageId(): string {\n\t\treturn this.#packageId;\n\t}\n\n\tgetPersonalMessage(): Uint8Array {\n\t\tconst creationTimeUtc =\n\t\t\tnew Date(this.#creationTimeMs).toISOString().slice(0, 19).replace('T', ' ') + ' UTC';\n\t\tconst message = `Accessing keys of package ${this.getPackageName()} for ${this.#ttlMin} mins from ${creationTimeUtc}, session key ${toBase64(this.#sessionKey.getPublicKey().toRawBytes())}`;\n\t\treturn new TextEncoder().encode(message);\n\t}\n\n\tasync setPersonalMessageSignature(personalMessageSignature: string) {\n\t\tif (!this.#personalMessageSignature) {\n\t\t\ttry {\n\t\t\t\tawait verifyPersonalMessageSignature(this.getPersonalMessage(), personalMessageSignature, {\n\t\t\t\t\taddress: this.#address,\n\t\t\t\t\tclient: this.#suiClient,\n\t\t\t\t});\n\t\t\t\tthis.#personalMessageSignature = personalMessageSignature;\n\t\t\t} catch (e) {\n\t\t\t\tthrow new InvalidPersonalMessageSignatureError('Not valid');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getCertificate(): Promise<Certificate> {\n\t\tif (!this.#personalMessageSignature) {\n\t\t\tif (this.#signer) {\n\t\t\t\tconst { signature } = await this.#signer.signPersonalMessage(this.getPersonalMessage());\n\t\t\t\tthis.#personalMessageSignature = signature;\n\t\t\t} else {\n\t\t\t\tthrow new InvalidPersonalMessageSignatureError('Personal message signature is not set');\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tuser: this.#address,\n\t\t\tsession_vk: toBase64(this.#sessionKey.getPublicKey().toRawBytes()),\n\t\t\tcreation_time: this.#creationTimeMs,\n\t\t\tttl_min: this.#ttlMin,\n\t\t\tsignature: this.#personalMessageSignature,\n\t\t\tmvr_name: this.#mvrName,\n\t\t};\n\t}\n\n\tasync createRequestParams(\n\t\ttxBytes: Uint8Array,\n\t): Promise<{ decryptionKey: Uint8Array; requestSignature: string }> {\n\t\tif (this.isExpired()) {\n\t\t\tthrow new ExpiredSessionKeyError();\n\t\t}\n\t\tconst egSk = generateSecretKey();\n\t\tconst msgToSign = RequestFormat.serialize({\n\t\t\tptb: txBytes.slice(1),\n\t\t\tencKey: toPublicKey(egSk),\n\t\t\tencVerificationKey: toVerificationKey(egSk),\n\t\t}).toBytes();\n\t\treturn {\n\t\t\tdecryptionKey: egSk,\n\t\t\trequestSignature: toBase64(await this.#sessionKey.sign(msgToSign)),\n\t\t};\n\t}\n\n\t/**\n\t * Export the Session Key object from the instance. Store the object in IndexedDB to persist.\n\t */\n\texport(): SessionKeyType {\n\t\tconst obj = {\n\t\t\taddress: this.#address,\n\t\t\tpackageId: this.#packageId,\n\t\t\tmvrName: this.#mvrName,\n\t\t\tcreationTimeMs: this.#creationTimeMs,\n\t\t\tttlMin: this.#ttlMin,\n\t\t\tpersonalMessageSignature: this.#personalMessageSignature,\n\t\t\tsessionKey: this.#sessionKey.getSecretKey(), // bech32 encoded string\n\t\t};\n\n\t\tObject.defineProperty(obj, 'toJSON', {\n\t\t\tenumerable: false,\n\t\t\tvalue: () => {\n\t\t\t\tthrow new Error('This object is not serializable');\n\t\t\t},\n\t\t});\n\t\treturn obj;\n\t}\n\n\t/**\n\t * Restore a SessionKey instance for the given object.\n\t * @returns A new SessionKey instance with restored state\n\t */\n\tstatic import(\n\t\tdata: SessionKeyType,\n\t\tsuiClient: SealCompatibleClient,\n\t\tsigner?: Signer,\n\t): SessionKey {\n\t\tconst instance = new SessionKey({\n\t\t\taddress: data.address,\n\t\t\tpackageId: data.packageId,\n\t\t\tmvrName: data.mvrName,\n\t\t\tttlMin: data.ttlMin,\n\t\t\tsigner,\n\t\t\tsuiClient,\n\t\t});\n\n\t\tinstance.#creationTimeMs = data.creationTimeMs;\n\t\tinstance.#sessionKey = Ed25519Keypair.fromSecretKey(data.sessionKey);\n\t\tinstance.#personalMessageSignature = data.personalMessageSignature;\n\n\t\tif (instance.isExpired()) {\n\t\t\tthrow new ExpiredSessionKeyError();\n\t\t}\n\t\treturn instance;\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAyB;AACzB,IAAAA,cAAoB;AAEpB,qBAA+B;AAC/B,mBAA2E;AAC3E,oBAA+C;AAC/C,qBAAkE;AAClE,mBAKO;AAfP;AAkBO,MAAM,gBAAgB,gBAAI,OAAO,iBAAiB;AAAA,EACxD,KAAK,gBAAI,OAAO,gBAAI,EAAE;AAAA,EACtB,QAAQ,gBAAI,OAAO,gBAAI,EAAE;AAAA,EACzB,oBAAoB,gBAAI,OAAO,gBAAI,EAAE;AACtC,CAAC;AAqBM,MAAM,cAAN,MAAM,YAAW;AAAA;AAAA;AAAA;AAAA,EAcvB,YAAY;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD,GAOG;AA3BH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAoBC,QAAI,WAAW,KAAC,kCAAoB,OAAO,GAAG;AAC7C,YAAM,IAAI,uBAAU,wBAAwB,OAAO,EAAE;AAAA,IACtD;AACA,QAAI,KAAC,iCAAmB,SAAS,KAAK,KAAC,gCAAkB,OAAO,GAAG;AAClE,YAAM,IAAI,uBAAU,sBAAsB,SAAS,eAAe,OAAO,EAAE;AAAA,IAC5E;AACA,QAAI,SAAS,MAAM,SAAS,GAAG;AAC9B,YAAM,IAAI,uBAAU,eAAe,MAAM,4BAA4B;AAAA,IACtE;AACA,QAAI,UAAU,OAAO,aAAa,EAAE,aAAa,MAAM,SAAS;AAC/D,YAAM,IAAI,uBAAU,mDAAmD;AAAA,IACxE;AAEA,uBAAK,UAAW;AAChB,uBAAK,YAAa;AAClB,uBAAK,UAAW;AAChB,uBAAK,iBAAkB,KAAK,I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BAAK;AAAA,MACrB,QAAQ,mBAAK;AAAA,MACb,0BAA0B,mBAAK;AAAA,MAC/B,YAAY,mBAAK,aAAY,aAAa;AAAA;AAAA,IAC3C;AAEA,WAAO,eAAe,KAAK,UAAU;AAAA,MACpC,YAAY;AAAA,MACZ,OAAO,MAAM;AACZ,cAAM,IAAI,MAAM,iCAAiC;AAAA,MAClD;AAAA,IACD,CAAC;AACD,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,OACN,MACA,WACA,QACa;AACb,UAAM,WAAW,IAAI,YAAW;AAAA,MAC/B,SAAS,KAAK;AAAA,MACd,WAAW,KAAK;AAAA,MAChB,SAAS,KAAK;AAAA,MACd,QAAQ,KAAK;AAAA,MACb;AAAA,MACA;AAAA,IACD,CAAC;AAED,2BAAS,iBAAkB,KAAK;AAChC,2BAAS,aAAc,8BAAe,cAAc,KAAK,UAAU;AACnE,2BAAS,2BAA4B,KAAK;AAE1C,QAAI,SAAS,UAAU,GAAG;AACzB,YAAM,IAAI,oCAAuB;AAAA,IAClC;AACA,WAAO;AAAA,EACR;AACD;AA7MC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATM,IAAM,aAAN;",
|
|
6
6
|
"names": ["import_bcs"]
|
|
7
7
|
}
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import type { ClientWithExtensions, Experimental_CoreClient } from '@mysten/sui/experimental';
|
|
1
|
+
import type { ClientWithExtensions, Experimental_CoreClient, Experimental_SuiClientTypes } from '@mysten/sui/experimental';
|
|
2
2
|
export type KeyCacheKey = `${string}:${string}`;
|
|
3
3
|
export type SealCompatibleClient = ClientWithExtensions<{
|
|
4
|
-
core: Experimental_CoreClient
|
|
4
|
+
core: Experimental_CoreClient & {
|
|
5
|
+
verifyZkLoginSignature: NonNullable<Experimental_SuiClientTypes.TransportMethods['verifyZkLoginSignature']>;
|
|
6
|
+
};
|
|
5
7
|
}>;
|
package/dist/cjs/types.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/types.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type {
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type {\n\tClientWithExtensions,\n\tExperimental_CoreClient,\n\tExperimental_SuiClientTypes,\n} from '@mysten/sui/experimental';\n\nexport type KeyCacheKey = `${string}:${string}`;\nexport type SealCompatibleClient = ClientWithExtensions<{\n\tcore: Experimental_CoreClient & {\n\t\tverifyZkLoginSignature: NonNullable<\n\t\t\tExperimental_SuiClientTypes.TransportMethods['verifyZkLoginSignature']\n\t\t>;\n\t};\n}>;\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "0.4.
|
|
1
|
+
export declare const PACKAGE_VERSION = "0.4.11";
|
package/dist/cjs/version.js
CHANGED
package/dist/cjs/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\n// This file is generated by genversion.mjs. Do not edit it directly.\n\nexport const PACKAGE_VERSION = '0.4.
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\n// This file is generated by genversion.mjs. Do not edit it directly.\n\nexport const PACKAGE_VERSION = '0.4.11';\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,MAAM,kBAAkB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/esm/bcs.d.ts
CHANGED
|
@@ -113,16 +113,14 @@ export declare const EncryptedObject: import("@mysten/bcs").BcsType<{
|
|
|
113
113
|
}>;
|
|
114
114
|
}>;
|
|
115
115
|
/**
|
|
116
|
-
* The Move struct for the
|
|
116
|
+
* The Move struct for the KeyServerV1 object.
|
|
117
117
|
*/
|
|
118
|
-
export declare const
|
|
119
|
-
id: string;
|
|
118
|
+
export declare const KeyServerMoveV1: import("@mysten/bcs").BcsType<{
|
|
120
119
|
name: string;
|
|
121
120
|
url: string;
|
|
122
121
|
keyType: number;
|
|
123
122
|
pk: number[];
|
|
124
123
|
}, {
|
|
125
|
-
id: string | Uint8Array<ArrayBufferLike>;
|
|
126
124
|
name: string;
|
|
127
125
|
url: string;
|
|
128
126
|
keyType: number;
|
|
@@ -130,3 +128,15 @@ export declare const KeyServerMove: import("@mysten/bcs").BcsType<{
|
|
|
130
128
|
length: number;
|
|
131
129
|
};
|
|
132
130
|
}>;
|
|
131
|
+
/**
|
|
132
|
+
* The Move struct for the parent object.
|
|
133
|
+
*/
|
|
134
|
+
export declare const KeyServerMove: import("@mysten/bcs").BcsType<{
|
|
135
|
+
id: string;
|
|
136
|
+
firstVersion: string;
|
|
137
|
+
lastVersion: string;
|
|
138
|
+
}, {
|
|
139
|
+
id: string | Uint8Array<ArrayBufferLike>;
|
|
140
|
+
firstVersion: string | number | bigint;
|
|
141
|
+
lastVersion: string | number | bigint;
|
|
142
|
+
}>;
|
package/dist/esm/bcs.js
CHANGED
|
@@ -31,17 +31,24 @@ const EncryptedObject = bcs.struct("EncryptedObject", {
|
|
|
31
31
|
encryptedShares: IBEEncryptions,
|
|
32
32
|
ciphertext: Ciphertext
|
|
33
33
|
});
|
|
34
|
-
const
|
|
35
|
-
id: bcs.Address,
|
|
34
|
+
const KeyServerMoveV1 = bcs.struct("KeyServerV1", {
|
|
36
35
|
name: bcs.string(),
|
|
37
36
|
url: bcs.string(),
|
|
38
37
|
keyType: bcs.u8(),
|
|
39
38
|
pk: bcs.vector(bcs.u8())
|
|
40
39
|
});
|
|
40
|
+
const KeyServerMove = bcs.struct("KeyServer", {
|
|
41
|
+
id: bcs.Address,
|
|
42
|
+
firstVersion: bcs.u64(),
|
|
43
|
+
// latest version
|
|
44
|
+
lastVersion: bcs.u64()
|
|
45
|
+
// oldest version
|
|
46
|
+
});
|
|
41
47
|
export {
|
|
42
48
|
Ciphertext,
|
|
43
49
|
EncryptedObject,
|
|
44
50
|
IBEEncryptions,
|
|
45
|
-
KeyServerMove
|
|
51
|
+
KeyServerMove,
|
|
52
|
+
KeyServerMoveV1
|
|
46
53
|
};
|
|
47
54
|
//# sourceMappingURL=bcs.js.map
|