@mysten/sui 2.35.0 → 2.37.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 (80) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/bcs/bcs.d.mts +6 -6
  3. package/dist/bcs/bcs.d.mts.map +1 -1
  4. package/dist/bcs/bcs.mjs +52 -16
  5. package/dist/bcs/bcs.mjs.map +1 -1
  6. package/dist/bcs/index.d.mts +12 -3
  7. package/dist/bcs/index.d.mts.map +1 -1
  8. package/dist/cryptography/publickey.mjs +1 -0
  9. package/dist/cryptography/publickey.mjs.map +1 -1
  10. package/dist/cryptography/signature-scheme.d.mts +4 -1
  11. package/dist/cryptography/signature-scheme.d.mts.map +1 -1
  12. package/dist/cryptography/signature-scheme.mjs +6 -3
  13. package/dist/cryptography/signature-scheme.mjs.map +1 -1
  14. package/dist/cryptography/signature.d.mts +1 -1
  15. package/dist/cryptography/signature.mjs +2 -1
  16. package/dist/cryptography/signature.mjs.map +1 -1
  17. package/dist/grpc/proto/sui/forking/v1alpha/forking_service.client.d.mts +4 -4
  18. package/dist/grpc/proto/sui/rpc/v2/ledger_service.client.d.mts +4 -4
  19. package/dist/grpc/proto/sui/rpc/v2/move_package_service.client.d.mts +4 -4
  20. package/dist/grpc/proto/sui/rpc/v2/name_service.client.d.mts +4 -4
  21. package/dist/grpc/proto/sui/rpc/v2/signature_verification_service.client.d.mts +4 -4
  22. package/dist/grpc/proto/sui/rpc/v2/state_service.client.d.mts +4 -4
  23. package/dist/grpc/proto/sui/rpc/v2/transaction_execution_service.client.d.mts +4 -4
  24. package/dist/keypairs/mldsa65/index.d.mts +3 -0
  25. package/dist/keypairs/mldsa65/index.mjs +4 -0
  26. package/dist/keypairs/mldsa65/keypair.d.mts +67 -0
  27. package/dist/keypairs/mldsa65/keypair.d.mts.map +1 -0
  28. package/dist/keypairs/mldsa65/keypair.mjs +91 -0
  29. package/dist/keypairs/mldsa65/keypair.mjs.map +1 -0
  30. package/dist/keypairs/mldsa65/publickey.d.mts +37 -0
  31. package/dist/keypairs/mldsa65/publickey.d.mts.map +1 -0
  32. package/dist/keypairs/mldsa65/publickey.mjs +64 -0
  33. package/dist/keypairs/mldsa65/publickey.mjs.map +1 -0
  34. package/dist/multisig/publickey.d.mts +18 -3
  35. package/dist/multisig/publickey.d.mts.map +1 -1
  36. package/dist/multisig/publickey.mjs +29 -11
  37. package/dist/multisig/publickey.mjs.map +1 -1
  38. package/dist/transactions/Transaction.d.mts +6 -6
  39. package/dist/verify/verify.d.mts.map +1 -1
  40. package/dist/verify/verify.mjs +6 -2
  41. package/dist/verify/verify.mjs.map +1 -1
  42. package/dist/version.mjs +1 -1
  43. package/dist/version.mjs.map +1 -1
  44. package/dist/zklogin/address-seed.d.mts +6 -0
  45. package/dist/zklogin/address-seed.d.mts.map +1 -0
  46. package/dist/zklogin/address-seed.mjs +51 -0
  47. package/dist/zklogin/address-seed.mjs.map +1 -0
  48. package/dist/zklogin/address.d.mts.map +1 -1
  49. package/dist/zklogin/address.mjs +2 -1
  50. package/dist/zklogin/address.mjs.map +1 -1
  51. package/dist/zklogin/bcs.d.mts +14 -14
  52. package/dist/zklogin/index.d.mts +2 -1
  53. package/dist/zklogin/index.mjs +3 -2
  54. package/dist/zklogin/nonce.mjs +1 -1
  55. package/dist/zklogin/publickey.d.mts.map +1 -1
  56. package/dist/zklogin/publickey.mjs +2 -2
  57. package/dist/zklogin/publickey.mjs.map +1 -1
  58. package/dist/zklogin/utils.d.mts +1 -3
  59. package/dist/zklogin/utils.d.mts.map +1 -1
  60. package/dist/zklogin/utils.mjs +1 -46
  61. package/dist/zklogin/utils.mjs.map +1 -1
  62. package/docs/cryptography/index.md +7 -6
  63. package/docs/cryptography/keypairs.md +13 -1
  64. package/docs/llms-index.md +1 -1
  65. package/package.json +9 -3
  66. package/src/bcs/bcs.ts +73 -14
  67. package/src/cryptography/publickey.ts +1 -0
  68. package/src/cryptography/signature-scheme.ts +4 -1
  69. package/src/cryptography/signature.ts +1 -0
  70. package/src/keypairs/mldsa65/index.ts +5 -0
  71. package/src/keypairs/mldsa65/keypair.ts +128 -0
  72. package/src/keypairs/mldsa65/publickey.ts +95 -0
  73. package/src/multisig/publickey.ts +68 -23
  74. package/src/verify/verify.ts +8 -2
  75. package/src/version.ts +1 -1
  76. package/src/zklogin/address-seed.ts +86 -0
  77. package/src/zklogin/address.ts +2 -6
  78. package/src/zklogin/index.ts +1 -2
  79. package/src/zklogin/publickey.ts +4 -4
  80. package/src/zklogin/utils.ts +0 -83
@@ -25,14 +25,16 @@ type CompressedSignature =
25
25
  | { Secp256k1: Uint8Array }
26
26
  | { Secp256r1: Uint8Array }
27
27
  | { ZkLogin: Uint8Array }
28
- | { Passkey: Uint8Array };
28
+ | { Passkey: Uint8Array }
29
+ | { MLDSA65: Uint8Array };
29
30
 
30
31
  type PublicKeyEnum =
31
32
  | { ED25519: Uint8Array }
32
33
  | { Secp256k1: Uint8Array }
33
34
  | { Secp256r1: Uint8Array }
34
35
  | { ZkLogin: Uint8Array }
35
- | { Passkey: Uint8Array };
36
+ | { Passkey: Uint8Array }
37
+ | { MLDSA65: Uint8Array };
36
38
 
37
39
  type PubkeyEnumWeightPair = {
38
40
  pubKey: PublicKeyEnum;
@@ -69,6 +71,7 @@ export class MultiSigPublicKey extends PublicKey {
69
71
  weight: number;
70
72
  publicKey: PublicKey;
71
73
  }[];
74
+ #options: { client?: ClientWithCoreApi };
72
75
  /**
73
76
  * Create a new MultiSigPublicKey object
74
77
  */
@@ -81,6 +84,8 @@ export class MultiSigPublicKey extends PublicKey {
81
84
  ) {
82
85
  super();
83
86
 
87
+ this.#options = options;
88
+
84
89
  if (typeof value === 'string') {
85
90
  this.rawBytes = fromBase64(value);
86
91
 
@@ -141,21 +146,27 @@ export class MultiSigPublicKey extends PublicKey {
141
146
  static fromPublicKeys({
142
147
  threshold,
143
148
  publicKeys,
149
+ client,
144
150
  }: {
145
151
  threshold: number;
146
152
  publicKeys: { publicKey: PublicKey; weight: number }[];
153
+ /** Client used to verify zkLogin member signatures */
154
+ client?: ClientWithCoreApi;
147
155
  }) {
148
- return new MultiSigPublicKey({
149
- pk_map: publicKeys.map(({ publicKey, weight }) => {
150
- const scheme = SIGNATURE_FLAG_TO_SCHEME[publicKey.flag() as SignatureFlag];
151
-
152
- return {
153
- pubKey: { [scheme]: publicKey.toRawBytes() } as PublicKeyEnum,
154
- weight,
155
- };
156
- }),
157
- threshold,
158
- });
156
+ return new MultiSigPublicKey(
157
+ {
158
+ pk_map: publicKeys.map(({ publicKey, weight }) => {
159
+ const scheme = SIGNATURE_FLAG_TO_SCHEME[publicKey.flag() as SignatureFlag];
160
+
161
+ return {
162
+ pubKey: { [scheme]: publicKey.toRawBytes() } as PublicKeyEnum,
163
+ weight,
164
+ };
165
+ }),
166
+ threshold,
167
+ },
168
+ { client },
169
+ );
159
170
  }
160
171
 
161
172
  /**
@@ -188,21 +199,22 @@ export class MultiSigPublicKey extends PublicKey {
188
199
  * Return the Sui address associated with this MultiSig public key
189
200
  */
190
201
  override toSuiAddress(): string {
191
- // max length = 1 flag byte + (max pk size + max weight size (u8)) * max signer size + 2 threshold bytes (u16)
192
- const maxLength = 1 + (64 + 1) * MAX_SIGNER_IN_MULTISIG + 2;
193
- const tmp = new Uint8Array(maxLength);
202
+ const suiBytes = this.publicKeys.map(({ publicKey }) => publicKey.toSuiBytes());
203
+ // 1 flag byte + 2 threshold bytes (u16) + per member: flagged public key + 1 weight byte (u8)
204
+ const length = 3 + suiBytes.reduce((sum, bytes) => sum + bytes.length + 1, 0);
205
+ const tmp = new Uint8Array(length);
194
206
  tmp.set([SIGNATURE_SCHEME_TO_FLAG['MultiSig']]);
195
207
 
196
208
  tmp.set(bcs.u16().serialize(this.multisigPublicKey.threshold).toBytes(), 1);
197
209
  // The initial value 3 ensures that following data will be after the flag byte and threshold bytes
198
210
  let i = 3;
199
- for (const { publicKey, weight } of this.publicKeys) {
200
- const bytes = publicKey.toSuiBytes();
211
+ for (const [j, { weight }] of this.publicKeys.entries()) {
212
+ const bytes = suiBytes[j];
201
213
  tmp.set(bytes, i);
202
214
  i += bytes.length;
203
215
  tmp.set([weight], i++);
204
216
  }
205
- return normalizeSuiAddress(bytesToHex(blake2b(tmp.slice(0, i), { dkLen: 32 })));
217
+ return normalizeSuiAddress(bytesToHex(blake2b(tmp, { dkLen: 32 })));
206
218
  }
207
219
 
208
220
  /**
@@ -213,9 +225,38 @@ export class MultiSigPublicKey extends PublicKey {
213
225
  }
214
226
 
215
227
  /**
216
- * Verifies that the signature is valid for for the provided message
228
+ * Verifies that the signature is valid for the provided message
217
229
  */
218
230
  async verify(message: Uint8Array, multisigSignature: string): Promise<boolean> {
231
+ return this.#verifyMembers(multisigSignature, (publicKey, signature) =>
232
+ publicKey.verify(message, signature),
233
+ );
234
+ }
235
+
236
+ /**
237
+ * Verifies that the signature is valid for the provided PersonalMessage
238
+ */
239
+ override verifyPersonalMessage(message: Uint8Array, multisigSignature: string): Promise<boolean> {
240
+ // Each member verifies with its own intent-aware method, so members that cannot verify a
241
+ // raw digest (zkLogin, which is verified through the client) still work.
242
+ return this.#verifyMembers(multisigSignature, (publicKey, signature) =>
243
+ publicKey.verifyPersonalMessage(message, signature),
244
+ );
245
+ }
246
+
247
+ /**
248
+ * Verifies that the signature is valid for the provided Transaction
249
+ */
250
+ override verifyTransaction(transaction: Uint8Array, multisigSignature: string): Promise<boolean> {
251
+ return this.#verifyMembers(multisigSignature, (publicKey, signature) =>
252
+ publicKey.verifyTransaction(transaction, signature),
253
+ );
254
+ }
255
+
256
+ async #verifyMembers(
257
+ multisigSignature: string,
258
+ verifyMember: (publicKey: PublicKey, signature: Uint8Array) => Promise<boolean>,
259
+ ): Promise<boolean> {
219
260
  // Multisig verification only supports serialized signature
220
261
  const parsed = parseSerializedSignature(multisigSignature);
221
262
 
@@ -236,8 +277,11 @@ export class MultiSigPublicKey extends PublicKey {
236
277
  return false;
237
278
  }
238
279
 
239
- for (const { publicKey, weight, signature } of parsePartialSignatures(multisig)) {
240
- if (!(await publicKey.verify(message, signature))) {
280
+ for (const { publicKey, weight, signature } of parsePartialSignatures(
281
+ multisig,
282
+ this.#options,
283
+ )) {
284
+ if (!(await verifyMember(publicKey, signature))) {
241
285
  return false;
242
286
  }
243
287
 
@@ -302,7 +346,8 @@ export class MultiSigPublicKey extends PublicKey {
302
346
  bitmap,
303
347
  multisig_pk: this.multisigPublicKey,
304
348
  };
305
- const bytes = bcs.MultiSig.serialize(multisig, { maxSize: 8192 }).toBytes();
349
+ // Ten ML-DSA-65 members are ~53 KB of signatures and public keys.
350
+ const bytes = bcs.MultiSig.serialize(multisig, { maxSize: 65536 }).toBytes();
306
351
  const tmp = new Uint8Array(bytes.length + 1);
307
352
  tmp.set([SIGNATURE_SCHEME_TO_FLAG['MultiSig']]);
308
353
  tmp.set(bytes, 1);
@@ -6,6 +6,7 @@ import { fromBase64 } from '@mysten/bcs';
6
6
  import type { PublicKey, SignatureFlag, SignatureScheme } from '../cryptography/index.js';
7
7
  import { parseSerializedSignature, SIGNATURE_FLAG_TO_SCHEME } from '../cryptography/index.js';
8
8
  import { Ed25519PublicKey } from '../keypairs/ed25519/publickey.js';
9
+ import { MLDSA65PublicKey } from '../keypairs/mldsa65/publickey.js';
9
10
  import { PasskeyPublicKey } from '../keypairs/passkey/publickey.js';
10
11
  import { Secp256k1PublicKey } from '../keypairs/secp256k1/publickey.js';
11
12
  import { Secp256r1PublicKey } from '../keypairs/secp256r1/publickey.js';
@@ -110,7 +111,9 @@ function parseSignature(signature: string, options: { client?: ClientWithCoreApi
110
111
  if (parsedSignature.signatureScheme === 'MultiSig') {
111
112
  return {
112
113
  ...parsedSignature,
113
- publicKey: new MultiSigPublicKey(parsedSignature.multisig.multisig_pk),
114
+ publicKey: new MultiSigPublicKey(parsedSignature.multisig.multisig_pk, {
115
+ client: options.client,
116
+ }),
114
117
  };
115
118
  }
116
119
 
@@ -151,7 +154,7 @@ export function publicKeyFromRawBytes(
151
154
  publicKey = new Secp256r1PublicKey(bytes);
152
155
  break;
153
156
  case 'MultiSig':
154
- publicKey = new MultiSigPublicKey(bytes);
157
+ publicKey = new MultiSigPublicKey(bytes, { client: options.client });
155
158
  break;
156
159
  case 'ZkLogin':
157
160
  publicKey = ZkLoginPublicIdentifier.fromBytes(bytes, options);
@@ -159,6 +162,9 @@ export function publicKeyFromRawBytes(
159
162
  case 'Passkey':
160
163
  publicKey = new PasskeyPublicKey(bytes);
161
164
  break;
165
+ case 'MLDSA65':
166
+ publicKey = new MLDSA65PublicKey(bytes);
167
+ break;
162
168
  default:
163
169
  throw new Error(`Unsupported signature scheme ${signatureScheme}`);
164
170
  }
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
 
4
4
  // This file is generated by genversion.mjs. Do not edit it directly.
5
5
 
6
- export const PACKAGE_VERSION = '2.35.0';
6
+ export const PACKAGE_VERSION = '2.37.0';
@@ -0,0 +1,86 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { poseidonHash } from './poseidon.js';
5
+
6
+ const MAX_KEY_CLAIM_NAME_LENGTH = 32;
7
+ const MAX_KEY_CLAIM_VALUE_LENGTH = 115;
8
+ const MAX_AUD_VALUE_LENGTH = 145;
9
+ const PACK_WIDTH = 248;
10
+
11
+ /**
12
+ * Splits an array into chunks of size chunk_size. If the array is not evenly
13
+ * divisible by chunk_size, the first chunk will be smaller than chunk_size.
14
+ *
15
+ * E.g., arrayChunk([1, 2, 3, 4, 5], 2) => [[1], [2, 3], [4, 5]]
16
+ *
17
+ * Note: Can be made more efficient by avoiding the reverse() calls.
18
+ */
19
+ function chunkArray<T>(array: T[], chunk_size: number): T[][] {
20
+ const chunks = Array(Math.ceil(array.length / chunk_size));
21
+ const revArray = array.reverse();
22
+ for (let i = 0; i < chunks.length; i++) {
23
+ chunks[i] = revArray.slice(i * chunk_size, (i + 1) * chunk_size).reverse();
24
+ }
25
+ return chunks.reverse();
26
+ }
27
+
28
+ function bytesBEToBigInt(bytes: number[]): bigint {
29
+ const hex = bytes.map((b) => b.toString(16).padStart(2, '0')).join('');
30
+ if (hex.length === 0) {
31
+ return BigInt(0);
32
+ }
33
+ return BigInt('0x' + hex);
34
+ }
35
+
36
+ // hashes an ASCII string to a field element
37
+ export function hashASCIIStrToField(str: string, maxSize: number) {
38
+ if (str.length > maxSize) {
39
+ throw new Error(`String ${str} is longer than ${maxSize} chars`);
40
+ }
41
+
42
+ // Note: Padding with zeroes is safe because we are only using this function to map human-readable sequence of bytes.
43
+ // So the ASCII values of those characters will never be zero (null character).
44
+ const strPadded = str
45
+ .padEnd(maxSize, String.fromCharCode(0))
46
+ .split('')
47
+ .map((c) => c.charCodeAt(0));
48
+
49
+ const chunkSize = PACK_WIDTH / 8;
50
+ const packed = chunkArray(strPadded, chunkSize).map((chunk) => bytesBEToBigInt(chunk));
51
+ return poseidonHash(packed);
52
+ }
53
+
54
+ // Reject claim inputs whose decoded form reveals a JSON escape ('"', '\', control char):
55
+ // the circuit hashes raw JWT bytes, so an escaped value would derive a different address.
56
+ function assertNoJsonEscape(value: string, label: string) {
57
+ for (let i = 0; i < value.length; i++) {
58
+ const c = value.charCodeAt(i);
59
+ if (c < 0x20 || c === 0x22 || c === 0x5c) {
60
+ throw new Error(
61
+ `zkLogin ${label} contains a JSON-escaped character (code ${c}); the circuit ` +
62
+ `hashes raw JWT bytes, so claim values with escapes are not supported`,
63
+ );
64
+ }
65
+ }
66
+ }
67
+
68
+ export function genAddressSeed(
69
+ salt: string | bigint,
70
+ name: string,
71
+ value: string,
72
+ aud: string,
73
+ max_name_length = MAX_KEY_CLAIM_NAME_LENGTH,
74
+ max_value_length = MAX_KEY_CLAIM_VALUE_LENGTH,
75
+ max_aud_length = MAX_AUD_VALUE_LENGTH,
76
+ ): bigint {
77
+ assertNoJsonEscape(name, 'key claim name');
78
+ assertNoJsonEscape(value, 'key claim value');
79
+ assertNoJsonEscape(aud, 'aud');
80
+ return poseidonHash([
81
+ hashASCIIStrToField(name, max_name_length),
82
+ hashASCIIStrToField(value, max_value_length),
83
+ hashASCIIStrToField(aud, max_aud_length),
84
+ poseidonHash([BigInt(salt)]),
85
+ ]);
86
+ }
@@ -6,13 +6,9 @@ import { bytesToHex } from '@noble/hashes/utils.js';
6
6
 
7
7
  import { SIGNATURE_SCHEME_TO_FLAG } from '../cryptography/signature-scheme.js';
8
8
  import { normalizeSuiAddress, SUI_ADDRESS_LENGTH } from '../utils/index.js';
9
+ import { genAddressSeed } from './address-seed.js';
9
10
  import { decodeJwt } from './jwt-utils.js';
10
- import {
11
- genAddressSeed,
12
- normalizeZkLoginIssuer,
13
- toBigEndianBytes,
14
- toPaddedBigEndianBytes,
15
- } from './utils.js';
11
+ import { normalizeZkLoginIssuer, toBigEndianBytes, toPaddedBigEndianBytes } from './utils.js';
16
12
 
17
13
  export function computeZkLoginAddressFromSeed(
18
14
  addressSeed: bigint,
@@ -5,10 +5,9 @@ export { getZkLoginSignature, parseZkLoginSignature } from './signature.js';
5
5
  export {
6
6
  toBigEndianBytes,
7
7
  toPaddedBigEndianBytes,
8
- hashASCIIStrToField,
9
- genAddressSeed,
10
8
  getExtendedEphemeralPublicKey,
11
9
  } from './utils.js';
10
+ export { hashASCIIStrToField, genAddressSeed } from './address-seed.js';
12
11
  export { computeZkLoginAddressFromSeed, computeZkLoginAddress, jwtToAddress } from './address.js';
13
12
  export type { ComputeZkLoginAddressOptions } from './address.js';
14
13
  export { toZkLoginPublicIdentifier, ZkLoginPublicIdentifier } from './publickey.js';
@@ -168,10 +168,11 @@ export class ZkLoginPublicIdentifier extends PublicKey {
168
168
  */
169
169
  verifyPersonalMessage(message: Uint8Array, signature: Uint8Array | string): Promise<boolean> {
170
170
  const parsedSignature = parseSerializedZkLoginSignature(signature);
171
- const address = new ZkLoginPublicIdentifier(parsedSignature.publicKey).toSuiAddress();
172
171
 
173
172
  return graphqlVerifyZkLoginSignature({
174
- address: address,
173
+ // Verify against this identifier's address, not one derived from the signature, so a
174
+ // signature from a different zkLogin identity is rejected (as the chain does for multisig).
175
+ address: this.toSuiAddress(),
175
176
  bytes: toBase64(message),
176
177
  signature: parsedSignature.serializedSignature,
177
178
  intentScope: 'PersonalMessage',
@@ -184,9 +185,8 @@ export class ZkLoginPublicIdentifier extends PublicKey {
184
185
  */
185
186
  verifyTransaction(transaction: Uint8Array, signature: Uint8Array | string): Promise<boolean> {
186
187
  const parsedSignature = parseSerializedZkLoginSignature(signature);
187
- const address = new ZkLoginPublicIdentifier(parsedSignature.publicKey).toSuiAddress();
188
188
  return graphqlVerifyZkLoginSignature({
189
- address: address,
189
+ address: this.toSuiAddress(),
190
190
  bytes: toBase64(transaction),
191
191
  signature: parsedSignature.serializedSignature,
192
192
  intentScope: 'TransactionData',
@@ -4,12 +4,6 @@
4
4
  import { hexToBytes } from '@noble/hashes/utils.js';
5
5
 
6
6
  import type { PublicKey } from '../cryptography/publickey.js';
7
- import { poseidonHash } from './poseidon.js';
8
-
9
- const MAX_KEY_CLAIM_NAME_LENGTH = 32;
10
- const MAX_KEY_CLAIM_VALUE_LENGTH = 115;
11
- const MAX_AUD_VALUE_LENGTH = 145;
12
- const PACK_WIDTH = 248;
13
7
 
14
8
  function findFirstNonZeroIndex(bytes: Uint8Array) {
15
9
  for (let i = 0; i < bytes.length; i++) {
@@ -44,83 +38,6 @@ export function getExtendedEphemeralPublicKey(publicKey: PublicKey) {
44
38
  return publicKey.toSuiPublicKey();
45
39
  }
46
40
 
47
- /**
48
- * Splits an array into chunks of size chunk_size. If the array is not evenly
49
- * divisible by chunk_size, the first chunk will be smaller than chunk_size.
50
- *
51
- * E.g., arrayChunk([1, 2, 3, 4, 5], 2) => [[1], [2, 3], [4, 5]]
52
- *
53
- * Note: Can be made more efficient by avoiding the reverse() calls.
54
- */
55
- export function chunkArray<T>(array: T[], chunk_size: number): T[][] {
56
- const chunks = Array(Math.ceil(array.length / chunk_size));
57
- const revArray = array.reverse();
58
- for (let i = 0; i < chunks.length; i++) {
59
- chunks[i] = revArray.slice(i * chunk_size, (i + 1) * chunk_size).reverse();
60
- }
61
- return chunks.reverse();
62
- }
63
-
64
- function bytesBEToBigInt(bytes: number[]): bigint {
65
- const hex = bytes.map((b) => b.toString(16).padStart(2, '0')).join('');
66
- if (hex.length === 0) {
67
- return BigInt(0);
68
- }
69
- return BigInt('0x' + hex);
70
- }
71
-
72
- // hashes an ASCII string to a field element
73
- export function hashASCIIStrToField(str: string, maxSize: number) {
74
- if (str.length > maxSize) {
75
- throw new Error(`String ${str} is longer than ${maxSize} chars`);
76
- }
77
-
78
- // Note: Padding with zeroes is safe because we are only using this function to map human-readable sequence of bytes.
79
- // So the ASCII values of those characters will never be zero (null character).
80
- const strPadded = str
81
- .padEnd(maxSize, String.fromCharCode(0))
82
- .split('')
83
- .map((c) => c.charCodeAt(0));
84
-
85
- const chunkSize = PACK_WIDTH / 8;
86
- const packed = chunkArray(strPadded, chunkSize).map((chunk) => bytesBEToBigInt(chunk));
87
- return poseidonHash(packed);
88
- }
89
-
90
- // Reject claim inputs whose decoded form reveals a JSON escape ('"', '\', control char):
91
- // the circuit hashes raw JWT bytes, so an escaped value would derive a different address.
92
- function assertNoJsonEscape(value: string, label: string) {
93
- for (let i = 0; i < value.length; i++) {
94
- const c = value.charCodeAt(i);
95
- if (c < 0x20 || c === 0x22 || c === 0x5c) {
96
- throw new Error(
97
- `zkLogin ${label} contains a JSON-escaped character (code ${c}); the circuit ` +
98
- `hashes raw JWT bytes, so claim values with escapes are not supported`,
99
- );
100
- }
101
- }
102
- }
103
-
104
- export function genAddressSeed(
105
- salt: string | bigint,
106
- name: string,
107
- value: string,
108
- aud: string,
109
- max_name_length = MAX_KEY_CLAIM_NAME_LENGTH,
110
- max_value_length = MAX_KEY_CLAIM_VALUE_LENGTH,
111
- max_aud_length = MAX_AUD_VALUE_LENGTH,
112
- ): bigint {
113
- assertNoJsonEscape(name, 'key claim name');
114
- assertNoJsonEscape(value, 'key claim value');
115
- assertNoJsonEscape(aud, 'aud');
116
- return poseidonHash([
117
- hashASCIIStrToField(name, max_name_length),
118
- hashASCIIStrToField(value, max_value_length),
119
- hashASCIIStrToField(aud, max_aud_length),
120
- poseidonHash([BigInt(salt)]),
121
- ]);
122
- }
123
-
124
41
  export function normalizeZkLoginIssuer(iss: string) {
125
42
  if (iss === 'accounts.google.com') {
126
43
  return 'https://accounts.google.com';