@aztec-labs/blob-lib 6.0.0-nightly.20260829

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 (102) hide show
  1. package/dest/batched_blob.d.ts +31 -0
  2. package/dest/batched_blob.d.ts.map +1 -0
  3. package/dest/batched_blob.js +20 -0
  4. package/dest/blob.d.ts +121 -0
  5. package/dest/blob.d.ts.map +1 -0
  6. package/dest/blob.js +167 -0
  7. package/dest/blob_batching.d.ts +118 -0
  8. package/dest/blob_batching.d.ts.map +1 -0
  9. package/dest/blob_batching.js +225 -0
  10. package/dest/blob_utils.d.ts +40 -0
  11. package/dest/blob_utils.d.ts.map +1 -0
  12. package/dest/blob_utils.js +69 -0
  13. package/dest/circuit_types/blob_accumulator.d.ts +23 -0
  14. package/dest/circuit_types/blob_accumulator.d.ts.map +1 -0
  15. package/dest/circuit_types/blob_accumulator.js +62 -0
  16. package/dest/circuit_types/final_blob_accumulator.d.ts +23 -0
  17. package/dest/circuit_types/final_blob_accumulator.d.ts.map +1 -0
  18. package/dest/circuit_types/final_blob_accumulator.js +66 -0
  19. package/dest/circuit_types/final_blob_batching_challenges.d.ts +16 -0
  20. package/dest/circuit_types/final_blob_batching_challenges.d.ts.map +1 -0
  21. package/dest/circuit_types/final_blob_batching_challenges.js +26 -0
  22. package/dest/circuit_types/index.d.ts +4 -0
  23. package/dest/circuit_types/index.d.ts.map +1 -0
  24. package/dest/circuit_types/index.js +4 -0
  25. package/dest/encoding/block_blob_data.d.ts +26 -0
  26. package/dest/encoding/block_blob_data.d.ts.map +1 -0
  27. package/dest/encoding/block_blob_data.js +72 -0
  28. package/dest/encoding/block_end_marker.d.ts +11 -0
  29. package/dest/encoding/block_end_marker.d.ts.map +1 -0
  30. package/dest/encoding/block_end_marker.js +41 -0
  31. package/dest/encoding/block_end_state_field.d.ts +12 -0
  32. package/dest/encoding/block_end_state_field.d.ts.map +1 -0
  33. package/dest/encoding/block_end_state_field.js +39 -0
  34. package/dest/encoding/checkpoint_blob_data.d.ts +15 -0
  35. package/dest/encoding/checkpoint_blob_data.d.ts.map +1 -0
  36. package/dest/encoding/checkpoint_blob_data.js +66 -0
  37. package/dest/encoding/checkpoint_end_marker.d.ts +8 -0
  38. package/dest/encoding/checkpoint_end_marker.d.ts.map +1 -0
  39. package/dest/encoding/checkpoint_end_marker.js +28 -0
  40. package/dest/encoding/fixtures.d.ts +39 -0
  41. package/dest/encoding/fixtures.d.ts.map +1 -0
  42. package/dest/encoding/fixtures.js +139 -0
  43. package/dest/encoding/index.d.ts +10 -0
  44. package/dest/encoding/index.d.ts.map +1 -0
  45. package/dest/encoding/index.js +9 -0
  46. package/dest/encoding/tx_blob_data.d.ts +19 -0
  47. package/dest/encoding/tx_blob_data.d.ts.map +1 -0
  48. package/dest/encoding/tx_blob_data.js +79 -0
  49. package/dest/encoding/tx_start_marker.d.ts +16 -0
  50. package/dest/encoding/tx_start_marker.d.ts.map +1 -0
  51. package/dest/encoding/tx_start_marker.js +77 -0
  52. package/dest/errors.d.ts +4 -0
  53. package/dest/errors.d.ts.map +1 -0
  54. package/dest/errors.js +6 -0
  55. package/dest/hash.d.ts +44 -0
  56. package/dest/hash.d.ts.map +1 -0
  57. package/dest/hash.js +82 -0
  58. package/dest/index.d.ts +11 -0
  59. package/dest/index.d.ts.map +1 -0
  60. package/dest/index.js +10 -0
  61. package/dest/interface.d.ts +8 -0
  62. package/dest/interface.d.ts.map +1 -0
  63. package/dest/interface.js +3 -0
  64. package/dest/kzg_context.d.ts +14 -0
  65. package/dest/kzg_context.d.ts.map +1 -0
  66. package/dest/kzg_context.js +37 -0
  67. package/dest/sponge_blob.d.ts +50 -0
  68. package/dest/sponge_blob.d.ts.map +1 -0
  69. package/dest/sponge_blob.js +144 -0
  70. package/dest/testing.d.ts +31 -0
  71. package/dest/testing.d.ts.map +1 -0
  72. package/dest/testing.js +66 -0
  73. package/dest/types.d.ts +17 -0
  74. package/dest/types.d.ts.map +1 -0
  75. package/dest/types.js +4 -0
  76. package/package.json +91 -0
  77. package/src/batched_blob.ts +26 -0
  78. package/src/blob.ts +191 -0
  79. package/src/blob_batching.ts +303 -0
  80. package/src/blob_utils.ts +84 -0
  81. package/src/circuit_types/blob_accumulator.ts +96 -0
  82. package/src/circuit_types/final_blob_accumulator.ts +75 -0
  83. package/src/circuit_types/final_blob_batching_challenges.ts +30 -0
  84. package/src/circuit_types/index.ts +4 -0
  85. package/src/encoding/block_blob_data.ts +113 -0
  86. package/src/encoding/block_end_marker.ts +55 -0
  87. package/src/encoding/block_end_state_field.ts +59 -0
  88. package/src/encoding/checkpoint_blob_data.ts +100 -0
  89. package/src/encoding/checkpoint_end_marker.ts +40 -0
  90. package/src/encoding/fixtures.ts +202 -0
  91. package/src/encoding/index.ts +9 -0
  92. package/src/encoding/tx_blob_data.ts +116 -0
  93. package/src/encoding/tx_start_marker.ts +97 -0
  94. package/src/errors.ts +6 -0
  95. package/src/hash.ts +94 -0
  96. package/src/index.ts +10 -0
  97. package/src/interface.ts +7 -0
  98. package/src/kzg_context.ts +48 -0
  99. package/src/sponge_blob.ts +175 -0
  100. package/src/testing.ts +94 -0
  101. package/src/trusted_setup_bit_reversed.json +4100 -0
  102. package/src/types.ts +17 -0
@@ -0,0 +1,79 @@
1
+ import { chunk } from '@aztec-labs/foundation/collection';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import { FieldReader } from '@aztec-labs/foundation/serialize';
4
+ import { BlobDeserializationError } from '../errors.js';
5
+ import { decodeTxStartMarker, encodeTxStartMarker } from './tx_start_marker.js';
6
+ export function encodeTxBlobData(txBlobData) {
7
+ return [
8
+ encodeTxStartMarker(txBlobData.txStartMarker),
9
+ txBlobData.txHash,
10
+ txBlobData.transactionFee,
11
+ ...txBlobData.noteHashes,
12
+ ...txBlobData.nullifiers,
13
+ ...txBlobData.l2ToL1Msgs,
14
+ ...txBlobData.publicDataWrites.flat(),
15
+ ...txBlobData.privateLogs.map((log)=>[
16
+ new Fr(log.length),
17
+ ...log
18
+ ]).flat(),
19
+ ...txBlobData.publicLogs,
20
+ ...txBlobData.contractClassLog
21
+ ];
22
+ }
23
+ export function decodeTxBlobData(fields) {
24
+ const reader = FieldReader.asReader(fields);
25
+ if (reader.isFinished()) {
26
+ throw new BlobDeserializationError(`Incorrect encoding of blob fields: not enough fields for tx blob data.`);
27
+ }
28
+ const txStartMarker = decodeTxStartMarker(reader.readField());
29
+ const checkRemainingFields = (requiredFields, type)=>{
30
+ if (requiredFields > reader.remainingFields()) {
31
+ throw new BlobDeserializationError(`Incorrect encoding of blob fields: not enough fields for ${type}. Expected ${requiredFields} fields, only ${reader.remainingFields()} remaining.`);
32
+ }
33
+ };
34
+ const numTxEffectFields = txStartMarker.numBlobFields - 1; // -1 because we already read the tx start marker.
35
+ checkRemainingFields(numTxEffectFields, 'tx effect');
36
+ const txHash = reader.readField();
37
+ const transactionFee = reader.readField();
38
+ checkRemainingFields(txStartMarker.numNoteHashes, 'note hashes');
39
+ const noteHashes = reader.readFieldArray(txStartMarker.numNoteHashes);
40
+ checkRemainingFields(txStartMarker.numNullifiers, 'nullifiers');
41
+ const nullifiers = reader.readFieldArray(txStartMarker.numNullifiers);
42
+ checkRemainingFields(txStartMarker.numL2ToL1Msgs, 'l2-to-l1 messages');
43
+ const l2ToL1Msgs = reader.readFieldArray(txStartMarker.numL2ToL1Msgs);
44
+ checkRemainingFields(txStartMarker.numPublicDataWrites * 2, 'public data writes'); // *2 for leaf slot and value
45
+ const publicDataWrites = chunk(reader.readFieldArray(txStartMarker.numPublicDataWrites * 2), 2);
46
+ const privateLogs = Array.from({
47
+ length: txStartMarker.numPrivateLogs
48
+ }, ()=>{
49
+ const length = reader.readU32();
50
+ checkRemainingFields(length, 'private log');
51
+ return reader.readFieldArray(length);
52
+ });
53
+ checkRemainingFields(txStartMarker.publicLogsLength, 'public logs');
54
+ const publicLogs = reader.readFieldArray(txStartMarker.publicLogsLength);
55
+ const contractClassLogBlobDataLength = txStartMarker.contractClassLogLength > 0 ? txStartMarker.contractClassLogLength + 1 : 0; // If the log exists, +1 for the contract address
56
+ checkRemainingFields(contractClassLogBlobDataLength, 'contract class logs');
57
+ const contractClassLog = reader.readFieldArray(contractClassLogBlobDataLength);
58
+ return {
59
+ txStartMarker,
60
+ txHash,
61
+ transactionFee,
62
+ noteHashes,
63
+ nullifiers,
64
+ l2ToL1Msgs,
65
+ publicDataWrites,
66
+ privateLogs,
67
+ publicLogs,
68
+ contractClassLog
69
+ };
70
+ }
71
+ export function getNumTxBlobFields(txStartMarker) {
72
+ return 1 + // tx start marker
73
+ 1 + // tx hash
74
+ 1 + // transaction fee
75
+ txStartMarker.numNoteHashes + txStartMarker.numNullifiers + txStartMarker.numL2ToL1Msgs + txStartMarker.numPublicDataWrites * 2 + // *2 for leaf slot and value per public data write
76
+ txStartMarker.numPrivateLogs + // +1 length field for each private log
77
+ txStartMarker.privateLogsLength + txStartMarker.publicLogsLength + txStartMarker.contractClassLogLength + (txStartMarker.contractClassLogLength > 0 ? 1 : 0 // +1 for contract address of the contract class log
78
+ );
79
+ }
@@ -0,0 +1,16 @@
1
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
2
+ export interface TxStartMarker {
3
+ numBlobFields: number;
4
+ revertCode: number;
5
+ numNoteHashes: number;
6
+ numNullifiers: number;
7
+ numL2ToL1Msgs: number;
8
+ numPublicDataWrites: number;
9
+ numPrivateLogs: number;
10
+ privateLogsLength: number;
11
+ publicLogsLength: number;
12
+ contractClassLogLength: number;
13
+ }
14
+ export declare function encodeTxStartMarker(txStartMarker: TxStartMarker): Fr;
15
+ export declare function decodeTxStartMarker(field: Fr): TxStartMarker;
16
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHhfc3RhcnRfbWFya2VyLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZW5jb2RpbmcvdHhfc3RhcnRfbWFya2VyLnRzIl0sIm5hbW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,CAAC;CAChC;AAED,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,aAAa,GAAG,EAAE,CAuBpE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,EAAE,GAAG,aAAa,CAwC5D"}
@@ -0,0 +1,77 @@
1
+ import { TX_START_PREFIX } from '@aztec-labs/constants';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import { BlobDeserializationError } from '../errors.js';
4
+ // Must match the implementation in `noir-protocol-circuits/crates/types/src/blob_data/tx_blob_data.nr`.
5
+ const NUM_BLOB_FIELDS_BIT_SIZE = 32n;
6
+ const REVERT_CODE_BIT_SIZE = 8n;
7
+ const NUM_NOTE_HASH_BIT_SIZE = 16n;
8
+ const NUM_NULLIFIER_BIT_SIZE = 16n;
9
+ const NUM_L2_TO_L1_MSG_BIT_SIZE = 16n;
10
+ const NUM_PUBLIC_DATA_WRITE_BIT_SIZE = 16n;
11
+ const NUM_PRIVATE_LOG_BIT_SIZE = 16n;
12
+ const PRIVATE_LOGS_LENGTH_BIT_SIZE = 16n;
13
+ const PUBLIC_LOGS_LENGTH_BIT_SIZE = 32n;
14
+ const CONTRACT_CLASS_LOG_LENGTH_BIT_SIZE = 16n;
15
+ export function encodeTxStartMarker(txStartMarker) {
16
+ let value = BigInt(TX_START_PREFIX);
17
+ value <<= NUM_NOTE_HASH_BIT_SIZE;
18
+ value += BigInt(txStartMarker.numNoteHashes);
19
+ value <<= NUM_NULLIFIER_BIT_SIZE;
20
+ value += BigInt(txStartMarker.numNullifiers);
21
+ value <<= NUM_L2_TO_L1_MSG_BIT_SIZE;
22
+ value += BigInt(txStartMarker.numL2ToL1Msgs);
23
+ value <<= NUM_PUBLIC_DATA_WRITE_BIT_SIZE;
24
+ value += BigInt(txStartMarker.numPublicDataWrites);
25
+ value <<= NUM_PRIVATE_LOG_BIT_SIZE;
26
+ value += BigInt(txStartMarker.numPrivateLogs);
27
+ value <<= PRIVATE_LOGS_LENGTH_BIT_SIZE;
28
+ value += BigInt(txStartMarker.privateLogsLength);
29
+ value <<= PUBLIC_LOGS_LENGTH_BIT_SIZE;
30
+ value += BigInt(txStartMarker.publicLogsLength);
31
+ value <<= CONTRACT_CLASS_LOG_LENGTH_BIT_SIZE;
32
+ value += BigInt(txStartMarker.contractClassLogLength);
33
+ value <<= REVERT_CODE_BIT_SIZE;
34
+ value += BigInt(txStartMarker.revertCode);
35
+ value <<= NUM_BLOB_FIELDS_BIT_SIZE;
36
+ value += BigInt(txStartMarker.numBlobFields);
37
+ return new Fr(value);
38
+ }
39
+ export function decodeTxStartMarker(field) {
40
+ let value = field.toBigInt();
41
+ const numBlobFields = Number(value & 2n ** NUM_BLOB_FIELDS_BIT_SIZE - 1n);
42
+ value >>= NUM_BLOB_FIELDS_BIT_SIZE;
43
+ const revertCode = Number(value & 2n ** REVERT_CODE_BIT_SIZE - 1n);
44
+ value >>= REVERT_CODE_BIT_SIZE;
45
+ const contractClassLogLength = Number(value & 2n ** CONTRACT_CLASS_LOG_LENGTH_BIT_SIZE - 1n);
46
+ value >>= CONTRACT_CLASS_LOG_LENGTH_BIT_SIZE;
47
+ const publicLogsLength = Number(value & 2n ** PUBLIC_LOGS_LENGTH_BIT_SIZE - 1n);
48
+ value >>= PUBLIC_LOGS_LENGTH_BIT_SIZE;
49
+ const privateLogsLength = Number(value & 2n ** PRIVATE_LOGS_LENGTH_BIT_SIZE - 1n);
50
+ value >>= PRIVATE_LOGS_LENGTH_BIT_SIZE;
51
+ const numPrivateLogs = Number(value & 2n ** NUM_PRIVATE_LOG_BIT_SIZE - 1n);
52
+ value >>= NUM_PRIVATE_LOG_BIT_SIZE;
53
+ const numPublicDataWrites = Number(value & 2n ** NUM_PUBLIC_DATA_WRITE_BIT_SIZE - 1n);
54
+ value >>= NUM_PUBLIC_DATA_WRITE_BIT_SIZE;
55
+ const numL2ToL1Msgs = Number(value & 2n ** NUM_L2_TO_L1_MSG_BIT_SIZE - 1n);
56
+ value >>= NUM_L2_TO_L1_MSG_BIT_SIZE;
57
+ const numNullifiers = Number(value & 2n ** NUM_NULLIFIER_BIT_SIZE - 1n);
58
+ value >>= NUM_NULLIFIER_BIT_SIZE;
59
+ const numNoteHashes = Number(value & 2n ** NUM_NOTE_HASH_BIT_SIZE - 1n);
60
+ value >>= NUM_NOTE_HASH_BIT_SIZE;
61
+ const prefix = value;
62
+ if (prefix !== BigInt(TX_START_PREFIX)) {
63
+ throw new BlobDeserializationError(`Incorrect encoding of blob fields: invalid tx start marker.`);
64
+ }
65
+ return {
66
+ numBlobFields,
67
+ revertCode,
68
+ numNoteHashes,
69
+ numNullifiers,
70
+ numL2ToL1Msgs,
71
+ numPublicDataWrites,
72
+ numPrivateLogs,
73
+ privateLogsLength,
74
+ publicLogsLength,
75
+ contractClassLogLength
76
+ };
77
+ }
@@ -0,0 +1,4 @@
1
+ export declare class BlobDeserializationError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvZXJyb3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLHFCQUFhLHdCQUF5QixTQUFRLEtBQUs7SUFDakQsWUFBWSxPQUFPLEVBQUUsTUFBTSxFQUcxQjtDQUNGIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF"}
package/dest/errors.js ADDED
@@ -0,0 +1,6 @@
1
+ export class BlobDeserializationError extends Error {
2
+ constructor(message){
3
+ super(message);
4
+ this.name = 'BlobDeserializationError';
5
+ }
6
+ }
package/dest/hash.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { BLS12Fr } from '@aztec-labs/foundation/curves/bls12';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ /**
4
+ * Returns ethereum's versioned blob hash, following kzg_to_versioned_hash: https://eips.ethereum.org/EIPS/eip-4844#helpers
5
+ */
6
+ export declare function computeEthVersionedBlobHash(commitment: Buffer): Buffer;
7
+ export declare function computeBlobsHash(evmVersionedBlobHashes: Buffer[]): Fr;
8
+ /**
9
+ * Computes a non-standard Poseidon2 hash over the provided fields.
10
+ *
11
+ * This function is used to compute:
12
+ * - `blobFieldsHash` of a checkpoint:
13
+ * Verified in the circuit against all fields absorbed into the blob sponge over the entire checkpoint.
14
+ * The exact number of fields is encoded in the checkpoint end marker (the last field).
15
+ * This hash is used when generating the challenge `z` for all blobs in the checkpoint.
16
+ * - `spongeBlobHash` of a block:
17
+ * Computed from the block's tx effects, its end-state, and the blob fields of all prior blocks in the same checkpoint.
18
+ * This hash is included in the block header.
19
+ */
20
+ export declare function computeBlobFieldsHash(fields: Fr[]): Promise<Fr>;
21
+ export declare function computeBlobCommitment(data: Uint8Array): Promise<Buffer>;
22
+ /**
23
+ * Get the commitment fields of the blob, to compute the challenge z.
24
+ *
25
+ * The 48-byte commitment is encoded into two field elements:
26
+ * +-------------------+------------------------+
27
+ * | 31 bytes | 17 bytes |
28
+ * +-------------------+------------------------+
29
+ * | Field Element 1 | Field Element 2 |
30
+ * | [0][bytes 0-30] | [0...0][bytes 31-47] |
31
+ * +-------------------+------------------------+
32
+ *
33
+ * @param commitment - The commitment to convert to fields. Computed from `computeBlobCommitment`.
34
+ * @returns The fields representing the commitment buffer.
35
+ */
36
+ export declare function commitmentToFields(commitment: Buffer): [Fr, Fr];
37
+ export declare function computeChallengeZ(blobFieldsHash: Fr, commitment: Buffer): Promise<Fr>;
38
+ /**
39
+ * Hash the u128 limbs of a BLS field's noir bignum representation under the `BLOB_HASHED_Y_LIMBS` separator.
40
+ * Used to commit to blob evaluation values `y_i` before folding them into the gamma accumulator; mirrors the
41
+ * hash accumulation performed in the rollup circuits.
42
+ */
43
+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Q0FBQyxFQUFFLENBQUMsQ0FHaEUifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../src/hash.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,qCAAqC,CAAC;AAC9D,OAAO,EAAE,EAAE,EAAE,MAAM,qCAAqC,CAAC;AAOzD;;GAEG;AACH,wBAAgB,2BAA2B,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAItE;AAOD,wBAAgB,gBAAgB,CAAC,sBAAsB,EAAE,MAAM,EAAE,GAAG,EAAE,CAErE;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,EAAE,CAAC,CAIrE;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAM7E;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAM/D;AAED,wBAAsB,iBAAiB,CAAC,cAAc,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC,CAM3F;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,EAAE,CAAC,CAGhE"}
package/dest/hash.js ADDED
@@ -0,0 +1,82 @@
1
+ import { DomainSeparator } from '@aztec-labs/constants';
2
+ import { poseidon2HashWithSeparator } from '@aztec-labs/foundation/crypto/poseidon';
3
+ import { sha256, sha256ToField } from '@aztec-labs/foundation/crypto/sha256';
4
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
5
+ import { getBytesPerBlob, getBytesPerCommitment, getKzg } from './kzg_context.js';
6
+ import { SpongeBlob } from './sponge_blob.js';
7
+ const VERSIONED_HASH_VERSION_KZG = 0x01;
8
+ /**
9
+ * Returns ethereum's versioned blob hash, following kzg_to_versioned_hash: https://eips.ethereum.org/EIPS/eip-4844#helpers
10
+ */ export function computeEthVersionedBlobHash(commitment) {
11
+ const hash = sha256(commitment);
12
+ hash[0] = VERSIONED_HASH_VERSION_KZG;
13
+ return hash;
14
+ }
15
+ // TODO(#13430): The blobsHash is confusingly similar to blobCommitmentsHash, calculated from below blobCommitments:
16
+ // - blobsHash := sha256([blobhash_0, ..., blobhash_m]) = a hash of all blob hashes in a block with m+1 blobs inserted into the header, exists so a user can cross check blobs.
17
+ // - blobCommitmentsHash := sha256( ...sha256(sha256(C_0), C_1) ... C_n) = iteratively calculated hash of all blob commitments in an epoch with n+1 blobs (see calculateBlobCommitmentsHash()),
18
+ // exists so we can validate injected commitments to the rollup circuits correspond to the correct real blobs.
19
+ // We may be able to combine these values e.g. blobCommitmentsHash := sha256( ...sha256(sha256(blobshash_0), blobshash_1) ... blobshash_l) for an epoch with l+1 blocks.
20
+ export function computeBlobsHash(evmVersionedBlobHashes) {
21
+ return sha256ToField(evmVersionedBlobHashes);
22
+ }
23
+ /**
24
+ * Computes a non-standard Poseidon2 hash over the provided fields.
25
+ *
26
+ * This function is used to compute:
27
+ * - `blobFieldsHash` of a checkpoint:
28
+ * Verified in the circuit against all fields absorbed into the blob sponge over the entire checkpoint.
29
+ * The exact number of fields is encoded in the checkpoint end marker (the last field).
30
+ * This hash is used when generating the challenge `z` for all blobs in the checkpoint.
31
+ * - `spongeBlobHash` of a block:
32
+ * Computed from the block's tx effects, its end-state, and the blob fields of all prior blocks in the same checkpoint.
33
+ * This hash is included in the block header.
34
+ */ export async function computeBlobFieldsHash(fields) {
35
+ const sponge = SpongeBlob.init();
36
+ await sponge.absorb(fields);
37
+ return sponge.squeeze();
38
+ }
39
+ export async function computeBlobCommitment(data) {
40
+ if (data.length !== getBytesPerBlob()) {
41
+ throw new Error(`Expected ${getBytesPerBlob()} bytes per blob. Got ${data.length}.`);
42
+ }
43
+ return Buffer.from(await getKzg().asyncBlobToKzgCommitment(data));
44
+ }
45
+ /**
46
+ * Get the commitment fields of the blob, to compute the challenge z.
47
+ *
48
+ * The 48-byte commitment is encoded into two field elements:
49
+ * +-------------------+------------------------+
50
+ * | 31 bytes | 17 bytes |
51
+ * +-------------------+------------------------+
52
+ * | Field Element 1 | Field Element 2 |
53
+ * | [0][bytes 0-30] | [0...0][bytes 31-47] |
54
+ * +-------------------+------------------------+
55
+ *
56
+ * @param commitment - The commitment to convert to fields. Computed from `computeBlobCommitment`.
57
+ * @returns The fields representing the commitment buffer.
58
+ */ export function commitmentToFields(commitment) {
59
+ if (commitment.length !== getBytesPerCommitment()) {
60
+ throw new Error(`Expected ${getBytesPerCommitment()} bytes for blob commitment. Got ${commitment.length}.`);
61
+ }
62
+ return [
63
+ new Fr(commitment.subarray(0, 31)),
64
+ new Fr(commitment.subarray(31, getBytesPerCommitment()))
65
+ ];
66
+ }
67
+ export async function computeChallengeZ(blobFieldsHash, commitment) {
68
+ const commitmentFields = commitmentToFields(commitment);
69
+ return await poseidon2HashWithSeparator([
70
+ blobFieldsHash,
71
+ commitmentFields[0],
72
+ commitmentFields[1]
73
+ ], DomainSeparator.BLOB_CHALLENGE_Z);
74
+ }
75
+ /**
76
+ * Hash the u128 limbs of a BLS field's noir bignum representation under the `BLOB_HASHED_Y_LIMBS` separator.
77
+ * Used to commit to blob evaluation values `y_i` before folding them into the gamma accumulator; mirrors the
78
+ * hash accumulation performed in the rollup circuits.
79
+ */ export async function hashBlobYLimbs(field) {
80
+ const num = field.toNoirBigNum();
81
+ return await poseidon2HashWithSeparator(num.limbs.map(Fr.fromHexString), DomainSeparator.BLOB_HASHED_Y_LIMBS);
82
+ }
@@ -0,0 +1,11 @@
1
+ export * from './batched_blob.js';
2
+ export * from './blob.js';
3
+ export * from './blob_batching.js';
4
+ export * from './blob_utils.js';
5
+ export * from './circuit_types/index.js';
6
+ export * from './encoding/index.js';
7
+ export * from './hash.js';
8
+ export * from './interface.js';
9
+ export * from './sponge_blob.js';
10
+ export * from './kzg_context.js';
11
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxjQUFjLG1CQUFtQixDQUFDO0FBQ2xDLGNBQWMsV0FBVyxDQUFDO0FBQzFCLGNBQWMsb0JBQW9CLENBQUM7QUFDbkMsY0FBYyxpQkFBaUIsQ0FBQztBQUNoQyxjQUFjLDBCQUEwQixDQUFDO0FBQ3pDLGNBQWMscUJBQXFCLENBQUM7QUFDcEMsY0FBYyxXQUFXLENBQUM7QUFDMUIsY0FBYyxnQkFBZ0IsQ0FBQztBQUMvQixjQUFjLGtCQUFrQixDQUFDO0FBQ2pDLGNBQWMsa0JBQWtCLENBQUMifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,qBAAqB,CAAC;AACpC,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC"}
package/dest/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from './batched_blob.js';
2
+ export * from './blob.js';
3
+ export * from './blob_batching.js';
4
+ export * from './blob_utils.js';
5
+ export * from './circuit_types/index.js';
6
+ export * from './encoding/index.js';
7
+ export * from './hash.js';
8
+ export * from './interface.js';
9
+ export * from './sponge_blob.js';
10
+ export * from './kzg_context.js';
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The relevant parts of a response from https://ethereum.github.io/beacon-APIs/?urls.primaryName=dev#/Beacon/getBlobSidecars
3
+ */
4
+ export interface BlobJson {
5
+ blob: string;
6
+ kzg_commitment: string;
7
+ }
8
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJmYWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsTUFBTSxXQUFXLFFBQVE7SUFDdkIsSUFBSSxFQUFFLE1BQU0sQ0FBQztJQUNiLGNBQWMsRUFBRSxNQUFNLENBQUM7Q0FDeEIifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interface.d.ts","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;CACxB"}
@@ -0,0 +1,3 @@
1
+ /**
2
+ * The relevant parts of a response from https://ethereum.github.io/beacon-APIs/?urls.primaryName=dev#/Beacon/getBlobSidecars
3
+ */ export { };
@@ -0,0 +1,14 @@
1
+ import type { Logger } from '@aztec-labs/foundation/log';
2
+ import type { DasContextJs } from '@crate-crypto/node-eth-kzg';
3
+ export type { DasContextJs } from '@crate-crypto/node-eth-kzg';
4
+ export declare function getBytesPerBlob(): number;
5
+ export declare function getBytesPerCommitment(): number;
6
+ /**
7
+ * Returns the lazily-initialized KZG context. The first call synchronously builds the
8
+ * precomputation tables (~2s locally, blocking the event loop; longer under constrained CPU), so
9
+ * callers on a latency-sensitive path should warm it ahead of time. Pass a logger to record how
10
+ * long that first build took.
11
+ * @param logger - Optional logger; when provided, the initial table build is timed and logged.
12
+ */
13
+ export declare function getKzg(logger?: Logger): DasContextJs;
14
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia3pnX2NvbnRleHQuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9remdfY29udGV4dC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxNQUFNLEVBQUUsTUFBTSw0QkFBNEIsQ0FBQztBQUV6RCxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSw0QkFBNEIsQ0FBQztBQU0vRCxZQUFZLEVBQUUsWUFBWSxFQUFFLE1BQU0sNEJBQTRCLENBQUM7QUFlL0Qsd0JBQWdCLGVBQWUsSUFBSSxNQUFNLENBRXhDO0FBRUQsd0JBQWdCLHFCQUFxQixJQUFJLE1BQU0sQ0FFOUM7QUFJRDs7Ozs7O0dBTUc7QUFDSCx3QkFBZ0IsTUFBTSxDQUFDLE1BQU0sQ0FBQyxFQUFFLE1BQU0sR0FBRyxZQUFZLENBT3BEIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kzg_context.d.ts","sourceRoot":"","sources":["../src/kzg_context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAM/D,YAAY,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAe/D,wBAAgB,eAAe,IAAI,MAAM,CAExC;AAED,wBAAgB,qBAAqB,IAAI,MAAM,CAE9C;AAID;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,YAAY,CAOpD"}
@@ -0,0 +1,37 @@
1
+ import { elapsedSync } from '@aztec-labs/foundation/timer';
2
+ import { createRequire } from 'module';
3
+ let nativeModule;
4
+ /** Lazily loads the @crate-crypto/node-eth-kzg native module. */ function loadNativeModule() {
5
+ if (!nativeModule) {
6
+ const require = createRequire(import.meta.url);
7
+ nativeModule = require('@crate-crypto/node-eth-kzg');
8
+ }
9
+ return nativeModule;
10
+ }
11
+ // Ethereum blob constants, loaded lazily from the native module.
12
+ // Values: BYTES_PER_BLOB=131072, BYTES_PER_COMMITMENT=48
13
+ export function getBytesPerBlob() {
14
+ return loadNativeModule().BYTES_PER_BLOB;
15
+ }
16
+ export function getBytesPerCommitment() {
17
+ return loadNativeModule().BYTES_PER_COMMITMENT;
18
+ }
19
+ let kzgInstance;
20
+ /**
21
+ * Returns the lazily-initialized KZG context. The first call synchronously builds the
22
+ * precomputation tables (~2s locally, blocking the event loop; longer under constrained CPU), so
23
+ * callers on a latency-sensitive path should warm it ahead of time. Pass a logger to record how
24
+ * long that first build took.
25
+ * @param logger - Optional logger; when provided, the initial table build is timed and logged.
26
+ */ export function getKzg(logger) {
27
+ if (!kzgInstance) {
28
+ const [durationMs, instance] = elapsedSync(()=>loadNativeModule().DasContextJs.create({
29
+ usePrecomp: true
30
+ }));
31
+ kzgInstance = instance;
32
+ logger?.verbose(`Loaded KZG trusted setup`, {
33
+ durationMs
34
+ });
35
+ }
36
+ return kzgInstance;
37
+ }
@@ -0,0 +1,50 @@
1
+ import { type FieldsOf } from '@aztec-labs/foundation/array';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import { BufferReader, FieldReader, type Tuple } from '@aztec-labs/foundation/serialize';
4
+ /**
5
+ * A Poseidon2 sponge used to accumulate data that will be added to blobs.
6
+ * See noir-projects/fnd/noir-protocol-circuits/crates/types/src/blob_data/sponge_blob.nr.
7
+ */
8
+ export declare class SpongeBlob {
9
+ /** Sponge with absorbed fields that will go into one or more blobs. */
10
+ readonly sponge: Poseidon2Sponge;
11
+ /** Number of effects absorbed so far. */
12
+ numAbsorbedFields: number;
13
+ static MAX_FIELDS: number;
14
+ constructor(
15
+ /** Sponge with absorbed fields that will go into one or more blobs. */
16
+ sponge: Poseidon2Sponge,
17
+ /** Number of effects absorbed so far. */
18
+ numAbsorbedFields: number);
19
+ /**
20
+ * Initialize the sponge blob to absorb data for a checkpoint.
21
+ */
22
+ static init(): SpongeBlob;
23
+ static fromBuffer(buffer: Buffer | BufferReader): SpongeBlob;
24
+ toBuffer(): Buffer<ArrayBufferLike>;
25
+ static getFields(fields: FieldsOf<SpongeBlob>): (number | Poseidon2Sponge)[];
26
+ toFields(): Fr[];
27
+ static fromFields(fields: Fr[] | FieldReader): SpongeBlob;
28
+ clone(): SpongeBlob;
29
+ absorb(fields: Fr[]): Promise<void>;
30
+ squeeze(): Promise<Fr>;
31
+ static empty(): SpongeBlob;
32
+ }
33
+ export declare class Poseidon2Sponge {
34
+ cache: Tuple<Fr, 3>;
35
+ state: Tuple<Fr, 4>;
36
+ cacheSize: number;
37
+ squeezeMode: boolean;
38
+ constructor(cache: Tuple<Fr, 3>, state: Tuple<Fr, 4>, cacheSize: number, squeezeMode: boolean);
39
+ static fromBuffer(buffer: Buffer | BufferReader): Poseidon2Sponge;
40
+ toBuffer(): Buffer<ArrayBufferLike>;
41
+ static getFields(fields: FieldsOf<Poseidon2Sponge>): (number | boolean | [Fr, Fr, Fr] | [Fr, Fr, Fr, Fr])[];
42
+ toFields(): Fr[];
43
+ static fromFields(fields: Fr[] | FieldReader): Poseidon2Sponge;
44
+ static empty(): Poseidon2Sponge;
45
+ static init(iv: Fr): Poseidon2Sponge;
46
+ performDuplex(): Promise<void>;
47
+ absorb(fields: Fr[]): Promise<void>;
48
+ squeeze(): Promise<Fr>;
49
+ }
50
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3BvbmdlX2Jsb2IuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9zcG9uZ2VfYmxvYi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEVBQUUsS0FBSyxRQUFRLEVBQWEsTUFBTSw4QkFBOEIsQ0FBQztBQUV4RSxPQUFPLEVBQUUsRUFBRSxFQUFFLE1BQU0scUNBQXFDLENBQUM7QUFDekQsT0FBTyx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,EAAE,MAAM,GAAG,YAAY,GAAG,eAAe,CAQhE;IAED,QAAQ,4BAEP;IAED,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,eAAe,CAAC,0DAEjD;IAED,QAAQ,IAAI,EAAE,EAAE,CAEf;IAED,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,EAAE,GAAG,WAAW,GAAG,eAAe,CAQ7D;IAED,MAAM,CAAC,KAAK,IAAI,eAAe,CAO9B;IAED,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,GAAG,eAAe,CAInC;IAKK,aAAa,kBASlB;IAEK,MAAM,CAAC,MAAM,EAAE,EAAE,EAAE,iBAaxB;IAEK,OAAO,IAAI,OAAO,CAAC,EAAE,CAAC,CAO3B;CACF"}
@@ -0,0 +1,144 @@
1
+ import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB, TWO_POW_64 } from '@aztec-labs/constants';
2
+ import { makeTuple } from '@aztec-labs/foundation/array';
3
+ import { poseidon2Permutation } from '@aztec-labs/foundation/crypto/poseidon';
4
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
5
+ import { BufferReader, FieldReader, serializeToBuffer, serializeToFields } from '@aztec-labs/foundation/serialize';
6
+ /**
7
+ * A Poseidon2 sponge used to accumulate data that will be added to blobs.
8
+ * See noir-projects/fnd/noir-protocol-circuits/crates/types/src/blob_data/sponge_blob.nr.
9
+ */ export class SpongeBlob {
10
+ sponge;
11
+ numAbsorbedFields;
12
+ static MAX_FIELDS = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB;
13
+ constructor(/** Sponge with absorbed fields that will go into one or more blobs. */ sponge, /** Number of effects absorbed so far. */ numAbsorbedFields){
14
+ this.sponge = sponge;
15
+ this.numAbsorbedFields = numAbsorbedFields;
16
+ }
17
+ /**
18
+ * Initialize the sponge blob to absorb data for a checkpoint.
19
+ */ static init() {
20
+ // This must match the implementation in noir-projects/fnd/noir-protocol-circuits/crates/types/src/blob_data/sponge_blob.nr
21
+ const iv = new Fr(BigInt(SpongeBlob.MAX_FIELDS) * TWO_POW_64);
22
+ const sponge = Poseidon2Sponge.init(iv);
23
+ return new SpongeBlob(sponge, 0);
24
+ }
25
+ static fromBuffer(buffer) {
26
+ const reader = BufferReader.asReader(buffer);
27
+ return new SpongeBlob(reader.readObject(Poseidon2Sponge), reader.readNumber());
28
+ }
29
+ toBuffer() {
30
+ return serializeToBuffer(...SpongeBlob.getFields(this));
31
+ }
32
+ static getFields(fields) {
33
+ return [
34
+ fields.sponge,
35
+ fields.numAbsorbedFields
36
+ ];
37
+ }
38
+ toFields() {
39
+ return serializeToFields(...SpongeBlob.getFields(this));
40
+ }
41
+ static fromFields(fields) {
42
+ const reader = FieldReader.asReader(fields);
43
+ return new SpongeBlob(reader.readObject(Poseidon2Sponge), reader.readField().toNumber());
44
+ }
45
+ clone() {
46
+ return SpongeBlob.fromBuffer(this.toBuffer());
47
+ }
48
+ async absorb(fields) {
49
+ if (this.numAbsorbedFields + fields.length > SpongeBlob.MAX_FIELDS) {
50
+ throw new Error(`Attempted to fill spongeBlob with ${this.numAbsorbedFields + fields.length}, but it has a max of ${SpongeBlob.MAX_FIELDS}`);
51
+ }
52
+ await this.sponge.absorb(fields);
53
+ this.numAbsorbedFields += fields.length;
54
+ }
55
+ async squeeze() {
56
+ return await this.sponge.squeeze();
57
+ }
58
+ static empty() {
59
+ return new SpongeBlob(Poseidon2Sponge.empty(), 0);
60
+ }
61
+ }
62
+ // This is just noir's stdlib version of the poseidon2 sponge. We use it for a blob-specific implmentation of the hasher.
63
+ export class Poseidon2Sponge {
64
+ cache;
65
+ state;
66
+ cacheSize;
67
+ squeezeMode;
68
+ constructor(cache, state, cacheSize, squeezeMode){
69
+ this.cache = cache;
70
+ this.state = state;
71
+ this.cacheSize = cacheSize;
72
+ this.squeezeMode = squeezeMode;
73
+ }
74
+ static fromBuffer(buffer) {
75
+ const reader = BufferReader.asReader(buffer);
76
+ return new Poseidon2Sponge(reader.readArray(3, Fr), reader.readArray(4, Fr), reader.readNumber(), reader.readBoolean());
77
+ }
78
+ toBuffer() {
79
+ return serializeToBuffer(this.cache, this.state, this.cacheSize, this.squeezeMode);
80
+ }
81
+ static getFields(fields) {
82
+ return [
83
+ fields.cache,
84
+ fields.state,
85
+ fields.cacheSize,
86
+ fields.squeezeMode
87
+ ];
88
+ }
89
+ toFields() {
90
+ return serializeToFields(...Poseidon2Sponge.getFields(this));
91
+ }
92
+ static fromFields(fields) {
93
+ const reader = FieldReader.asReader(fields);
94
+ return new Poseidon2Sponge(reader.readFieldArray(3), reader.readFieldArray(4), reader.readField().toNumber(), reader.readBoolean());
95
+ }
96
+ static empty() {
97
+ return new Poseidon2Sponge(makeTuple(3, ()=>Fr.ZERO), makeTuple(4, ()=>Fr.ZERO), 0, false);
98
+ }
99
+ static init(iv) {
100
+ const sponge = Poseidon2Sponge.empty();
101
+ sponge.state[3] = iv;
102
+ return sponge;
103
+ }
104
+ // Note: there isn't currently an impl in ts that allows for a custom aborption via an
105
+ // existing sponge.
106
+ // A custom blob-based impl of noir/noir-repo/noir_stdlib/src/hash/poseidon2.nr
107
+ async performDuplex() {
108
+ for(let i = 0; i < this.cache.length; i++){
109
+ if (i < this.cacheSize) {
110
+ this.state[i] = this.state[i].add(this.cache[i]);
111
+ }
112
+ }
113
+ const perm = await poseidon2Permutation(this.state);
114
+ // ts doesn't understand that the above always gives 4
115
+ this.state = [
116
+ perm[0],
117
+ perm[1],
118
+ perm[2],
119
+ perm[3]
120
+ ];
121
+ }
122
+ async absorb(fields) {
123
+ if (this.squeezeMode) {
124
+ throw new Error(`Poseidon sponge is not able to absorb more inputs.`);
125
+ }
126
+ for (const field of fields){
127
+ if (this.cacheSize == this.cache.length) {
128
+ await this.performDuplex();
129
+ this.cache[0] = field;
130
+ this.cacheSize = 1;
131
+ } else {
132
+ this.cache[this.cacheSize++] = field;
133
+ }
134
+ }
135
+ }
136
+ async squeeze() {
137
+ if (this.squeezeMode) {
138
+ throw new Error(`Poseidon sponge has already been squeezed.`);
139
+ }
140
+ await this.performDuplex();
141
+ this.squeezeMode = true;
142
+ return this.state[0];
143
+ }
144
+ }