@mysten/seal 0.5.1 → 0.6.0

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 (54) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cjs/bls12381.d.ts +4 -4
  3. package/dist/cjs/bls12381.js +2 -2
  4. package/dist/cjs/bls12381.js.map +2 -2
  5. package/dist/cjs/client.d.ts +2 -2
  6. package/dist/cjs/client.js.map +2 -2
  7. package/dist/cjs/decrypt.js.map +1 -1
  8. package/dist/cjs/dem.d.ts +9 -9
  9. package/dist/cjs/dem.js +14 -2
  10. package/dist/cjs/dem.js.map +2 -2
  11. package/dist/cjs/elgamal.d.ts +3 -3
  12. package/dist/cjs/elgamal.js.map +2 -2
  13. package/dist/cjs/encrypt.d.ts +2 -2
  14. package/dist/cjs/encrypt.js.map +1 -1
  15. package/dist/cjs/kdf.d.ts +1 -1
  16. package/dist/cjs/kdf.js.map +2 -2
  17. package/dist/cjs/key-server.d.ts +4 -4
  18. package/dist/cjs/key-server.js +8 -6
  19. package/dist/cjs/key-server.js.map +2 -2
  20. package/dist/cjs/session-key.d.ts +3 -3
  21. package/dist/cjs/session-key.js.map +1 -1
  22. package/dist/cjs/shamir.d.ts +2 -2
  23. package/dist/cjs/shamir.js.map +2 -2
  24. package/dist/cjs/version.d.ts +1 -1
  25. package/dist/cjs/version.js +1 -1
  26. package/dist/cjs/version.js.map +1 -1
  27. package/dist/esm/bls12381.d.ts +4 -4
  28. package/dist/esm/bls12381.js +2 -2
  29. package/dist/esm/bls12381.js.map +2 -2
  30. package/dist/esm/client.d.ts +2 -2
  31. package/dist/esm/client.js.map +2 -2
  32. package/dist/esm/decrypt.js.map +1 -1
  33. package/dist/esm/dem.d.ts +9 -9
  34. package/dist/esm/dem.js +14 -2
  35. package/dist/esm/dem.js.map +2 -2
  36. package/dist/esm/elgamal.d.ts +3 -3
  37. package/dist/esm/elgamal.js.map +2 -2
  38. package/dist/esm/encrypt.d.ts +2 -2
  39. package/dist/esm/encrypt.js.map +1 -1
  40. package/dist/esm/kdf.d.ts +1 -1
  41. package/dist/esm/kdf.js.map +2 -2
  42. package/dist/esm/key-server.d.ts +4 -4
  43. package/dist/esm/key-server.js +8 -6
  44. package/dist/esm/key-server.js.map +2 -2
  45. package/dist/esm/session-key.d.ts +3 -3
  46. package/dist/esm/session-key.js.map +1 -1
  47. package/dist/esm/shamir.d.ts +2 -2
  48. package/dist/esm/shamir.js.map +2 -2
  49. package/dist/esm/version.d.ts +1 -1
  50. package/dist/esm/version.js +1 -1
  51. package/dist/esm/version.js.map +1 -1
  52. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  53. package/dist/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +5 -5
@@ -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 { bcs, fromBase64, fromHex, toBase64, toHex } from '@mysten/bcs';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { KeyServerMove, KeyServerMoveV1 } from './bcs.js';\nimport { InvalidKeyServerError, InvalidKeyServerVersionError, SealAPIError } 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';\nimport { elgamalDecrypt } from './elgamal.js';\nimport type { Certificate } from './session-key.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 * 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(await 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\tif (ksVersioned.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\tthrow new InvalidKeyServerError(\n\t\t\t\t\t`Server ${objectId} has invalid key type: ${ksVersioned.keyType}`,\n\t\t\t\t);\n\t\t\t}\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\n/**\n * Options for fetching keys from the key server.\n */\nexport interface FetchKeysOptions {\n\t/** The URL of the key server. */\n\turl: string;\n\t/** The Base64 string of request signature. */\n\trequestSignature: string;\n\t/** The transaction bytes. */\n\ttransactionBytes: Uint8Array;\n\t/** The ephemeral secret key. */\n\tencKey: Uint8Array;\n\t/** The ephemeral public key. */\n\tencKeyPk: Uint8Array;\n\t/** The ephemeral verification key. */\n\tencVerificationKey: Uint8Array;\n\t/** The certificate. */\n\tcertificate: Certificate;\n\t/** Request timeout in milliseconds. */\n\ttimeout: number;\n\t/** Optional API key name. */\n\tapiKeyName?: string;\n\t/** Optional API key. */\n\tapiKey?: string;\n\t/** Optional abort signal for cancellation. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * Helper function to request all keys from URL with requestSig, txBytes, ephemeral pubkey.\n * Then decrypt the Seal key with ephemeral secret key. Returns a list decryption keys with\n * their full IDs.\n *\n * @param url - The URL of the key server.\n * @param requestSig - The Base64 string of request signature.\n * @param txBytes - The transaction bytes.\n * @param encKey - The ephemeral secret key.\n * @param certificate - The certificate.\n * @returns - A list of full ID and the decrypted key.\n */\nexport async function fetchKeysForAllIds({\n\turl,\n\trequestSignature,\n\ttransactionBytes,\n\tencKey,\n\tencKeyPk,\n\tencVerificationKey,\n\tcertificate,\n\ttimeout,\n\tapiKeyName,\n\tapiKey,\n\tsignal,\n}: FetchKeysOptions): Promise<{ fullId: string; key: Uint8Array }[]> {\n\tconst body = {\n\t\tptb: toBase64(transactionBytes.slice(1)), // removes the byte of the transaction type version\n\t\tenc_key: toBase64(encKeyPk),\n\t\tenc_verification_key: toBase64(encVerificationKey),\n\t\trequest_signature: requestSignature, // already b64\n\t\tcertificate,\n\t};\n\n\tconst timeoutSignal = AbortSignal.timeout(timeout);\n\tconst combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;\n\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(url + '/v1/fetch_key', {\n\t\tmethod: 'POST',\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\tbody: JSON.stringify(body),\n\t\tsignal: combinedSignal,\n\t});\n\tawait SealAPIError.assertResponse(response, requestId);\n\tconst resp = await response.json();\n\tverifyKeyServerVersion(response);\n\n\treturn resp.decryption_keys.map((dk: { id: Uint8Array; encrypted_key: [string, string] }) => ({\n\t\tfullId: toHex(dk.id),\n\t\tkey: elgamalDecrypt(encKey, dk.encrypted_key.map(fromBase64) as [Uint8Array, Uint8Array]),\n\t}));\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,iBAA0D;AAC1D,uBAA0B;AAE1B,IAAAA,cAA+C;AAC/C,mBAAkF;AAClF,iBAAwB;AACxB,qBAAgC;AAGhC,mBAAiC;AACjC,qBAA+B;AAG/B,MAAM,0BAA0B;AAUzB,IAAK,gBAAL,kBAAKC,mBAAL;AACN,EAAAA,8BAAA,2BAAwB,KAAxB;AADW,SAAAA;AAAA,GAAA;AAIL,MAAM,6BAA6B,IAAI,qBAAQ,OAAO;AAU7D,eAAsB,mBAAmB;AAAA,EACxC;AAAA,EACA;AACD,GAGyB;AACxB,SAAO,MAAM,QAAQ;AAAA,IACpB,UAAU,IAAI,OAAO,aAAa;AAEjC,YAAM,MAAM,MAAM,OAAO,KAAK,UAAU;AAAA,QACvC;AAAA,MACD,CAAC;AACD,YAAM,KAAK,0BAAc,MAAM,MAAM,IAAI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;AAAA,IACR,SAAS;AAAA,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,MAAM,KAAK,UAAU,IAAI;AAAA,IACzB,QAAQ;AAAA,EACT,CAAC;AACD,QAAM,0BAAa,eAAe,UAAU,SAAS;AACrD,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,yBAAuB,QAAQ;AAE/B,SAAO,KAAK,gBAAgB,IAAI,CAAC,QAA6D;AAAA,IAC7F,YAAQ,kBAAM,GAAG,EAAE;AAAA,IACnB,SAAK,+BAAe,QAAQ,GAAG,cAAc,IAAI,qBAAU,CAA6B;AAAA,EACzF,EAAE;AACH;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { bcs, fromBase64, fromHex, toBase64, toHex } from '@mysten/bcs';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { KeyServerMove, KeyServerMoveV1 } from './bcs.js';\nimport { InvalidKeyServerError, InvalidKeyServerVersionError, SealAPIError } 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';\nimport { elgamalDecrypt } from './elgamal.js';\nimport type { Certificate } from './session-key.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<ArrayBuffer>;\n};\n\nexport enum KeyServerType {\n\tBonehFranklinBLS12381 = 0,\n}\n\nexport const SERVER_VERSION_REQUIREMENT = new Version('0.4.1');\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(await 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\tif (ksVersioned.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\tthrow new InvalidKeyServerError(\n\t\t\t\t\t`Server ${objectId} has invalid key type: ${ksVersioned.keyType}`,\n\t\t\t\t);\n\t\t\t}\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\n/**\n * Options for fetching keys from the key server.\n */\nexport interface FetchKeysOptions {\n\t/** The URL of the key server. */\n\turl: string;\n\t/** The Base64 string of request signature. */\n\trequestSignature: string;\n\t/** The transaction bytes. */\n\ttransactionBytes: Uint8Array;\n\t/** The ephemeral secret key. */\n\tencKey: Uint8Array<ArrayBuffer>;\n\t/** The ephemeral public key. */\n\tencKeyPk: Uint8Array<ArrayBuffer>;\n\t/** The ephemeral verification key. */\n\tencVerificationKey: Uint8Array;\n\t/** The certificate. */\n\tcertificate: Certificate;\n\t/** Request timeout in milliseconds. */\n\ttimeout: number;\n\t/** Optional API key name. */\n\tapiKeyName?: string;\n\t/** Optional API key. */\n\tapiKey?: string;\n\t/** Optional abort signal for cancellation. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * Helper function to request all keys from URL with requestSig, txBytes, ephemeral pubkey.\n * Then decrypt the Seal key with ephemeral secret key. Returns a list decryption keys with\n * their full IDs.\n *\n * @param url - The URL of the key server.\n * @param requestSig - The Base64 string of request signature.\n * @param txBytes - The transaction bytes.\n * @param encKey - The ephemeral secret key.\n * @param certificate - The certificate.\n * @returns - A list of full ID and the decrypted key.\n */\nexport async function fetchKeysForAllIds({\n\turl,\n\trequestSignature,\n\ttransactionBytes,\n\tencKey,\n\tencKeyPk,\n\tencVerificationKey,\n\tcertificate,\n\ttimeout,\n\tapiKeyName,\n\tapiKey,\n\tsignal,\n}: FetchKeysOptions): Promise<{ fullId: string; key: Uint8Array<ArrayBuffer> }[]> {\n\tconst body = {\n\t\tptb: toBase64(transactionBytes.slice(1)), // removes the byte of the transaction type version\n\t\tenc_key: toBase64(encKeyPk),\n\t\tenc_verification_key: toBase64(encVerificationKey),\n\t\trequest_signature: requestSignature, // already b64\n\t\tcertificate,\n\t};\n\n\tconst timeoutSignal = AbortSignal.timeout(timeout);\n\tconst combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;\n\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(url + '/v1/fetch_key', {\n\t\tmethod: 'POST',\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\tbody: JSON.stringify(body),\n\t\tsignal: combinedSignal,\n\t});\n\tawait SealAPIError.assertResponse(response, requestId);\n\tconst resp = await response.json();\n\tverifyKeyServerVersion(response);\n\n\treturn resp.decryption_keys.map(\n\t\t(dk: { id: Uint8Array<ArrayBuffer>; encrypted_key: [string, string] }) => ({\n\t\t\tfullId: toHex(dk.id),\n\t\t\tkey: elgamalDecrypt(encKey, dk.encrypted_key.map(fromBase64) as [Uint8Array, Uint8Array]),\n\t\t}),\n\t);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,iBAA0D;AAC1D,uBAA0B;AAE1B,IAAAA,cAA+C;AAC/C,mBAAkF;AAClF,iBAAwB;AACxB,qBAAgC;AAGhC,mBAAiC;AACjC,qBAA+B;AAG/B,MAAM,0BAA0B;AAUzB,IAAK,gBAAL,kBAAKC,mBAAL;AACN,EAAAA,8BAAA,2BAAwB,KAAxB;AADW,SAAAA;AAAA,GAAA;AAIL,MAAM,6BAA6B,IAAI,qBAAQ,OAAO;AAU7D,eAAsB,mBAAmB;AAAA,EACxC;AAAA,EACA;AACD,GAGyB;AACxB,SAAO,MAAM,QAAQ;AAAA,IACpB,UAAU,IAAI,OAAO,aAAa;AAEjC,YAAM,MAAM,MAAM,OAAO,KAAK,UAAU;AAAA,QACvC;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,WAAW;AACpC,QAAM,WAAW,MAAM,MAAM,MAAM,iBAAiB;AAAA,IACnD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,cAAc;AAAA,MACd,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,MACtB,GAAI,cAAc,SAAS,EAAE,CAAC,UAAU,GAAG,OAAO,IAAI,CAAC;AAAA,IACxD;AAAA,IACA,MAAM,KAAK,UAAU,IAAI;AAAA,IACzB,QAAQ;AAAA,EACT,CAAC;AACD,QAAM,0BAAa,eAAe,UAAU,SAAS;AACrD,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,yBAAuB,QAAQ;AAE/B,SAAO,KAAK,gBAAgB;AAAA,IAC3B,CAAC,QAA0E;AAAA,MAC1E,YAAQ,kBAAM,GAAG,EAAE;AAAA,MACnB,SAAK,+BAAe,QAAQ,GAAG,cAAc,IAAI,qBAAU,CAA6B;AAAA,IACzF;AAAA,EACD;AACD;",
6
6
  "names": ["import_bcs", "KeyServerType"]
7
7
  }
@@ -63,9 +63,9 @@ export declare class SessionKey {
63
63
  * its public key and its verification key.
64
64
  */
65
65
  createRequestParams(txBytes: Uint8Array): Promise<{
66
- encKey: Uint8Array;
67
- encKeyPk: Uint8Array;
68
- encVerificationKey: Uint8Array;
66
+ encKey: Uint8Array<ArrayBuffer>;
67
+ encKeyPk: Uint8Array<ArrayBuffer>;
68
+ encVerificationKey: Uint8Array<ArrayBuffer>;
69
69
  requestSignature: string;
70
70
  }>;
71
71
  /**
@@ -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\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 ExportedSessionKey = {\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\tprivate constructor({\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\t/**\n\t * Create a new SessionKey instance.\n\t * @param address - The address of the user.\n\t * @param packageId - The ID of the package.\n\t * @param mvrName - Optional. The name of the MVR, if there is one.\n\t * @param ttlMin - The TTL in minutes.\n\t * @param signer - Optional. The signer instance, e.g. EnokiSigner.\n\t * @param suiClient - The Sui client.\n\t * @returns A new SessionKey instance.\n\t */\n\tstatic async create({\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}): 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\tmvrName,\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\t/**\n\t * Create request params for the given transaction bytes.\n\t * @param txBytes - The transaction bytes.\n\t * @returns The request params containing the ephemeral secret key,\n\t * its public key and its verification key.\n\t */\n\tasync createRequestParams(txBytes: Uint8Array): Promise<{\n\t\tencKey: Uint8Array;\n\t\tencKeyPk: Uint8Array;\n\t\tencVerificationKey: Uint8Array;\n\t\trequestSignature: string;\n\t}> {\n\t\tif (this.isExpired()) {\n\t\t\tthrow new ExpiredSessionKeyError();\n\t\t}\n\t\tconst encKey = generateSecretKey();\n\t\tconst encKeyPk = toPublicKey(encKey);\n\t\tconst encVerificationKey = toVerificationKey(encKey);\n\n\t\tconst msgToSign = RequestFormat.serialize({\n\t\t\tptb: txBytes.slice(1),\n\t\t\tencKey: encKeyPk,\n\t\t\tencVerificationKey,\n\t\t}).toBytes();\n\t\treturn {\n\t\t\tencKey,\n\t\t\tencKeyPk,\n\t\t\tencVerificationKey,\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(): ExportedSessionKey {\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: ExportedSessionKey,\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"],
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 ExportedSessionKey = {\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\tprivate constructor({\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\t/**\n\t * Create a new SessionKey instance.\n\t * @param address - The address of the user.\n\t * @param packageId - The ID of the package.\n\t * @param mvrName - Optional. The name of the MVR, if there is one.\n\t * @param ttlMin - The TTL in minutes.\n\t * @param signer - Optional. The signer instance, e.g. EnokiSigner.\n\t * @param suiClient - The Sui client.\n\t * @returns A new SessionKey instance.\n\t */\n\tstatic async create({\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}): 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\tmvrName,\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\t/**\n\t * Create request params for the given transaction bytes.\n\t * @param txBytes - The transaction bytes.\n\t * @returns The request params containing the ephemeral secret key,\n\t * its public key and its verification key.\n\t */\n\tasync createRequestParams(txBytes: Uint8Array): Promise<{\n\t\tencKey: Uint8Array<ArrayBuffer>;\n\t\tencKeyPk: Uint8Array<ArrayBuffer>;\n\t\tencVerificationKey: Uint8Array<ArrayBuffer>;\n\t\trequestSignature: string;\n\t}> {\n\t\tif (this.isExpired()) {\n\t\t\tthrow new ExpiredSessionKeyError();\n\t\t}\n\t\tconst encKey = generateSecretKey();\n\t\tconst encKeyPk = toPublicKey(encKey);\n\t\tconst encVerificationKey = toVerificationKey(encKey);\n\n\t\tconst msgToSign = RequestFormat.serialize({\n\t\t\tptb: txBytes.slice(1),\n\t\t\tencKey: encKeyPk,\n\t\t\tencVerificationKey,\n\t\t}).toBytes();\n\t\treturn {\n\t\t\tencKey,\n\t\t\tencKeyPk,\n\t\t\tencVerificationKey,\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(): ExportedSessionKey {\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: ExportedSessionKey,\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
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,GAAG,CAAC;AAAA,EACxB,QAAQ,gBAAI,OAAO,gBAAI,GAAG,CAAC;AAAA,EAC3B,oBAAoB,gBAAI,OAAO,gBAAI,GAAG,CAAC;AACxC,CAAC;AAqBM,MAAM,cAAN,MAAM,YAAW;AAAA,EAWf,YAAY;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA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,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;AArOC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATM,IAAM,aAAN;",
6
6
  "names": ["import_bcs"]
7
7
  }
@@ -51,7 +51,7 @@ export declare class Polynomial {
51
51
  /** Representation of a share of a secret. The index is a number between 1 and 255. */
52
52
  export type Share = {
53
53
  index: number;
54
- share: Uint8Array;
54
+ share: Uint8Array<ArrayBuffer>;
55
55
  };
56
56
  /**
57
57
  * Split a secret into shares.
@@ -69,7 +69,7 @@ export declare function split(secret: Uint8Array, threshold: number, total: numb
69
69
  * @param shares The shares to combine.
70
70
  * @returns The secret.
71
71
  */
72
- export declare function combine(shares: Share[]): Uint8Array;
72
+ export declare function combine(shares: Share[]): Uint8Array<ArrayBuffer>;
73
73
  /**
74
74
  * Interpolate a polynomial from the given shares.
75
75
  *
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/shamir.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { allEqual, hasDuplicates } from './utils.js';\n\nconst GF256_SIZE = 256;\n\n/**\n * A field element in the Rijndael finite field GF(2\u2078) with a fixed generator g = 0x03.\n */\nexport class GF256 {\n\tvalue: number;\n\n\tconstructor(value: number) {\n\t\tif (value < 0 || value >= GF256_SIZE) {\n\t\t\tthrow new Error(`Invalid value ${value} for GF256`);\n\t\t}\n\t\tthis.value = value;\n\t}\n\n\tlog(): number {\n\t\tif (this.value === 0) {\n\t\t\tthrow new Error('Invalid value');\n\t\t}\n\t\treturn LOG[this.value - 1];\n\t}\n\n\tstatic exp(x: number): GF256 {\n\t\treturn new GF256(EXP[x % (GF256_SIZE - 1)]);\n\t}\n\n\tadd(other: GF256): GF256 {\n\t\treturn new GF256(this.value ^ other.value);\n\t}\n\n\tsub(other: GF256): GF256 {\n\t\t// Addition is the same as subtraction in a binary field.\n\t\treturn this.add(other);\n\t}\n\n\tneg(): GF256 {\n\t\t// Negation doesn't change the value in a binary field.\n\t\treturn this;\n\t}\n\n\tmul(other: GF256): GF256 {\n\t\tif (this.value === 0 || other.value === 0) {\n\t\t\treturn new GF256(0);\n\t\t}\n\t\treturn GF256.exp(this.log() + other.log());\n\t}\n\n\tdiv(other: GF256): GF256 {\n\t\treturn this.mul(GF256.exp(GF256_SIZE - other.log() - 1));\n\t}\n\n\tequals(other: GF256): boolean {\n\t\treturn this.value === other.value;\n\t}\n\n\tstatic zero(): GF256 {\n\t\treturn new GF256(0);\n\t}\n\n\tstatic one(): GF256 {\n\t\treturn new GF256(1);\n\t}\n}\n\n/// Table of E\u1D62 = g\u2071 where g = 0x03 generates the multiplicative group of the field.\nconst EXP: number[] = [\n\t0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35,\n\t0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa,\n\t0xe5, 0x34, 0x5c, 0xe4, 0x37, 0x59, 0xeb, 0x26, 0x6a, 0xbe, 0xd9, 0x70, 0x90, 0xab, 0xe6, 0x31,\n\t0x53, 0xf5, 0x04, 0x0c, 0x14, 0x3c, 0x44, 0xcc, 0x4f, 0xd1, 0x68, 0xb8, 0xd3, 0x6e, 0xb2, 0xcd,\n\t0x4c, 0xd4, 0x67, 0xa9, 0xe0, 0x3b, 0x4d, 0xd7, 0x62, 0xa6, 0xf1, 0x08, 0x18, 0x28, 0x78, 0x88,\n\t0x83, 0x9e, 0xb9, 0xd0, 0x6b, 0xbd, 0xdc, 0x7f, 0x81, 0x98, 0xb3, 0xce, 0x49, 0xdb, 0x76, 0x9a,\n\t0xb5, 0xc4, 0x57, 0xf9, 0x10, 0x30, 0x50, 0xf0, 0x0b, 0x1d, 0x27, 0x69, 0xbb, 0xd6, 0x61, 0xa3,\n\t0xfe, 0x19, 0x2b, 0x7d, 0x87, 0x92, 0xad, 0xec, 0x2f, 0x71, 0x93, 0xae, 0xe9, 0x20, 0x60, 0xa0,\n\t0xfb, 0x16, 0x3a, 0x4e, 0xd2, 0x6d, 0xb7, 0xc2, 0x5d, 0xe7, 0x32, 0x56, 0xfa, 0x15, 0x3f, 0x41,\n\t0xc3, 0x5e, 0xe2, 0x3d, 0x47, 0xc9, 0x40, 0xc0, 0x5b, 0xed, 0x2c, 0x74, 0x9c, 0xbf, 0xda, 0x75,\n\t0x9f, 0xba, 0xd5, 0x64, 0xac, 0xef, 0x2a, 0x7e, 0x82, 0x9d, 0xbc, 0xdf, 0x7a, 0x8e, 0x89, 0x80,\n\t0x9b, 0xb6, 0xc1, 0x58, 0xe8, 0x23, 0x65, 0xaf, 0xea, 0x25, 0x6f, 0xb1, 0xc8, 0x43, 0xc5, 0x54,\n\t0xfc, 0x1f, 0x21, 0x63, 0xa5, 0xf4, 0x07, 0x09, 0x1b, 0x2d, 0x77, 0x99, 0xb0, 0xcb, 0x46, 0xca,\n\t0x45, 0xcf, 0x4a, 0xde, 0x79, 0x8b, 0x86, 0x91, 0xa8, 0xe3, 0x3e, 0x42, 0xc6, 0x51, 0xf3, 0x0e,\n\t0x12, 0x36, 0x5a, 0xee, 0x29, 0x7b, 0x8d, 0x8c, 0x8f, 0x8a, 0x85, 0x94, 0xa7, 0xf2, 0x0d, 0x17,\n\t0x39, 0x4b, 0xdd, 0x7c, 0x84, 0x97, 0xa2, 0xfd, 0x1c, 0x24, 0x6c, 0xb4, 0xc7, 0x52, 0xf6,\n];\n\n/// Table of L\u1D62 = LOG[i + 1] such that g^L\u1D62 = i where g = 0x03.\nconst LOG: number[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 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97,\n\t0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53,\n\t0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44,\n\t0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67,\n\t0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07,\n];\n\nexport class Polynomial {\n\tcoefficients: GF256[];\n\n\t/**\n\t * Construct a new Polynomial over [GF256] from the given coefficients.\n\t * The first coefficient is the constant term.\n\t */\n\tconstructor(coefficients: GF256[]) {\n\t\tthis.coefficients = coefficients.slice();\n\n\t\t// The highest degree coefficient is always non-zero.\n\t\twhile (\n\t\t\tthis.coefficients.length > 0 &&\n\t\t\tthis.coefficients[this.coefficients.length - 1].value === 0\n\t\t) {\n\t\t\tthis.coefficients.pop();\n\t\t}\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): Polynomial {\n\t\treturn new Polynomial(Array.from(bytes, (b) => new GF256(b)));\n\t}\n\n\tdegree(): number {\n\t\tif (this.coefficients.length === 0) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn this.coefficients.length - 1;\n\t}\n\n\tgetCoefficient(index: number): GF256 {\n\t\tif (index >= this.coefficients.length) {\n\t\t\treturn GF256.zero();\n\t\t}\n\t\treturn this.coefficients[index];\n\t}\n\n\tadd(other: Polynomial): Polynomial {\n\t\tconst degree = Math.max(this.degree(), other.degree());\n\t\treturn new Polynomial(\n\t\t\tArray.from({ length: degree + 1 }, (_, i) =>\n\t\t\t\tthis.getCoefficient(i).add(other.getCoefficient(i)),\n\t\t\t),\n\t\t);\n\t}\n\n\tmul(other: Polynomial): Polynomial {\n\t\tconst degree = this.degree() + other.degree();\n\t\treturn new Polynomial(\n\t\t\tArray.from({ length: degree + 1 }, (_, i) => {\n\t\t\t\tlet sum = GF256.zero();\n\t\t\t\tfor (let j = 0; j <= i; j++) {\n\t\t\t\t\tif (j <= this.degree() && i - j <= other.degree()) {\n\t\t\t\t\t\tsum = sum.add(this.getCoefficient(j).mul(other.getCoefficient(i - j)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn sum;\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** The polynomial s * this. */\n\tscale(s: GF256): Polynomial {\n\t\treturn new Polynomial(this.coefficients.map((c) => c.mul(s)));\n\t}\n\n\tdiv(s: GF256): Polynomial {\n\t\treturn this.scale(new GF256(1).div(s));\n\t}\n\n\t/** The polynomial x + c. */\n\tstatic monic_linear(c: GF256): Polynomial {\n\t\treturn new Polynomial([c, GF256.one()]);\n\t}\n\n\tstatic zero(): Polynomial {\n\t\treturn new Polynomial([]);\n\t}\n\n\tstatic one(): Polynomial {\n\t\treturn new Polynomial([GF256.one()]);\n\t}\n\n\t/** Given a set of coordinates, interpolate a polynomial. */\n\tstatic interpolate(coordinates: { x: GF256; y: GF256 }[]): Polynomial {\n\t\tif (coordinates.length < 1) {\n\t\t\tthrow new Error('At least one coefficient is required');\n\t\t}\n\n\t\tif (hasDuplicates(coordinates.map(({ x }) => x.value))) {\n\t\t\tthrow new Error('Coefficients must have unique x values');\n\t\t}\n\n\t\treturn coordinates.reduce(\n\t\t\t(sum, { x: x_j, y: y_j }, j) =>\n\t\t\t\tsum.add(\n\t\t\t\t\tcoordinates\n\t\t\t\t\t\t.filter((_, i) => i !== j)\n\t\t\t\t\t\t.reduce(\n\t\t\t\t\t\t\t(product, { x: x_i }) =>\n\t\t\t\t\t\t\t\tproduct.mul(Polynomial.monic_linear(x_i.neg()).div(x_j.sub(x_i))),\n\t\t\t\t\t\t\tPolynomial.one(),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.scale(y_j),\n\t\t\t\t),\n\t\t\tPolynomial.zero(),\n\t\t);\n\t}\n\n\t/** Given a set of coordinates, interpolate a polynomial and evaluate it at x = 0. */\n\tstatic combine(coordinates: { x: GF256; y: GF256 }[]): GF256 {\n\t\tif (coordinates.length < 1) {\n\t\t\tthrow new Error('At least one coefficient is required');\n\t\t}\n\n\t\tif (hasDuplicates(coordinates.map(({ x }) => x.value))) {\n\t\t\tthrow new Error('Coefficients must have unique x values');\n\t\t}\n\n\t\tconst quotient: GF256 = coordinates.reduce((sum, { x: x_j, y: y_j }, j) => {\n\t\t\tconst denominator = x_j.mul(\n\t\t\t\tcoordinates\n\t\t\t\t\t.filter((_, i) => i !== j)\n\t\t\t\t\t.reduce((product, { x: x_i }) => product.mul(x_i.sub(x_j)), GF256.one()),\n\t\t\t);\n\t\t\treturn sum.add(y_j.div(denominator));\n\t\t}, GF256.zero());\n\n\t\tconst xProduct = coordinates.reduce((product, { x }) => product.mul(x), GF256.one());\n\t\treturn xProduct.mul(quotient);\n\t}\n\n\t/** Evaluate the polynomial at x. */\n\tevaluate(x: GF256): GF256 {\n\t\treturn this.coefficients\n\t\t\t.toReversed()\n\t\t\t.reduce((sum, coefficient) => sum.mul(x).add(coefficient), GF256.zero());\n\t}\n\n\tequals(other: Polynomial): boolean {\n\t\tif (this.coefficients.length !== other.coefficients.length) {\n\t\t\treturn false;\n\t\t}\n\t\treturn this.coefficients.every((c, i) => c.equals(other.getCoefficient(i)));\n\t}\n}\n\n/** Representation of a share of a secret. The index is a number between 1 and 255. */\nexport type Share = {\n\tindex: number;\n\tshare: Uint8Array;\n};\n\nfunction toInternalShare(share: Share): InternalShare {\n\treturn {\n\t\tindex: new GF256(share.index),\n\t\tshare: Array.from(share.share, (byte) => new GF256(byte)),\n\t};\n}\n\n/** Internal representation of a share of a secret. The index is a non-zero GF256. */\ntype InternalShare = {\n\tindex: GF256;\n\tshare: GF256[];\n};\n\nfunction toShare(internalShare: InternalShare): Share {\n\treturn {\n\t\tindex: internalShare.index.value,\n\t\tshare: new Uint8Array(internalShare.share.map((byte) => byte.value)),\n\t};\n}\n\n/**\n * Sample a random polynomial with the given constant and degree.\n *\n * @param constant The constant term of the polynomial.\n * @param degree The degree of the polynomial.\n * @returns A random polynomial with the given constant and degree.\n */\nfunction samplePolynomial(constant: GF256, degree: number): Polynomial {\n\tconst randomCoefficients = new Uint8Array(degree);\n\tcrypto.getRandomValues(randomCoefficients);\n\n\t// The resulting polynomial has degree + 1 coefficients.\n\treturn Polynomial.fromBytes(new Uint8Array([constant.value, ...randomCoefficients]));\n}\n\n/**\n * Split a secret into shares.\n *\n * @param secret The secret to split.\n * @param threshold The minimum number of shares required to reconstruct the secret.\n * @param total The total number of shares to generate.\n * @returns The shares.\n */\nexport function split(secret: Uint8Array, threshold: number, total: number): Share[] {\n\tif (threshold > total || threshold < 1 || total >= GF256_SIZE) {\n\t\tthrow new Error(`Invalid threshold ${threshold} or total ${total}`);\n\t}\n\n\tconst polynomials = Array.from(secret, (s) => samplePolynomial(new GF256(s), threshold - 1));\n\treturn Array.from({ length: total }, (_, i) => {\n\t\t// Indexes start at 1 because 0 is reserved for the constant term (which is also the secret).\n\t\tconst index = new GF256(i + 1);\n\t\tconst share = polynomials.map((p) => p.evaluate(index));\n\t\treturn toShare({ index, share });\n\t});\n}\n\n/** Validate a set of shares and return them in internal shares representation along with the length of the shares. */\nfunction validateShares(shares: Share[]): { internalShares: InternalShare[]; length: number } {\n\tif (shares.length < 1) {\n\t\tthrow new Error('At least one share is required');\n\t}\n\n\tif (!allEqual(shares.map(({ share }) => share.length))) {\n\t\tthrow new Error('All shares must have the same length');\n\t}\n\n\tif (hasDuplicates(shares.map(({ index }) => index))) {\n\t\tthrow new Error('Shares must have unique indices');\n\t}\n\n\tconst internalShares = shares.map(toInternalShare);\n\tconst length = internalShares[0].share.length;\n\n\treturn { internalShares, length };\n}\n\n/**\n * Combine shares into a secret. If fewer than the threshold number of shares are provided,\n * the result will be indistinguishable from random.\n *\n * @param shares The shares to combine.\n * @returns The secret.\n */\nexport function combine(shares: Share[]): Uint8Array {\n\tconst { internalShares, length } = validateShares(shares);\n\n\treturn new Uint8Array(\n\t\tArray.from(\n\t\t\t{ length },\n\t\t\t(_, i) =>\n\t\t\t\tPolynomial.combine(\n\t\t\t\t\tinternalShares.map(({ index, share }) => ({\n\t\t\t\t\t\tx: index,\n\t\t\t\t\t\ty: share[i],\n\t\t\t\t\t})),\n\t\t\t\t).value,\n\t\t),\n\t);\n}\n\n/**\n * Interpolate a polynomial from the given shares.\n *\n * @param shares The shares to interpolate from.\n * @returns A function that evaluates the polynomial at a given x.\n */\nexport function interpolate(shares: Share[]): (x: number) => Uint8Array {\n\tconst { internalShares, length } = validateShares(shares);\n\n\tconst polynomials = Array.from({ length }, (_, i) =>\n\t\tPolynomial.interpolate(internalShares.map(({ index, share }) => ({ x: index, y: share[i] }))),\n\t);\n\n\treturn (x: number) => {\n\t\treturn new Uint8Array(polynomials.map((p) => p.evaluate(new GF256(x)).value));\n\t};\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAwC;AAExC,MAAM,aAAa;AAKZ,MAAM,MAAM;AAAA,EAGlB,YAAY,OAAe;AAC1B,QAAI,QAAQ,KAAK,SAAS,YAAY;AACrC,YAAM,IAAI,MAAM,iBAAiB,KAAK,YAAY;AAAA,IACnD;AACA,SAAK,QAAQ;AAAA,EACd;AAAA,EAEA,MAAc;AACb,QAAI,KAAK,UAAU,GAAG;AACrB,YAAM,IAAI,MAAM,eAAe;AAAA,IAChC;AACA,WAAO,IAAI,KAAK,QAAQ,CAAC;AAAA,EAC1B;AAAA,EAEA,OAAO,IAAI,GAAkB;AAC5B,WAAO,IAAI,MAAM,IAAI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OAAO;AAAA,UACzC,GAAG;AAAA,UACH,GAAG,MAAM,CAAC;AAAA,QACX,EAAE;AAAA,MACH,EAAE;AAAA,IACJ;AAAA,EACD;AACD;AAQO,SAAS,YAAY,QAA4C;AACvE,QAAM,EAAE,gBAAgB,OAAO,IAAI,eAAe,MAAM;AAExD,QAAM,cAAc,MAAM;AAAA,IAAK,EAAE,OAAO;AAAA,IAAG,CAAC,GAAG,MAC9C,WAAW,YAAY,eAAe,IAAI,CAAC,EAAE,OAAO,MAAM,OAAO,EAAE,GAAG,OAAO,GAAG,MAAM,CAAC,EAAE,EAAE,CAAC;AAAA,EAC7F;AAEA,SAAO,CAAC,MAAc;AACrB,WAAO,IAAI,WAAW,YAAY,IAAI,CAAC,MAAM,EAAE,SAAS,IAAI,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC;AAAA,EAC7E;AACD;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { allEqual, hasDuplicates } from './utils.js';\n\nconst GF256_SIZE = 256;\n\n/**\n * A field element in the Rijndael finite field GF(2\u2078) with a fixed generator g = 0x03.\n */\nexport class GF256 {\n\tvalue: number;\n\n\tconstructor(value: number) {\n\t\tif (value < 0 || value >= GF256_SIZE) {\n\t\t\tthrow new Error(`Invalid value ${value} for GF256`);\n\t\t}\n\t\tthis.value = value;\n\t}\n\n\tlog(): number {\n\t\tif (this.value === 0) {\n\t\t\tthrow new Error('Invalid value');\n\t\t}\n\t\treturn LOG[this.value - 1];\n\t}\n\n\tstatic exp(x: number): GF256 {\n\t\treturn new GF256(EXP[x % (GF256_SIZE - 1)]);\n\t}\n\n\tadd(other: GF256): GF256 {\n\t\treturn new GF256(this.value ^ other.value);\n\t}\n\n\tsub(other: GF256): GF256 {\n\t\t// Addition is the same as subtraction in a binary field.\n\t\treturn this.add(other);\n\t}\n\n\tneg(): GF256 {\n\t\t// Negation doesn't change the value in a binary field.\n\t\treturn this;\n\t}\n\n\tmul(other: GF256): GF256 {\n\t\tif (this.value === 0 || other.value === 0) {\n\t\t\treturn new GF256(0);\n\t\t}\n\t\treturn GF256.exp(this.log() + other.log());\n\t}\n\n\tdiv(other: GF256): GF256 {\n\t\treturn this.mul(GF256.exp(GF256_SIZE - other.log() - 1));\n\t}\n\n\tequals(other: GF256): boolean {\n\t\treturn this.value === other.value;\n\t}\n\n\tstatic zero(): GF256 {\n\t\treturn new GF256(0);\n\t}\n\n\tstatic one(): GF256 {\n\t\treturn new GF256(1);\n\t}\n}\n\n/// Table of E\u1D62 = g\u2071 where g = 0x03 generates the multiplicative group of the field.\nconst EXP: number[] = [\n\t0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35,\n\t0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa,\n\t0xe5, 0x34, 0x5c, 0xe4, 0x37, 0x59, 0xeb, 0x26, 0x6a, 0xbe, 0xd9, 0x70, 0x90, 0xab, 0xe6, 0x31,\n\t0x53, 0xf5, 0x04, 0x0c, 0x14, 0x3c, 0x44, 0xcc, 0x4f, 0xd1, 0x68, 0xb8, 0xd3, 0x6e, 0xb2, 0xcd,\n\t0x4c, 0xd4, 0x67, 0xa9, 0xe0, 0x3b, 0x4d, 0xd7, 0x62, 0xa6, 0xf1, 0x08, 0x18, 0x28, 0x78, 0x88,\n\t0x83, 0x9e, 0xb9, 0xd0, 0x6b, 0xbd, 0xdc, 0x7f, 0x81, 0x98, 0xb3, 0xce, 0x49, 0xdb, 0x76, 0x9a,\n\t0xb5, 0xc4, 0x57, 0xf9, 0x10, 0x30, 0x50, 0xf0, 0x0b, 0x1d, 0x27, 0x69, 0xbb, 0xd6, 0x61, 0xa3,\n\t0xfe, 0x19, 0x2b, 0x7d, 0x87, 0x92, 0xad, 0xec, 0x2f, 0x71, 0x93, 0xae, 0xe9, 0x20, 0x60, 0xa0,\n\t0xfb, 0x16, 0x3a, 0x4e, 0xd2, 0x6d, 0xb7, 0xc2, 0x5d, 0xe7, 0x32, 0x56, 0xfa, 0x15, 0x3f, 0x41,\n\t0xc3, 0x5e, 0xe2, 0x3d, 0x47, 0xc9, 0x40, 0xc0, 0x5b, 0xed, 0x2c, 0x74, 0x9c, 0xbf, 0xda, 0x75,\n\t0x9f, 0xba, 0xd5, 0x64, 0xac, 0xef, 0x2a, 0x7e, 0x82, 0x9d, 0xbc, 0xdf, 0x7a, 0x8e, 0x89, 0x80,\n\t0x9b, 0xb6, 0xc1, 0x58, 0xe8, 0x23, 0x65, 0xaf, 0xea, 0x25, 0x6f, 0xb1, 0xc8, 0x43, 0xc5, 0x54,\n\t0xfc, 0x1f, 0x21, 0x63, 0xa5, 0xf4, 0x07, 0x09, 0x1b, 0x2d, 0x77, 0x99, 0xb0, 0xcb, 0x46, 0xca,\n\t0x45, 0xcf, 0x4a, 0xde, 0x79, 0x8b, 0x86, 0x91, 0xa8, 0xe3, 0x3e, 0x42, 0xc6, 0x51, 0xf3, 0x0e,\n\t0x12, 0x36, 0x5a, 0xee, 0x29, 0x7b, 0x8d, 0x8c, 0x8f, 0x8a, 0x85, 0x94, 0xa7, 0xf2, 0x0d, 0x17,\n\t0x39, 0x4b, 0xdd, 0x7c, 0x84, 0x97, 0xa2, 0xfd, 0x1c, 0x24, 0x6c, 0xb4, 0xc7, 0x52, 0xf6,\n];\n\n/// Table of L\u1D62 = LOG[i + 1] such that g^L\u1D62 = i where g = 0x03.\nconst LOG: number[] = [\n\t0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03, 0x64,\n\t0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1, 0x7d,\n\t0xc2, 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c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44,\n\t0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67,\n\t0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07,\n];\n\nexport class Polynomial {\n\tcoefficients: GF256[];\n\n\t/**\n\t * Construct a new Polynomial over [GF256] from the given coefficients.\n\t * The first coefficient is the constant term.\n\t */\n\tconstructor(coefficients: GF256[]) {\n\t\tthis.coefficients = coefficients.slice();\n\n\t\t// The highest degree coefficient is always non-zero.\n\t\twhile (\n\t\t\tthis.coefficients.length > 0 &&\n\t\t\tthis.coefficients[this.coefficients.length - 1].value === 0\n\t\t) {\n\t\t\tthis.coefficients.pop();\n\t\t}\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): Polynomial {\n\t\treturn new Polynomial(Array.from(bytes, (b) => new GF256(b)));\n\t}\n\n\tdegree(): number {\n\t\tif (this.coefficients.length === 0) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn this.coefficients.length - 1;\n\t}\n\n\tgetCoefficient(index: number): GF256 {\n\t\tif (index >= this.coefficients.length) {\n\t\t\treturn GF256.zero();\n\t\t}\n\t\treturn this.coefficients[index];\n\t}\n\n\tadd(other: Polynomial): Polynomial {\n\t\tconst degree = Math.max(this.degree(), other.degree());\n\t\treturn new Polynomial(\n\t\t\tArray.from({ length: degree + 1 }, (_, i) =>\n\t\t\t\tthis.getCoefficient(i).add(other.getCoefficient(i)),\n\t\t\t),\n\t\t);\n\t}\n\n\tmul(other: Polynomial): Polynomial {\n\t\tconst degree = this.degree() + other.degree();\n\t\treturn new Polynomial(\n\t\t\tArray.from({ length: degree + 1 }, (_, i) => {\n\t\t\t\tlet sum = GF256.zero();\n\t\t\t\tfor (let j = 0; j <= i; j++) {\n\t\t\t\t\tif (j <= this.degree() && i - j <= other.degree()) {\n\t\t\t\t\t\tsum = sum.add(this.getCoefficient(j).mul(other.getCoefficient(i - j)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn sum;\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** The polynomial s * this. */\n\tscale(s: GF256): Polynomial {\n\t\treturn new Polynomial(this.coefficients.map((c) => c.mul(s)));\n\t}\n\n\tdiv(s: GF256): Polynomial {\n\t\treturn this.scale(new GF256(1).div(s));\n\t}\n\n\t/** The polynomial x + c. */\n\tstatic monic_linear(c: GF256): Polynomial {\n\t\treturn new Polynomial([c, GF256.one()]);\n\t}\n\n\tstatic zero(): Polynomial {\n\t\treturn new Polynomial([]);\n\t}\n\n\tstatic one(): Polynomial {\n\t\treturn new Polynomial([GF256.one()]);\n\t}\n\n\t/** Given a set of coordinates, interpolate a polynomial. */\n\tstatic interpolate(coordinates: { x: GF256; y: GF256 }[]): Polynomial {\n\t\tif (coordinates.length < 1) {\n\t\t\tthrow new Error('At least one coefficient is required');\n\t\t}\n\n\t\tif (hasDuplicates(coordinates.map(({ x }) => x.value))) {\n\t\t\tthrow new Error('Coefficients must have unique x values');\n\t\t}\n\n\t\treturn coordinates.reduce(\n\t\t\t(sum, { x: x_j, y: y_j }, j) =>\n\t\t\t\tsum.add(\n\t\t\t\t\tcoordinates\n\t\t\t\t\t\t.filter((_, i) => i !== j)\n\t\t\t\t\t\t.reduce(\n\t\t\t\t\t\t\t(product, { x: x_i }) =>\n\t\t\t\t\t\t\t\tproduct.mul(Polynomial.monic_linear(x_i.neg()).div(x_j.sub(x_i))),\n\t\t\t\t\t\t\tPolynomial.one(),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.scale(y_j),\n\t\t\t\t),\n\t\t\tPolynomial.zero(),\n\t\t);\n\t}\n\n\t/** Given a set of coordinates, interpolate a polynomial and evaluate it at x = 0. */\n\tstatic combine(coordinates: { x: GF256; y: GF256 }[]): GF256 {\n\t\tif (coordinates.length < 1) {\n\t\t\tthrow new Error('At least one coefficient is required');\n\t\t}\n\n\t\tif (hasDuplicates(coordinates.map(({ x }) => x.value))) {\n\t\t\tthrow new Error('Coefficients must have unique x values');\n\t\t}\n\n\t\tconst quotient: GF256 = coordinates.reduce((sum, { x: x_j, y: y_j }, j) => {\n\t\t\tconst denominator = x_j.mul(\n\t\t\t\tcoordinates\n\t\t\t\t\t.filter((_, i) => i !== j)\n\t\t\t\t\t.reduce((product, { x: x_i }) => product.mul(x_i.sub(x_j)), GF256.one()),\n\t\t\t);\n\t\t\treturn sum.add(y_j.div(denominator));\n\t\t}, GF256.zero());\n\n\t\tconst xProduct = coordinates.reduce((product, { x }) => product.mul(x), GF256.one());\n\t\treturn xProduct.mul(quotient);\n\t}\n\n\t/** Evaluate the polynomial at x. */\n\tevaluate(x: GF256): GF256 {\n\t\treturn this.coefficients\n\t\t\t.toReversed()\n\t\t\t.reduce((sum, coefficient) => sum.mul(x).add(coefficient), GF256.zero());\n\t}\n\n\tequals(other: Polynomial): boolean {\n\t\tif (this.coefficients.length !== other.coefficients.length) {\n\t\t\treturn false;\n\t\t}\n\t\treturn this.coefficients.every((c, i) => c.equals(other.getCoefficient(i)));\n\t}\n}\n\n/** Representation of a share of a secret. The index is a number between 1 and 255. */\nexport type Share = {\n\tindex: number;\n\tshare: Uint8Array<ArrayBuffer>;\n};\n\nfunction toInternalShare(share: Share): InternalShare {\n\treturn {\n\t\tindex: new GF256(share.index),\n\t\tshare: Array.from(share.share, (byte) => new GF256(byte)),\n\t};\n}\n\n/** Internal representation of a share of a secret. The index is a non-zero GF256. */\ntype InternalShare = {\n\tindex: GF256;\n\tshare: GF256[];\n};\n\nfunction toShare(internalShare: InternalShare): Share {\n\treturn {\n\t\tindex: internalShare.index.value,\n\t\tshare: new Uint8Array(internalShare.share.map((byte) => byte.value)),\n\t};\n}\n\n/**\n * Sample a random polynomial with the given constant and degree.\n *\n * @param constant The constant term of the polynomial.\n * @param degree The degree of the polynomial.\n * @returns A random polynomial with the given constant and degree.\n */\nfunction samplePolynomial(constant: GF256, degree: number): Polynomial {\n\tconst randomCoefficients = new Uint8Array(degree);\n\tcrypto.getRandomValues(randomCoefficients);\n\n\t// The resulting polynomial has degree + 1 coefficients.\n\treturn Polynomial.fromBytes(new Uint8Array([constant.value, ...randomCoefficients]));\n}\n\n/**\n * Split a secret into shares.\n *\n * @param secret The secret to split.\n * @param threshold The minimum number of shares required to reconstruct the secret.\n * @param total The total number of shares to generate.\n * @returns The shares.\n */\nexport function split(secret: Uint8Array, threshold: number, total: number): Share[] {\n\tif (threshold > total || threshold < 1 || total >= GF256_SIZE) {\n\t\tthrow new Error(`Invalid threshold ${threshold} or total ${total}`);\n\t}\n\n\tconst polynomials = Array.from(secret, (s) => samplePolynomial(new GF256(s), threshold - 1));\n\treturn Array.from({ length: total }, (_, i) => {\n\t\t// Indexes start at 1 because 0 is reserved for the constant term (which is also the secret).\n\t\tconst index = new GF256(i + 1);\n\t\tconst share = polynomials.map((p) => p.evaluate(index));\n\t\treturn toShare({ index, share });\n\t});\n}\n\n/** Validate a set of shares and return them in internal shares representation along with the length of the shares. */\nfunction validateShares(shares: Share[]): { internalShares: InternalShare[]; length: number } {\n\tif (shares.length < 1) {\n\t\tthrow new Error('At least one share is required');\n\t}\n\n\tif (!allEqual(shares.map(({ share }) => share.length))) {\n\t\tthrow new Error('All shares must have the same length');\n\t}\n\n\tif (hasDuplicates(shares.map(({ index }) => index))) {\n\t\tthrow new Error('Shares must have unique indices');\n\t}\n\n\tconst internalShares = shares.map(toInternalShare);\n\tconst length = internalShares[0].share.length;\n\n\treturn { internalShares, length };\n}\n\n/**\n * Combine shares into a secret. If fewer than the threshold number of shares are provided,\n * the result will be indistinguishable from random.\n *\n * @param shares The shares to combine.\n * @returns The secret.\n */\nexport function combine(shares: Share[]): Uint8Array<ArrayBuffer> {\n\tconst { internalShares, length } = validateShares(shares);\n\n\treturn new Uint8Array(\n\t\tArray.from(\n\t\t\t{ length },\n\t\t\t(_, i) =>\n\t\t\t\tPolynomial.combine(\n\t\t\t\t\tinternalShares.map(({ index, share }) => ({\n\t\t\t\t\t\tx: index,\n\t\t\t\t\t\ty: share[i],\n\t\t\t\t\t})),\n\t\t\t\t).value,\n\t\t),\n\t);\n}\n\n/**\n * Interpolate a polynomial from the given shares.\n *\n * @param shares The shares to interpolate from.\n * @returns A function that evaluates the polynomial at a given x.\n */\nexport function interpolate(shares: Share[]): (x: number) => Uint8Array {\n\tconst { internalShares, length } = validateShares(shares);\n\n\tconst polynomials = Array.from({ length }, (_, i) =>\n\t\tPolynomial.interpolate(internalShares.map(({ index, share }) => ({ x: index, y: share[i] }))),\n\t);\n\n\treturn (x: number) => {\n\t\treturn new Uint8Array(polynomials.map((p) => p.evaluate(new GF256(x)).value));\n\t};\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAwC;AAExC,MAAM,aAAa;AAKZ,MAAM,MAAM;AAAA,EAGlB,YAAY,OAAe;AAC1B,QAAI,QAAQ,KAAK,SAAS,YAAY;AACrC,YAAM,IAAI,MAAM,iBAAiB,KAAK,YAAY;AAAA,IACnD;AACA,SAAK,QAAQ;AAAA,EACd;AAAA,EAEA,MAAc;AACb,QAAI,KAAK,UAAU,GAAG;AACrB,YAAM,IAAI,MAAM,eAAe;AAAA,IAChC;AACA,WAAO,IAAI,KAAK,QAAQ,CAAC;AAAA,EAC1B;AAAA,EAEA,OAAO,IAAI,GAAkB;AAC5B,WAAO,IAAI,MAAM,IAAI,KAAK,aAAa,EAAE,CAAC;AAAA,EAC3C;AAAA,EAEA,IAAI,OAAqB;AACxB,WAAO,IAAI,MAAM,KAAK,QAAQ,MAAM,KAAK;AAAA,EAC1C;AAAA,EAEA,IAAI,OAAqB;AAExB,WAAO,KAAK,IAAI,KAAK;AAAA,EACtB;AAAA,EAEA,MA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MAAM;AAAA,IAAK,EAAE,OAAO;AAAA,IAAG,CAAC,GAAG,MAC9C,WAAW,YAAY,eAAe,IAAI,CAAC,EAAE,OAAO,MAAM,OAAO,EAAE,GAAG,OAAO,GAAG,MAAM,CAAC,EAAE,EAAE,CAAC;AAAA,EAC7F;AAEA,SAAO,CAAC,MAAc;AACrB,WAAO,IAAI,WAAW,YAAY,IAAI,CAAC,MAAM,EAAE,SAAS,IAAI,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC;AAAA,EAC7E;AACD;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "0.5.1";
1
+ export declare const PACKAGE_VERSION = "0.6.0";
@@ -21,5 +21,5 @@ __export(version_exports, {
21
21
  PACKAGE_VERSION: () => PACKAGE_VERSION
22
22
  });
23
23
  module.exports = __toCommonJS(version_exports);
24
- const PACKAGE_VERSION = "0.5.1";
24
+ const PACKAGE_VERSION = "0.6.0";
25
25
  //# sourceMappingURL=version.js.map
@@ -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.5.1';\n"],
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.6.0';\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,MAAM,kBAAkB;",
6
6
  "names": []
7
7
  }
@@ -6,7 +6,7 @@ export declare class G1Element {
6
6
  constructor(point: ProjPointType<bigint>);
7
7
  static generator(): G1Element;
8
8
  static fromBytes(bytes: Uint8Array): G1Element;
9
- toBytes(): Uint8Array;
9
+ toBytes(): Uint8Array<ArrayBuffer>;
10
10
  multiply(scalar: Scalar): G1Element;
11
11
  add(other: G1Element): G1Element;
12
12
  subtract(other: G1Element): G1Element;
@@ -19,7 +19,7 @@ export declare class G2Element {
19
19
  constructor(point: ProjPointType<Fp2>);
20
20
  static generator(): G2Element;
21
21
  static fromBytes(bytes: Uint8Array): G2Element;
22
- toBytes(): Uint8Array;
22
+ toBytes(): Uint8Array<ArrayBuffer>;
23
23
  multiply(scalar: Scalar): G2Element;
24
24
  add(other: G2Element): G2Element;
25
25
  static hashToCurve(data: Uint8Array): G2Element;
@@ -29,7 +29,7 @@ export declare class GTElement {
29
29
  element: Fp12;
30
30
  static readonly SIZE = 576;
31
31
  constructor(element: Fp12);
32
- toBytes(): Uint8Array;
32
+ toBytes(): Uint8Array<ArrayBuffer>;
33
33
  equals(other: GTElement): boolean;
34
34
  }
35
35
  export declare class Scalar {
@@ -37,7 +37,7 @@ export declare class Scalar {
37
37
  static readonly SIZE = 32;
38
38
  constructor(scalar: bigint);
39
39
  static random(): Scalar;
40
- toBytes(): Uint8Array;
40
+ toBytes(): Uint8Array<ArrayBuffer>;
41
41
  static fromBytes(bytes: Uint8Array): Scalar;
42
42
  static fromNumber(num: number): Scalar;
43
43
  }
@@ -11,7 +11,7 @@ const _G1Element = class _G1Element {
11
11
  return new _G1Element(bls12_381.G1.ProjectivePoint.fromHex(toHex(bytes)));
12
12
  }
13
13
  toBytes() {
14
- return this.point.toRawBytes();
14
+ return this.point.toBytes();
15
15
  }
16
16
  multiply(scalar) {
17
17
  return new _G1Element(this.point.multiply(scalar.scalar));
@@ -44,7 +44,7 @@ const _G2Element = class _G2Element {
44
44
  return new _G2Element(bls12_381.G2.ProjectivePoint.fromHex(toHex(bytes)));
45
45
  }
46
46
  toBytes() {
47
- return this.point.toRawBytes();
47
+ return this.point.toBytes();
48
48
  }
49
49
  multiply(scalar) {
50
50
  return new _G2Element(this.point.multiply(scalar.scalar));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/bls12381.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toHex } from '@mysten/bcs';\nimport type { Fp2, Fp12 } from '@noble/curves/abstract/tower';\nimport type { ProjPointType } from '@noble/curves/abstract/weierstrass';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nexport class G1Element {\n\tpoint: ProjPointType<bigint>;\n\n\tpublic static readonly SIZE = 48;\n\n\tconstructor(point: ProjPointType<bigint>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G1Element {\n\t\treturn new G1Element(bls12_381.G1.ProjectivePoint.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G1Element {\n\t\treturn new G1Element(bls12_381.G1.ProjectivePoint.fromHex(toHex(bytes)));\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\treturn this.point.toRawBytes();\n\t}\n\n\tmultiply(scalar: Scalar): G1Element {\n\t\treturn new G1Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.add(other.point));\n\t}\n\n\tsubtract(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.subtract(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G1Element {\n\t\treturn new G1Element(\n\t\t\tbls12_381.G1.ProjectivePoint.fromAffine(bls12_381.G1.hashToCurve(data).toAffine()),\n\t\t);\n\t}\n\n\tpairing(other: G2Element): GTElement {\n\t\treturn new GTElement(bls12_381.pairing(this.point, other.point));\n\t}\n}\n\nexport class G2Element {\n\tpoint: ProjPointType<Fp2>;\n\n\tpublic static readonly SIZE = 96;\n\n\tconstructor(point: ProjPointType<Fp2>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G2Element {\n\t\treturn new G2Element(bls12_381.G2.ProjectivePoint.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G2Element {\n\t\treturn new G2Element(bls12_381.G2.ProjectivePoint.fromHex(toHex(bytes)));\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\treturn this.point.toRawBytes();\n\t}\n\n\tmultiply(scalar: Scalar): G2Element {\n\t\treturn new G2Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G2Element): G2Element {\n\t\treturn new G2Element(this.point.add(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G2Element {\n\t\treturn new G2Element(\n\t\t\tbls12_381.G2.ProjectivePoint.fromAffine(bls12_381.G2.hashToCurve(data).toAffine()),\n\t\t);\n\t}\n\n\tequals(other: G2Element): boolean {\n\t\treturn this.point.equals(other.point);\n\t}\n}\n\nexport class GTElement {\n\telement: Fp12;\n\n\tpublic static readonly SIZE = 576;\n\n\tconstructor(element: Fp12) {\n\t\tthis.element = element;\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\t// This permutation reorders the 6 pairs of coefficients of the GT element for compatability with the Rust and Move implementations.\n\t\t//\n\t\t// The permutation P may be computed as:\n\t\t// for i in 0..3 {\n\t\t// for j in 0..2 {\n\t\t// P[2 * i + j] = i + 3 * j;\n\t\t// }\n\t\t// }\n\t\tconst P = [0, 3, 1, 4, 2, 5];\n\t\tconst PAIR_SIZE = GTElement.SIZE / P.length;\n\n\t\tconst bytes = bls12_381.fields.Fp12.toBytes(this.element);\n\t\tconst result = new Uint8Array(GTElement.SIZE);\n\n\t\tfor (let i = 0; i < P.length; i++) {\n\t\t\tconst sourceStart = P[i] * PAIR_SIZE;\n\t\t\tconst sourceEnd = sourceStart + PAIR_SIZE;\n\t\t\tconst targetStart = i * PAIR_SIZE;\n\t\t\tresult.set(bytes.subarray(sourceStart, sourceEnd), targetStart);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tequals(other: GTElement): boolean {\n\t\treturn bls12_381.fields.Fp12.eql(this.element, other.element);\n\t}\n}\n\nexport class Scalar {\n\tscalar: bigint;\n\n\tpublic static readonly SIZE = 32;\n\n\tconstructor(scalar: bigint) {\n\t\tthis.scalar = scalar;\n\t}\n\n\tstatic random(): Scalar {\n\t\treturn Scalar.fromBytes(bls12_381.utils.randomPrivateKey());\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\treturn new Uint8Array(bls12_381.fields.Fr.toBytes(this.scalar));\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): Scalar {\n\t\treturn new Scalar(bls12_381.fields.Fr.fromBytes(bytes));\n\t}\n\n\tstatic fromNumber(num: number): Scalar {\n\t\treturn new Scalar(BigInt(num));\n\t}\n}\n"],
5
- "mappings": "AAGA,SAAS,aAAa;AAGtB,SAAS,iBAAiB;AAEnB,MAAM,aAAN,MAAM,WAAU;AAAA,EAKtB,YAAY,OAA8B;AACzC,SAAK,QAAQ;AAAA,EACd;AAAA,EAEA,OAAO,YAAuB;AAC7B,WAAO,IAAI,WAAU,UAAU,GAAG,gBAAgB,IAAI;AAAA,EACvD;AAAA,EAEA,OAAO,UAAU,OAA8B;AAC9C,WAAO,IAAI,WAAU,UAAU,GAAG,gBAAgB,QAAQ,MAAM,KAAK,CAAC,CAAC;AAAA,EACxE;AAAA,EAEA,UAAsB;AACrB,WAAO,KAAK,MAAM,WAAW;AAAA,EAC9B;AAAA,EAEA,SAAS,QAA2B;AACnC,WAAO,IAAI,WAAU,KAAK,MAAM,SAAS,OAAO,MAAM,CAAC;AAAA,EACxD;AAAA,EAEA,IAAI,OAA6B;AAChC,WAAO,IAAI,WAAU,KAAK,MAAM,IAAI,MAAM,KAAK,CAAC;AAAA,EACjD;AAAA,EAEA,SAAS,OAA6B;AACrC,WAAO,IAAI,WAAU,KAAK,MAAM,SAAS,MAAM,KAAK,CAAC;AAAA,EACtD;AAAA,EAEA,OAAO,YAAY,MAA6B;AAC/C,WAAO,IAAI;AAAA,MACV,UAAU,GAAG,gBAAgB,WAAW,UAAU,GAAG,YAAY,IAAI,EAAE,SAAS,CAAC;AAAA,IAClF;AAAA,EACD;AAAA,EAEA,QAAQ,OAA6B;AACpC,WAAO,IAAI,UAAU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I;AAE5C,aAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AAClC,YAAM,cAAc,EAAE,CAAC,IAAI;AAC3B,YAAM,YAAY,cAAc;AAChC,YAAM,cAAc,IAAI;AACxB,aAAO,IAAI,MAAM,SAAS,aAAa,SAAS,GAAG,WAAW;AAAA,IAC/D;AAEA,WAAO;AAAA,EACR;AAAA,EAEA,OAAO,OAA2B;AACjC,WAAO,UAAU,OAAO,KAAK,IAAI,KAAK,SAAS,MAAM,OAAO;AAAA,EAC7D;AACD;AArCa,WAGW,OAAO;AAHxB,IAAM,YAAN;AAuCA,MAAM,UAAN,MAAM,QAAO;AAAA,EAKnB,YAAY,QAAgB;AAC3B,SAAK,SAAS;AAAA,EACf;AAAA,EAEA,OAAO,SAAiB;AACvB,WAAO,QAAO,UAAU,UAAU,MAAM,iBAAiB,CAAC;AAAA,EAC3D;AAAA,EAEA,UAAsB;AACrB,WAAO,IAAI,WAAW,UAAU,OAAO,GAAG,QAAQ,KAAK,MAAM,CAAC;AAAA,EAC/D;AAAA,EAEA,OAAO,UAAU,OAA2B;AAC3C,WAAO,IAAI,QAAO,UAAU,OAAO,GAAG,UAAU,KAAK,CAAC;AAAA,EACvD;AAAA,EAEA,OAAO,WAAW,KAAqB;AACtC,WAAO,IAAI,QAAO,OAAO,GAAG,CAAC;AAAA,EAC9B;AACD;AAxBa,QAGW,OAAO;AAHxB,IAAM,SAAN;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toHex } from '@mysten/bcs';\nimport type { Fp2, Fp12 } from '@noble/curves/abstract/tower';\nimport type { ProjPointType } from '@noble/curves/abstract/weierstrass';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nexport class G1Element {\n\tpoint: ProjPointType<bigint>;\n\n\tpublic static readonly SIZE = 48;\n\n\tconstructor(point: ProjPointType<bigint>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G1Element {\n\t\treturn new G1Element(bls12_381.G1.ProjectivePoint.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G1Element {\n\t\treturn new G1Element(bls12_381.G1.ProjectivePoint.fromHex(toHex(bytes)));\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.point.toBytes() as Uint8Array<ArrayBuffer>;\n\t}\n\n\tmultiply(scalar: Scalar): G1Element {\n\t\treturn new G1Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.add(other.point));\n\t}\n\n\tsubtract(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.subtract(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G1Element {\n\t\treturn new G1Element(\n\t\t\tbls12_381.G1.ProjectivePoint.fromAffine(bls12_381.G1.hashToCurve(data).toAffine()),\n\t\t);\n\t}\n\n\tpairing(other: G2Element): GTElement {\n\t\treturn new GTElement(bls12_381.pairing(this.point, other.point));\n\t}\n}\n\nexport class G2Element {\n\tpoint: ProjPointType<Fp2>;\n\n\tpublic static readonly SIZE = 96;\n\n\tconstructor(point: ProjPointType<Fp2>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G2Element {\n\t\treturn new G2Element(bls12_381.G2.ProjectivePoint.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G2Element {\n\t\treturn new G2Element(bls12_381.G2.ProjectivePoint.fromHex(toHex(bytes)));\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.point.toBytes() as Uint8Array<ArrayBuffer>;\n\t}\n\n\tmultiply(scalar: Scalar): G2Element {\n\t\treturn new G2Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G2Element): G2Element {\n\t\treturn new G2Element(this.point.add(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G2Element {\n\t\treturn new G2Element(\n\t\t\tbls12_381.G2.ProjectivePoint.fromAffine(bls12_381.G2.hashToCurve(data).toAffine()),\n\t\t);\n\t}\n\n\tequals(other: G2Element): boolean {\n\t\treturn this.point.equals(other.point);\n\t}\n}\n\nexport class GTElement {\n\telement: Fp12;\n\n\tpublic static readonly SIZE = 576;\n\n\tconstructor(element: Fp12) {\n\t\tthis.element = element;\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\t// This permutation reorders the 6 pairs of coefficients of the GT element for compatability with the Rust and Move implementations.\n\t\t//\n\t\t// The permutation P may be computed as:\n\t\t// for i in 0..3 {\n\t\t// for j in 0..2 {\n\t\t// P[2 * i + j] = i + 3 * j;\n\t\t// }\n\t\t// }\n\t\tconst P = [0, 3, 1, 4, 2, 5];\n\t\tconst PAIR_SIZE = GTElement.SIZE / P.length;\n\n\t\tconst bytes = bls12_381.fields.Fp12.toBytes(this.element);\n\t\tconst result = new Uint8Array(GTElement.SIZE);\n\n\t\tfor (let i = 0; i < P.length; i++) {\n\t\t\tconst sourceStart = P[i] * PAIR_SIZE;\n\t\t\tconst sourceEnd = sourceStart + PAIR_SIZE;\n\t\t\tconst targetStart = i * PAIR_SIZE;\n\t\t\tresult.set(bytes.subarray(sourceStart, sourceEnd), targetStart);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tequals(other: GTElement): boolean {\n\t\treturn bls12_381.fields.Fp12.eql(this.element, other.element);\n\t}\n}\n\nexport class Scalar {\n\tscalar: bigint;\n\n\tpublic static readonly SIZE = 32;\n\n\tconstructor(scalar: bigint) {\n\t\tthis.scalar = scalar;\n\t}\n\n\tstatic random(): Scalar {\n\t\treturn Scalar.fromBytes(bls12_381.utils.randomPrivateKey());\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn new Uint8Array(bls12_381.fields.Fr.toBytes(this.scalar)) as Uint8Array<ArrayBuffer>;\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): Scalar {\n\t\treturn new Scalar(bls12_381.fields.Fr.fromBytes(bytes));\n\t}\n\n\tst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AO,UAAU,OAAO,KAAK,IAAI,KAAK,SAAS,MAAM,OAAO;AAAA,EAC7D;AACD;AArCa,WAGW,OAAO;AAHxB,IAAM,YAAN;AAuCA,MAAM,UAAN,MAAM,QAAO;AAAA,EAKnB,YAAY,QAAgB;AAC3B,SAAK,SAAS;AAAA,EACf;AAAA,EAEA,OAAO,SAAiB;AACvB,WAAO,QAAO,UAAU,UAAU,MAAM,iBAAiB,CAAC;AAAA,EAC3D;AAAA,EAEA,UAAmC;AAClC,WAAO,IAAI,WAAW,UAAU,OAAO,GAAG,QAAQ,KAAK,MAAM,CAAC;AAAA,EAC/D;AAAA,EAEA,OAAO,UAAU,OAA2B;AAC3C,WAAO,IAAI,QAAO,UAAU,OAAO,GAAG,UAAU,KAAK,CAAC;AAAA,EACvD;AAAA,EAEA,OAAO,WAAW,KAAqB;AACtC,WAAO,IAAI,QAAO,OAAO,GAAG,CAAC;AAAA,EAC9B;AACD;AAxBa,QAGW,OAAO;AAHxB,IAAM,SAAN;",
6
6
  "names": []
7
7
  }
@@ -22,8 +22,8 @@ export declare class SealClient {
22
22
  * Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
23
23
  */
24
24
  encrypt({ kemType, demType, threshold, packageId, id, data, aad, }: EncryptOptions): Promise<{
25
- encryptedObject: Uint8Array;
26
- key: Uint8Array;
25
+ encryptedObject: Uint8Array<ArrayBuffer>;
26
+ key: Uint8Array<ArrayBuffer>;
27
27
  }>;
28
28
  /**
29
29
  * Decrypt the given encrypted bytes using cached keys.
@@ -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\tInvalidPackageError,\n\tInvalidThresholdError,\n\ttoMajorityError,\n\tTooManyFailedFetchKeyRequestsError,\n} from './error.js';\nimport { BonehFranklinBLS12381Services } from './ibe.js';\nimport {\n\tBonehFranklinBLS12381DerivedKey,\n\tretrieveKeyServers,\n\tverifyKeyServer,\n\tfetchKeysForAllIds,\n} from './key-server.js';\nimport type { DerivedKey, KeyServer } from './key-server.js';\nimport type {\n\tDecryptOptions,\n\tEncryptOptions,\n\tFetchKeysOptions,\n\tGetDerivedKeysOptions,\n\tKeyCacheKey,\n\tKeyServerConfig,\n\tSealClientExtensionOptions,\n\tSealClientOptions,\n\tSealCompatibleClient,\n} from './types.js';\nimport { createFullId, count } from './utils.js';\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#cachedPublicKeys = new Map<string, G2Element>();\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 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}: EncryptOptions) {\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 * If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that\n\t * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.\n\t * This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors\n\t * receive the same output (e.g., for onchain encrypted voting).\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 * @param checkShareConsistency - If true, the shares are checked for consistency.\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt({ data, sessionKey, txBytes, checkShareConsistency }: DecryptOptions) {\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\tif (checkShareConsistency) {\n\t\t\tconst publicKeys = await this.getPublicKeys(\n\t\t\t\tencryptedObject.services.map(([objectId, _]) => objectId),\n\t\t\t);\n\t\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys, publicKeys });\n\t\t}\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 * Get the public keys for the given services.\n\t * If all public keys are not in the cache, they are retrieved.\n\t *\n\t * @param services - The services to get the public keys for.\n\t * @returns The public keys for the given services in the same order as the given services.\n\t */\n\tasync getPublicKeys(services: string[]): Promise<G2Element[]> {\n\t\tconst keyServers = await this.getKeyServers();\n\n\t\t// Collect the key servers not already in store or cache.\n\t\tconst missingKeyServers = services.filter(\n\t\t\t(objectId) => !keyServers.has(objectId) && !this.#cachedPublicKeys.has(objectId),\n\t\t);\n\n\t\t// If there are missing key servers, retrieve them and update the cache.\n\t\tif (missingKeyServers.length > 0) {\n\t\t\t(\n\t\t\t\tawait retrieveKeyServers({\n\t\t\t\t\tobjectIds: missingKeyServers,\n\t\t\t\t\tclient: this.#suiClient,\n\t\t\t\t})\n\t\t\t).forEach((keyServer) =>\n\t\t\t\tthis.#cachedPublicKeys.set(keyServer.objectId, G2Element.fromBytes(keyServer.pk)),\n\t\t\t);\n\t\t}\n\n\t\treturn services.map((objectId) => {\n\t\t\tconst keyServer = keyServers.get(objectId);\n\t\t\tif (keyServer) {\n\t\t\t\treturn G2Element.fromBytes(keyServer.pk);\n\t\t\t}\n\t\t\treturn this.#cachedPublicKeys.get(objectId)!;\n\t\t});\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({ ids, txBytes, sessionKey, threshold }: FetchKeysOptions) {\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\tconst certificate = 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\turl: server.url,\n\t\t\t\t\trequestSignature: signedRequest.requestSignature,\n\t\t\t\t\ttransactionBytes: txBytes,\n\t\t\t\t\tencKey: signedRequest.encKey,\n\t\t\t\t\tencKeyPk: signedRequest.encKeyPk,\n\t\t\t\t\tencVerificationKey: signedRequest.encVerificationKey,\n\t\t\t\t\tcertificate,\n\t\t\t\t\ttimeout: this.#timeout,\n\t\t\t\t\tapiKeyName: config?.apiKeyName,\n\t\t\t\t\tapiKey: config?.apiKey,\n\t\t\t\t\tsignal: controller.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}: GetDerivedKeysOptions): 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\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port { 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\tretrieveKeyServers,\n\tverifyKeyServer,\n\tfetchKeysForAllIds,\n} from './key-server.js';\nimport type { DerivedKey, KeyServer } from './key-server.js';\nimport type {\n\tDecryptOptions,\n\tEncryptOptions,\n\tFetchKeysOptions,\n\tGetDerivedKeysOptions,\n\tKeyCacheKey,\n\tKeyServerConfig,\n\tSealClientExtensionOptions,\n\tSealClientOptions,\n\tSealCompatibleClient,\n} from './types.js';\nimport { createFullId, count } from './utils.js';\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#cachedPublicKeys = new Map<string, G2Element>();\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 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}: EncryptOptions) {\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(\n\t\t\t\tdemType,\n\t\t\t\tdata as Uint8Array<ArrayBuffer>,\n\t\t\t\taad as Uint8Array<ArrayBuffer>,\n\t\t\t),\n\t\t});\n\t}\n\n\t#createEncryptionInput(\n\t\ttype: DemType,\n\t\tdata: Uint8Array<ArrayBuffer>,\n\t\taad: Uint8Array<ArrayBuffer>,\n\t): 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 * If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that\n\t * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.\n\t * This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors\n\t * receive the same output (e.g., for onchain encrypted voting).\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 * @param checkShareConsistency - If true, the shares are checked for consistency.\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt({ data, sessionKey, txBytes, checkShareConsistency }: DecryptOptions) {\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\tif (checkShareConsistency) {\n\t\t\tconst publicKeys = await this.getPublicKeys(\n\t\t\t\tencryptedObject.services.map(([objectId, _]) => objectId),\n\t\t\t);\n\t\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys, publicKeys });\n\t\t}\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 * Get the public keys for the given services.\n\t * If all public keys are not in the cache, they are retrieved.\n\t *\n\t * @param services - The services to get the public keys for.\n\t * @returns The public keys for the given services in the same order as the given services.\n\t */\n\tasync getPublicKeys(services: string[]): Promise<G2Element[]> {\n\t\tconst keyServers = await this.getKeyServers();\n\n\t\t// Collect the key servers not already in store or cache.\n\t\tconst missingKeyServers = services.filter(\n\t\t\t(objectId) => !keyServers.has(objectId) && !this.#cachedPublicKeys.has(objectId),\n\t\t);\n\n\t\t// If there are missing key servers, retrieve them and update the cache.\n\t\tif (missingKeyServers.length > 0) {\n\t\t\t(\n\t\t\t\tawait retrieveKeyServers({\n\t\t\t\t\tobjectIds: missingKeyServers,\n\t\t\t\t\tclient: this.#suiClient,\n\t\t\t\t})\n\t\t\t).forEach((keyServer) =>\n\t\t\t\tthis.#cachedPublicKeys.set(keyServer.objectId, G2Element.fromBytes(keyServer.pk)),\n\t\t\t);\n\t\t}\n\n\t\treturn services.map((objectId) => {\n\t\t\tconst keyServer = keyServers.get(objectId);\n\t\t\tif (keyServer) {\n\t\t\t\treturn G2Element.fromBytes(keyServer.pk);\n\t\t\t}\n\t\t\treturn this.#cachedPublicKeys.get(objectId)!;\n\t\t});\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({ ids, txBytes, sessionKey, threshold }: FetchKeysOptions) {\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\tconst certificate = 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\turl: server.url,\n\t\t\t\t\trequestSignature: signedRequest.requestSignature,\n\t\t\t\t\ttransactionBytes: txBytes,\n\t\t\t\t\tencKey: signedRequest.encKey,\n\t\t\t\t\tencKeyPk: signedRequest.encKeyPk,\n\t\t\t\t\tencVerificationKey: signedRequest.encVerificationKey,\n\t\t\t\t\tcertificate,\n\t\t\t\t\ttimeout: this.#timeout,\n\t\t\t\t\tapiKeyName: config?.apiKeyName,\n\t\t\t\t\tapiKey: config?.apiKey,\n\t\t\t\t\tsignal: controller.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}: GetDerivedKeysOptions): 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;AAGA,SAAS,uBAAuB;AAChC,SAAS,WAAW,iBAAiB;AACrC,SAAS,eAAe;AAExB,SAAS,WAAW,kBAAkB;AACtC,SAAS,SAAS,SAAS,eAAe;AAC1C;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,qCAAqC;AAC9C;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAaP,SAAS,cAAc,aAAa;AAE7B,MAAM,cAAN,MAAM,YAAW;AAAA,EAWvB,YAAY,SAA4B;AAXlC;AACN;AACA;AACA,oCAAsD;AACtD;AAEA;AAAA,oCAAc,oBAAI,IAA4B;AAC9C,0CAAoB,oBAAI,IAAuB;AAC/C;AACA;AAGC,uBAAK,YAAa,QAAQ;AAE1B,QACC,IAAI,IAAI,QAAQ,cAAc,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,QAAQ,cAAc,QACpF;AACD,YAAM,IAAI,0BAA0B,sBAAsB;AAAA,IAC3D;AAEA,QACC,QAAQ,cAAc,KAAK,CAAC,MAAO,EAAE,cAAc,CAAC,EAAE,UAAY,CAAC,EAAE,cAAc,EAAE,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BAAM,IAAI,sBAAsB,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;AA3PM,IAAM,aAAN;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/decrypt.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\n\nimport type { EncryptedObject } from './bcs.js';\nimport type { G1Element } from './bls12381.js';\nimport { G2Element } from './bls12381.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { InvalidCiphertextError, UnsupportedFeatureError } from './error.js';\nimport { BonehFranklinBLS12381Services, decryptRandomness, verifyNonce } from './ibe.js';\nimport { deriveKey, KeyPurpose } from './kdf.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId, equals } from './utils.js';\nimport { combine, interpolate } from './shamir.js';\n\nexport interface DecryptOptions {\n\tencryptedObject: typeof EncryptedObject.$inferType;\n\tkeys: Map<KeyCacheKey, G1Element>;\n\tpublicKeys?: G2Element[];\n}\n\n/**\n * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.\n * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers\n * otherwise, this will throw an error.\n * Also, it's assumed that the keys were verified by the caller.\n *\n * If publicKeys are provided, the decrypted shares are checked for consistency, meaning that\n * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.\n *\n * @returns - The decrypted plaintext corresponding to ciphertext.\n */\nexport async function decrypt({\n\tencryptedObject,\n\tkeys,\n\tpublicKeys,\n}: DecryptOptions): Promise<Uint8Array> {\n\tif (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {\n\t\tthrow new UnsupportedFeatureError('Encryption mode not supported');\n\t}\n\n\tconst fullId = createFullId(encryptedObject.packageId, encryptedObject.id);\n\n\t// Get the indices of the service whose keys are in the keystore.\n\tconst inKeystore = encryptedObject.services\n\t\t.map((_, i) => i)\n\t\t.filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));\n\n\tif (inKeystore.length < encryptedObject.threshold) {\n\t\tthrow new Error('Not enough shares. Please fetch more keys.');\n\t}\n\n\tconst encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;\n\tif (encryptedShares.length !== encryptedObject.services.length) {\n\t\tthrow new InvalidCiphertextError(\n\t\t\t`Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`,\n\t\t);\n\t}\n\n\tconst nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);\n\n\t// Decrypt each share.\n\tconst shares = inKeystore.map((i) => {\n\t\tconst [objectId, index] = encryptedObject.services[i];\n\t\t// Use the index as the unique info parameter to allow for multiple shares per key server.\n\t\tconst share = BonehFranklinBLS12381Services.decrypt(\n\t\t\tnonce,\n\t\t\tkeys.get(`${fullId}:${objectId}`)!,\n\t\t\tencryptedShares[i],\n\t\t\tfromHex(fullId),\n\t\t\t[objectId, index],\n\t\t);\n\t\treturn { index, share };\n\t});\n\n\t// Combine the decrypted shares into the key\n\tconst baseKey = combine(shares);\n\n\t// Decrypt randomness\n\tconst randomnessKey = deriveKey(\n\t\tKeyPurpose.EncryptedRandomness,\n\t\tbaseKey,\n\t\tencryptedShares,\n\t\tencryptedObject.threshold,\n\t\tencryptedObject.services.map(([objectIds, _]) => objectIds),\n\t);\n\tconst randomness = decryptRandomness(\n\t\tencryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedRandomness,\n\t\trandomnessKey,\n\t);\n\n\t// Verify that the nonce was created with the randomness.\n\tif (!verifyNonce(nonce, randomness)) {\n\t\tthrow new InvalidCiphertextError('Invalid nonce');\n\t}\n\n\t// If public keys are provided, check consistency of the shares.\n\tconst checkShareConsistency = publicKeys !== undefined;\n\tif (checkShareConsistency) {\n\t\tconst polynomial = interpolate(shares);\n\t\tconst allShares = BonehFranklinBLS12381Services.decryptAllSharesUsingRandomness(\n\t\t\trandomness,\n\t\t\tencryptedShares,\n\t\t\tencryptedObject.services,\n\t\t\tpublicKeys,\n\t\t\tnonce,\n\t\t\tfromHex(fullId),\n\t\t);\n\t\tif (allShares.some(({ index, share }) => !equals(polynomial(index), share))) {\n\t\t\tthrow new InvalidCiphertextError('Invalid shares');\n\t\t}\n\t}\n\n\t// Derive the DEM key\n\tconst demKey = deriveKey(\n\t\tKeyPurpose.DEM,\n\t\tbaseKey,\n\t\tencryptedShares,\n\t\tencryptedObject.threshold,\n\t\tencryptedObject.services.map(([objectId, _]) => objectId),\n\t);\n\n\t// Decrypt the ciphertext\n\tif (encryptedObject.ciphertext.Aes256Gcm) {\n\t\treturn AesGcm256.decrypt(demKey, encryptedObject.ciphertext);\n\t} else if (encryptedObject.ciphertext.Hmac256Ctr) {\n\t\treturn Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);\n\t} else if (encryptedObject.ciphertext.Plain) {\n\t\t// In case `Plain` mode is used, return the key.\n\t\treturn demKey;\n\t} else {\n\t\tthrow new InvalidCiphertextError('Invalid ciphertext type');\n\t}\n}\n"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\n\nimport type { EncryptedObject } from './bcs.js';\nimport type { G1Element } from './bls12381.js';\nimport { G2Element } from './bls12381.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { InvalidCiphertextError, UnsupportedFeatureError } from './error.js';\nimport { BonehFranklinBLS12381Services, decryptRandomness, verifyNonce } from './ibe.js';\nimport { deriveKey, KeyPurpose } from './kdf.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId, equals } from './utils.js';\nimport { combine, interpolate } from './shamir.js';\n\nexport interface DecryptOptions {\n\tencryptedObject: typeof EncryptedObject.$inferType;\n\tkeys: Map<KeyCacheKey, G1Element>;\n\tpublicKeys?: G2Element[];\n}\n\n/**\n * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.\n * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers\n * otherwise, this will throw an error.\n * Also, it's assumed that the keys were verified by the caller.\n *\n * If publicKeys are provided, the decrypted shares are checked for consistency, meaning that\n * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.\n *\n * @returns - The decrypted plaintext corresponding to ciphertext.\n */\nexport async function decrypt({\n\tencryptedObject,\n\tkeys,\n\tpublicKeys,\n}: DecryptOptions): Promise<Uint8Array> {\n\tif (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {\n\t\tthrow new UnsupportedFeatureError('Encryption mode not supported');\n\t}\n\n\tconst fullId = createFullId(encryptedObject.packageId, encryptedObject.id);\n\n\t// Get the indices of the service whose keys are in the keystore.\n\tconst inKeystore = encryptedObject.services\n\t\t.map((_, i) => i)\n\t\t.filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));\n\n\tif (inKeystore.length < encryptedObject.threshold) {\n\t\tthrow new Error('Not enough shares. Please fetch more keys.');\n\t}\n\n\tconst encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;\n\tif (encryptedShares.length !== encryptedObject.services.length) {\n\t\tthrow new InvalidCiphertextError(\n\t\t\t`Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`,\n\t\t);\n\t}\n\n\tconst nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);\n\n\t// Decrypt each share.\n\tconst shares = inKeystore.map((i) => {\n\t\tconst [objectId, index] = encryptedObject.services[i];\n\t\t// Use the index as the unique info parameter to allow for multiple shares per key server.\n\t\tconst share = BonehFranklinBLS12381Services.decrypt(\n\t\t\tnonce,\n\t\t\tkeys.get(`${fullId}:${objectId}`)!,\n\t\t\tencryptedShares[i],\n\t\t\tfromHex(fullId),\n\t\t\t[objectId, index],\n\t\t) as Uint8Array<ArrayBuffer>;\n\t\treturn { index, share };\n\t});\n\n\t// Combine the decrypted shares into the key\n\tconst baseKey = combine(shares);\n\n\t// Decrypt randomness\n\tconst randomnessKey = deriveKey(\n\t\tKeyPurpose.EncryptedRandomness,\n\t\tbaseKey,\n\t\tencryptedShares,\n\t\tencryptedObject.threshold,\n\t\tencryptedObject.services.map(([objectIds, _]) => objectIds),\n\t);\n\tconst randomness = decryptRandomness(\n\t\tencryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedRandomness,\n\t\trandomnessKey,\n\t);\n\n\t// Verify that the nonce was created with the randomness.\n\tif (!verifyNonce(nonce, randomness)) {\n\t\tthrow new InvalidCiphertextError('Invalid nonce');\n\t}\n\n\t// If public keys are provided, check consistency of the shares.\n\tconst checkShareConsistency = publicKeys !== undefined;\n\tif (checkShareConsistency) {\n\t\tconst polynomial = interpolate(shares);\n\t\tconst allShares = BonehFranklinBLS12381Services.decryptAllSharesUsingRandomness(\n\t\t\trandomness,\n\t\t\tencryptedShares,\n\t\t\tencryptedObject.services,\n\t\t\tpublicKeys,\n\t\t\tnonce,\n\t\t\tfromHex(fullId),\n\t\t);\n\t\tif (allShares.some(({ index, share }) => !equals(polynomial(index), share))) {\n\t\t\tthrow new InvalidCiphertextError('Invalid shares');\n\t\t}\n\t}\n\n\t// Derive the DEM key\n\tconst demKey = deriveKey(\n\t\tKeyPurpose.DEM,\n\t\tbaseKey,\n\t\tencryptedShares,\n\t\tencryptedObject.threshold,\n\t\tencryptedObject.services.map(([objectId, _]) => objectId),\n\t);\n\n\t// Decrypt the ciphertext\n\tif (encryptedObject.ciphertext.Aes256Gcm) {\n\t\treturn AesGcm256.decrypt(demKey, encryptedObject.ciphertext);\n\t} else if (encryptedObject.ciphertext.Hmac256Ctr) {\n\t\treturn Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);\n\t} else if (encryptedObject.ciphertext.Plain) {\n\t\t// In case `Plain` mode is used, return the key.\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