@mysten/sui
Version:
Sui TypeScript API
1 lines • 2.08 kB
Source Map (JSON)
{"version":3,"file":"nonce.mjs","names":[],"sources":["../../src/zklogin/nonce.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toHex } from '@mysten/bcs';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { base64urlnopad } from '@scure/base';\n\nimport type { PublicKey } from '../cryptography/publickey.js';\nimport { poseidonHash } from './poseidon.js';\nimport { toPaddedBigEndianBytes } from './utils.js';\n\nexport const NONCE_LENGTH = 27;\n\nfunction toBigIntBE(bytes: Uint8Array) {\n\tconst hex = toHex(bytes);\n\tif (hex.length === 0) {\n\t\treturn BigInt(0);\n\t}\n\treturn BigInt(`0x${hex}`);\n}\n\nexport function generateRandomness() {\n\t// Once Node 20 enters LTS, we can just use crypto.getRandomValues(new Uint8Array(16)), but until then we use `randomBytes` to improve compatibility:\n\treturn String(toBigIntBE(randomBytes(16)));\n}\n\nexport function generateNonce(publicKey: PublicKey, maxEpoch: number, randomness: bigint | string) {\n\tconst publicKeyBytes = toBigIntBE(publicKey.toSuiBytes());\n\tconst eph_public_key_0 = publicKeyBytes / 2n ** 128n;\n\tconst eph_public_key_1 = publicKeyBytes % 2n ** 128n;\n\tconst bigNum = poseidonHash([eph_public_key_0, eph_public_key_1, maxEpoch, BigInt(randomness)]);\n\tconst Z = toPaddedBigEndianBytes(bigNum, 20);\n\tconst nonce = base64urlnopad.encode(Z);\n\n\tif (nonce.length !== NONCE_LENGTH) {\n\t\tthrow new Error(`Length of nonce ${nonce} (${nonce.length}) is not equal to ${NONCE_LENGTH}`);\n\t}\n\treturn nonce;\n}\n"],"mappings":";;;;;;;AAWA,MAAa,eAAe;AAE5B,SAAS,WAAW,OAAmB;CACtC,MAAM,MAAM,MAAM,MAAM;AACxB,KAAI,IAAI,WAAW,EAClB,QAAO,OAAO,EAAE;AAEjB,QAAO,OAAO,KAAK,MAAM;;AAG1B,SAAgB,qBAAqB;AAEpC,QAAO,OAAO,WAAW,YAAY,GAAG,CAAC,CAAC;;AAG3C,SAAgB,cAAc,WAAsB,UAAkB,YAA6B;CAClG,MAAM,iBAAiB,WAAW,UAAU,YAAY,CAAC;CAIzD,MAAM,IAAI,uBADK,aAAa;EAFH,iBAAiB,MAAM;EACvB,iBAAiB,MAAM;EACiB;EAAU,OAAO,WAAW;EAAC,CAAC,EACtD,GAAG;CAC5C,MAAM,QAAQ,eAAe,OAAO,EAAE;AAEtC,KAAI,MAAM,WAAW,aACpB,OAAM,IAAI,MAAM,mBAAmB,MAAM,IAAI,MAAM,OAAO,oBAAoB,eAAe;AAE9F,QAAO"}