@aztec/simulator 0.87.4 → 0.87.6

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 (122) hide show
  1. package/dest/client.d.ts +5 -5
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +4 -4
  4. package/dest/private/acvm/acvm.d.ts +1 -2
  5. package/dest/private/acvm/acvm.d.ts.map +1 -1
  6. package/dest/private/acvm/index.d.ts +0 -1
  7. package/dest/private/acvm/index.d.ts.map +1 -1
  8. package/dest/private/acvm/index.js +0 -1
  9. package/dest/private/{providers/acvm_native.d.ts → acvm_native.d.ts} +4 -4
  10. package/dest/private/acvm_native.d.ts.map +1 -0
  11. package/dest/private/{providers/acvm_wasm.d.ts → acvm_wasm.d.ts} +4 -4
  12. package/dest/private/acvm_wasm.d.ts.map +1 -0
  13. package/dest/private/{providers/acvm_wasm.js → acvm_wasm.js} +2 -2
  14. package/dest/private/{providers/acvm_wasm_with_blobs.d.ts → acvm_wasm_with_blobs.d.ts} +5 -5
  15. package/dest/private/acvm_wasm_with_blobs.d.ts.map +1 -0
  16. package/dest/private/{providers/acvm_wasm_with_blobs.js → acvm_wasm_with_blobs.js} +2 -2
  17. package/dest/private/{providers/circuit_recording → circuit_recording}/circuit_recorder.d.ts +2 -2
  18. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -0
  19. package/dest/private/{providers/circuit_recording → circuit_recording}/circuit_recorder.js +2 -3
  20. package/dest/private/{providers/circuit_recording → circuit_recording}/file_circuit_recorder.d.ts +1 -1
  21. package/dest/private/circuit_recording/file_circuit_recorder.d.ts.map +1 -0
  22. package/dest/private/circuit_recording/memory_circuit_recorder.d.ts.map +1 -0
  23. package/dest/private/{providers/circuit_recording/simulation_provider_recorder_wrapper.d.ts → circuit_recording/simulator_recorder_wrapper.d.ts} +7 -7
  24. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts.map +1 -0
  25. package/dest/private/{providers/circuit_recording/simulation_provider_recorder_wrapper.js → circuit_recording/simulator_recorder_wrapper.js} +2 -2
  26. package/dest/private/{providers/simulation_provider.d.ts → circuit_simulator.d.ts} +4 -4
  27. package/dest/private/circuit_simulator.d.ts.map +1 -0
  28. package/dest/private/{providers/simulation_provider.js → circuit_simulator.js} +1 -1
  29. package/dest/private/factory.d.ts +12 -0
  30. package/dest/private/factory.d.ts.map +1 -0
  31. package/dest/private/{providers/factory.js → factory.js} +2 -2
  32. package/dest/server.d.ts +6 -5
  33. package/dest/server.d.ts.map +1 -1
  34. package/dest/server.js +5 -4
  35. package/dest/testing.d.ts +1 -1
  36. package/dest/testing.d.ts.map +1 -1
  37. package/dest/testing.js +1 -1
  38. package/package.json +15 -15
  39. package/src/client.ts +5 -5
  40. package/src/private/acvm/acvm.ts +2 -3
  41. package/src/private/acvm/index.ts +0 -1
  42. package/src/private/{providers/acvm_native.ts → acvm_native.ts} +4 -4
  43. package/src/private/{providers/acvm_wasm.ts → acvm_wasm.ts} +4 -4
  44. package/src/private/{providers/acvm_wasm_with_blobs.ts → acvm_wasm_with_blobs.ts} +5 -5
  45. package/src/private/{providers/circuit_recording → circuit_recording}/circuit_recorder.ts +4 -5
  46. package/src/private/{providers/circuit_recording → circuit_recording}/file_circuit_recorder.ts +1 -1
  47. package/src/private/{providers/circuit_recording/simulation_provider_recorder_wrapper.ts → circuit_recording/simulator_recorder_wrapper.ts} +6 -6
  48. package/src/private/{providers/simulation_provider.ts → circuit_simulator.ts} +3 -3
  49. package/src/private/{providers/factory.ts → factory.ts} +6 -6
  50. package/src/server.ts +6 -5
  51. package/src/testing.ts +1 -1
  52. package/dest/private/acvm/oracle/index.d.ts +0 -14
  53. package/dest/private/acvm/oracle/index.d.ts.map +0 -1
  54. package/dest/private/acvm/oracle/index.js +0 -2
  55. package/dest/private/acvm/oracle/oracle.d.ts +0 -52
  56. package/dest/private/acvm/oracle/oracle.d.ts.map +0 -1
  57. package/dest/private/acvm/oracle/oracle.js +0 -312
  58. package/dest/private/acvm/oracle/typed_oracle.d.ts +0 -83
  59. package/dest/private/acvm/oracle/typed_oracle.d.ts.map +0 -1
  60. package/dest/private/acvm/oracle/typed_oracle.js +0 -138
  61. package/dest/private/execution_data_provider.d.ts +0 -301
  62. package/dest/private/execution_data_provider.d.ts.map +0 -1
  63. package/dest/private/execution_data_provider.js +0 -14
  64. package/dest/private/execution_note_cache.d.ts +0 -93
  65. package/dest/private/execution_note_cache.d.ts.map +0 -1
  66. package/dest/private/execution_note_cache.js +0 -180
  67. package/dest/private/hashed_values_cache.d.ts +0 -28
  68. package/dest/private/hashed_values_cache.d.ts.map +0 -1
  69. package/dest/private/hashed_values_cache.js +0 -36
  70. package/dest/private/index.d.ts +0 -16
  71. package/dest/private/index.d.ts.map +0 -1
  72. package/dest/private/index.js +0 -15
  73. package/dest/private/message_load_oracle_inputs.d.ts +0 -19
  74. package/dest/private/message_load_oracle_inputs.d.ts.map +0 -1
  75. package/dest/private/message_load_oracle_inputs.js +0 -24
  76. package/dest/private/pick_notes.d.ts +0 -85
  77. package/dest/private/pick_notes.d.ts.map +0 -1
  78. package/dest/private/pick_notes.js +0 -51
  79. package/dest/private/private_execution.d.ts +0 -25
  80. package/dest/private/private_execution.d.ts.map +0 -1
  81. package/dest/private/private_execution.js +0 -96
  82. package/dest/private/private_execution_oracle.d.ts +0 -187
  83. package/dest/private/private_execution_oracle.d.ts.map +0 -1
  84. package/dest/private/private_execution_oracle.js +0 -318
  85. package/dest/private/providers/acvm_native.d.ts.map +0 -1
  86. package/dest/private/providers/acvm_wasm.d.ts.map +0 -1
  87. package/dest/private/providers/acvm_wasm_with_blobs.d.ts.map +0 -1
  88. package/dest/private/providers/circuit_recording/circuit_recorder.d.ts.map +0 -1
  89. package/dest/private/providers/circuit_recording/file_circuit_recorder.d.ts.map +0 -1
  90. package/dest/private/providers/circuit_recording/memory_circuit_recorder.d.ts.map +0 -1
  91. package/dest/private/providers/circuit_recording/simulation_provider_recorder_wrapper.d.ts.map +0 -1
  92. package/dest/private/providers/factory.d.ts +0 -12
  93. package/dest/private/providers/factory.d.ts.map +0 -1
  94. package/dest/private/providers/simulation_provider.d.ts.map +0 -1
  95. package/dest/private/simulator.d.ts +0 -36
  96. package/dest/private/simulator.d.ts.map +0 -1
  97. package/dest/private/simulator.js +0 -104
  98. package/dest/private/utility_execution_oracle.d.ts +0 -163
  99. package/dest/private/utility_execution_oracle.d.ts.map +0 -1
  100. package/dest/private/utility_execution_oracle.js +0 -257
  101. package/dest/test/utils.d.ts +0 -13
  102. package/dest/test/utils.d.ts.map +0 -1
  103. package/dest/test/utils.js +0 -22
  104. package/src/private/acvm/oracle/index.ts +0 -16
  105. package/src/private/acvm/oracle/oracle.ts +0 -523
  106. package/src/private/acvm/oracle/typed_oracle.ts +0 -273
  107. package/src/private/execution_data_provider.ts +0 -388
  108. package/src/private/execution_note_cache.ts +0 -217
  109. package/src/private/hashed_values_cache.ts +0 -47
  110. package/src/private/index.ts +0 -19
  111. package/src/private/message_load_oracle_inputs.ts +0 -23
  112. package/src/private/pick_notes.ts +0 -141
  113. package/src/private/private_execution.ts +0 -160
  114. package/src/private/private_execution_oracle.ts +0 -508
  115. package/src/private/simulator.ts +0 -170
  116. package/src/private/utility_execution_oracle.ts +0 -384
  117. package/src/test/utils.ts +0 -36
  118. /package/dest/private/{providers/acvm_native.js → acvm_native.js} +0 -0
  119. /package/dest/private/{providers/circuit_recording → circuit_recording}/file_circuit_recorder.js +0 -0
  120. /package/dest/private/{providers/circuit_recording → circuit_recording}/memory_circuit_recorder.d.ts +0 -0
  121. /package/dest/private/{providers/circuit_recording → circuit_recording}/memory_circuit_recorder.js +0 -0
  122. /package/src/private/{providers/circuit_recording → circuit_recording}/memory_circuit_recorder.ts +0 -0
@@ -1,217 +0,0 @@
1
- import { Fr } from '@aztec/foundation/fields';
2
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
3
- import { computeNoteHashNonce, computeUniqueNoteHash, siloNoteHash, siloNullifier } from '@aztec/stdlib/hash';
4
-
5
- import type { NoteData } from './acvm/index.js';
6
-
7
- interface PendingNote {
8
- note: NoteData;
9
- counter: number;
10
- noteHashForConsumption: Fr;
11
- }
12
-
13
- /**
14
- * Data that's accessible by all the function calls in an execution.
15
- */
16
- export class ExecutionNoteCache {
17
- /**
18
- * New notes created in this transaction.
19
- * They are pushed to this array in the same order as they are emitted.
20
- */
21
- private notes: PendingNote[] = [];
22
- /**
23
- * This mapping maps from a contract address to the notes in the contract.
24
- */
25
- private noteMap: Map<bigint, PendingNote[]> = new Map();
26
-
27
- /**
28
- * This maps from a contract address to the nullifiers emitted from the contract.
29
- * The note which is nullified might be new or not (i.e., was generated in a previous transaction).
30
- * Note that their value (bigint representation) is used because Frs cannot be looked up in Sets.
31
- */
32
- private nullifierMap: Map<bigint, Set<bigint>> = new Map();
33
-
34
- /**
35
- * All nullifiers emitted in this transaction.
36
- */
37
- private allNullifiers: Set<bigint> = new Set();
38
-
39
- private minRevertibleSideEffectCounter = 0;
40
-
41
- private inRevertiblePhase = false;
42
-
43
- /**
44
- * We don't need to use the tx request hash for nonces if another non revertible nullifier is emitted.
45
- * In that case we disable injecting the tx request hash as a nullifier.
46
- */
47
- private usedTxRequestHashForNonces = true;
48
-
49
- constructor(private readonly txRequestHash: Fr) {}
50
-
51
- /**
52
- * Enters the revertible phase of the transaction.
53
- * @param minRevertibleSideEffectCounter - The counter at which the transaction enters the revertible phase.
54
- */
55
- public async setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter: number) {
56
- if (this.inRevertiblePhase) {
57
- throw new Error(
58
- `Cannot enter the revertible phase twice. Current counter: ${minRevertibleSideEffectCounter}. Previous enter counter: ${this.minRevertibleSideEffectCounter}`,
59
- );
60
- }
61
- this.inRevertiblePhase = true;
62
- this.minRevertibleSideEffectCounter = minRevertibleSideEffectCounter;
63
-
64
- let nonceGenerator = this.txRequestHash;
65
- const nullifiers = this.getAllNullifiers();
66
- if (nullifiers.length > 0) {
67
- nonceGenerator = new Fr(nullifiers[0]);
68
- this.usedTxRequestHashForNonces = false;
69
- }
70
-
71
- // The existing pending notes are all non-revertible.
72
- // They cannot be squashed by nullifiers emitted after minRevertibleSideEffectCounter is set.
73
- // Their indexes in the tx are known at this point and won't change. So we can assign a nonce to each one of them.
74
- // The nonces will be used to create the "complete" nullifier.
75
- const updatedNotes = await Promise.all(
76
- this.notes.map(async ({ note, counter }, i) => {
77
- const nonce = await computeNoteHashNonce(nonceGenerator, i);
78
- const uniqueNoteHash = await computeUniqueNoteHash(
79
- nonce,
80
- await siloNoteHash(note.contractAddress, note.noteHash),
81
- );
82
- return {
83
- counter,
84
- note: { ...note, nonce },
85
- noteHashForConsumption: uniqueNoteHash,
86
- };
87
- }),
88
- );
89
- // Rebuild the data.
90
- this.notes = [];
91
- this.noteMap = new Map();
92
- updatedNotes.forEach(n => this.#addNote(n));
93
- }
94
-
95
- public finish() {
96
- // If we never entered the revertible phase, we need to use the tx request hash as a nonce for the notes if no nullifiers have been emitted.
97
- if (!this.inRevertiblePhase) {
98
- this.usedTxRequestHashForNonces = this.getAllNullifiers().length === 0;
99
- }
100
- // If we entered the revertible phase, the nonce generator was decided based on wether or not a nullifier was emitted before entering.
101
- return {
102
- usedTxRequestHashForNonces: this.usedTxRequestHashForNonces,
103
- };
104
- }
105
-
106
- /**
107
- * Add a new note to cache.
108
- * @param note - New note created during execution.
109
- */
110
- public addNewNote(note: NoteData, counter: number) {
111
- const previousNote = this.notes[this.notes.length - 1];
112
- if (previousNote && previousNote.counter >= counter) {
113
- throw new Error(
114
- `Note hash counters must be strictly increasing. Current counter: ${counter}. Previous counter: ${previousNote.counter}.`,
115
- );
116
- }
117
-
118
- this.#addNote({ note, counter, noteHashForConsumption: note.noteHash });
119
- }
120
-
121
- /**
122
- * Add a nullifier to cache. It could be for a db note or a new note created during execution.
123
- * @param contractAddress - Contract address of the note.
124
- * @param innerNullifier - Inner nullifier of the note.
125
- * @param noteHash - A hash of the note. If this value equals 0, it means the note being nullified is from a previous
126
- * transaction (and thus not a new note).
127
- */
128
- public async nullifyNote(contractAddress: AztecAddress, innerNullifier: Fr, noteHash: Fr) {
129
- const siloedNullifier = await siloNullifier(contractAddress, innerNullifier);
130
- let nullifiedNoteHashCounter: number | undefined = undefined;
131
- // Find and remove the matching new note and log(s) if the emitted noteHash is not empty.
132
- if (!noteHash.isEmpty()) {
133
- const notesInContract = this.noteMap.get(contractAddress.toBigInt()) ?? [];
134
- const noteIndexToRemove = notesInContract.findIndex(n => n.noteHashForConsumption.equals(noteHash));
135
- if (noteIndexToRemove === -1) {
136
- throw new Error('Attempt to remove a pending note that does not exist.');
137
- }
138
-
139
- const note = notesInContract.splice(noteIndexToRemove, 1)[0];
140
- nullifiedNoteHashCounter = note.counter;
141
- this.noteMap.set(contractAddress.toBigInt(), notesInContract);
142
- this.notes = this.notes.filter(n => n.counter !== note.counter);
143
-
144
- // If the note is non revertible and the nullifier was emitted in the revertible phase, both the note hash and the nullifier will be emitted
145
- if (this.inRevertiblePhase && note.counter < this.minRevertibleSideEffectCounter) {
146
- this.recordNullifier(contractAddress, siloedNullifier);
147
- }
148
- } else {
149
- // If the note being nullified comes from a previous tx the nullifier will be emitted.
150
- this.recordNullifier(contractAddress, siloedNullifier);
151
- }
152
- return nullifiedNoteHashCounter;
153
- }
154
-
155
- /**
156
- * Adds a nullifier to the cache. Note cache needs to track all nullifiers to decide which nullifier to use for note siloing.
157
- * @param contractAddress - Contract address that emitted the nullifier.
158
- * @param innerNullifier
159
- */
160
- public async nullifierCreated(contractAddress: AztecAddress, innerNullifier: Fr) {
161
- const siloedNullifier = await siloNullifier(contractAddress, innerNullifier);
162
- this.recordNullifier(contractAddress, siloedNullifier);
163
- }
164
-
165
- /**
166
- * Return notes created up to current point in execution.
167
- * If a nullifier for a note in this list is emitted, the note will be deleted.
168
- * @param contractAddress - Contract address of the notes.
169
- * @param storageSlot - Storage slot of the notes.
170
- **/
171
- public getNotes(contractAddress: AztecAddress, storageSlot: Fr) {
172
- const notes = this.noteMap.get(contractAddress.toBigInt()) ?? [];
173
- return notes.filter(n => n.note.storageSlot.equals(storageSlot)).map(n => n.note);
174
- }
175
-
176
- /**
177
- * Check if a note exists in the newNotes array.
178
- * @param contractAddress - Contract address of the note.
179
- * @param storageSlot - Storage slot of the note.
180
- * @param noteHash - A hash of the note.
181
- **/
182
- public checkNoteExists(contractAddress: AztecAddress, noteHash: Fr) {
183
- const notes = this.noteMap.get(contractAddress.toBigInt()) ?? [];
184
- return notes.some(n => n.note.noteHash.equals(noteHash));
185
- }
186
-
187
- /**
188
- * Return all nullifiers emitted from a contract.
189
- * @param contractAddress - Address of the contract.
190
- */
191
- public getNullifiers(contractAddress: AztecAddress): Set<bigint> {
192
- return this.nullifierMap.get(contractAddress.toBigInt()) ?? new Set();
193
- }
194
-
195
- #addNote(note: PendingNote) {
196
- this.notes.push(note);
197
-
198
- const notes = this.noteMap.get(note.note.contractAddress.toBigInt()) ?? [];
199
- notes.push(note);
200
- this.noteMap.set(note.note.contractAddress.toBigInt(), notes);
201
- }
202
-
203
- getAllNotes(): PendingNote[] {
204
- return this.notes;
205
- }
206
-
207
- getAllNullifiers(): Fr[] {
208
- return [...this.allNullifiers].map(n => new Fr(n));
209
- }
210
-
211
- recordNullifier(contractAddress: AztecAddress, siloedNullifier: Fr) {
212
- const nullifiers = this.getNullifiers(contractAddress);
213
- nullifiers.add(siloedNullifier.toBigInt());
214
- this.nullifierMap.set(contractAddress.toBigInt(), nullifiers);
215
- this.allNullifiers.add(siloedNullifier.toBigInt());
216
- }
217
- }
@@ -1,47 +0,0 @@
1
- import { Fr } from '@aztec/foundation/fields';
2
- import { HashedValues } from '@aztec/stdlib/tx';
3
-
4
- /**
5
- * A cache for hashed values (arguments, returns) during transaction execution.
6
- */
7
- export class HashedValuesCache {
8
- private cache: Map<bigint, Fr[]>;
9
-
10
- constructor(initialArguments: HashedValues[] = []) {
11
- this.cache = new Map();
12
- for (const initialArg of initialArguments) {
13
- this.cache.set(initialArg.hash.toBigInt(), initialArg.values);
14
- }
15
- }
16
-
17
- /**
18
- * Creates a new hashed values cache.
19
- * @param initialArguments - The initial arguments to add to the cache.
20
- * @returns The new hashed values cache.
21
- */
22
- public static create(initialArguments: HashedValues[] = []) {
23
- return new HashedValuesCache(initialArguments);
24
- }
25
-
26
- /**
27
- * Gets preimage of a hash.
28
- * @param hash - The hash to get the preimage of.
29
- * @returns The preimage.
30
- */
31
- public getPreimage(hash: Fr): Fr[] | undefined {
32
- if (hash.isEmpty()) {
33
- return [];
34
- } else {
35
- return this.cache.get(hash.toBigInt());
36
- }
37
- }
38
-
39
- /**
40
- * Stores values in cache and returns its hash.
41
- * @param values - The values to store.
42
- * @returns The hash of the values.
43
- */
44
- public store(values: Fr[], hash: Fr) {
45
- this.cache.set(hash.toBigInt(), values);
46
- }
47
- }
@@ -1,19 +0,0 @@
1
- export { AcirSimulator } from './simulator.js';
2
- export {
3
- type ExecutionDataProvider,
4
- ContractClassNotFoundError,
5
- ContractNotFoundError,
6
- } from './execution_data_provider.js';
7
- export * from './pick_notes.js';
8
- export { ExecutionNoteCache } from './execution_note_cache.js';
9
- export { extractPrivateCircuitPublicInputs, readCurrentClassId } from './private_execution.js';
10
- export { witnessMapToFields } from './acvm/deserialize.js';
11
- export { toACVMWitness } from './acvm/serialize.js';
12
- export { executePrivateFunction } from './private_execution.js';
13
- export { PrivateExecutionOracle } from './private_execution_oracle.js';
14
- export { UtilityExecutionOracle } from './utility_execution_oracle.js';
15
- export { extractCallStack } from './acvm/acvm.js';
16
- export { type NoteData, TypedOracle } from './acvm/oracle/typed_oracle.js';
17
- export { Oracle } from './acvm/oracle/oracle.js';
18
- export { HashedValuesCache } from './hashed_values_cache.js';
19
- export { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
@@ -1,23 +0,0 @@
1
- import { Fr } from '@aztec/foundation/fields';
2
- import type { SiblingPath } from '@aztec/foundation/trees';
3
-
4
- export class MessageLoadOracleInputs<N extends number> {
5
- constructor(
6
- /** The index of the message commitment in the merkle tree. */
7
- public index: bigint,
8
- /** The path in the merkle tree to the message. */
9
- public siblingPath: SiblingPath<N>,
10
- ) {}
11
-
12
- toFields(): Fr[] {
13
- return [new Fr(this.index), ...this.siblingPath.toFields()];
14
- }
15
-
16
- /**
17
- * Returns a representation of the public data witness as expected by intrinsic Noir deserialization.
18
- */
19
- public toNoirRepresentation(): (string | string[])[] {
20
- // TODO(#12874): remove the stupid as string conversion by modifying ForeignCallOutput type in acvm.js
21
- return [new Fr(this.index).toString() as string, this.siblingPath.toFields().map(fr => fr.toString()) as string[]];
22
- }
23
- }
@@ -1,141 +0,0 @@
1
- import { Fr } from '@aztec/foundation/fields';
2
- import { Comparator, type Note } from '@aztec/stdlib/note';
3
-
4
- export interface PropertySelector {
5
- index: number;
6
- offset: number;
7
- length: number;
8
- }
9
-
10
- /**
11
- * Configuration for selecting values.
12
- */
13
- export interface Select {
14
- /**
15
- * Selector of the field to select and match.
16
- */
17
- selector: PropertySelector;
18
- /**
19
- * Required value of the field.
20
- */
21
- value: Fr;
22
- /**
23
- * The comparator to use
24
- */
25
- comparator: Comparator;
26
- }
27
-
28
- /**
29
- * The order to sort an array.
30
- */
31
- export enum SortOrder {
32
- NADA = 0,
33
- DESC = 1,
34
- ASC = 2,
35
- }
36
-
37
- /**
38
- * Configuration for sorting values.
39
- */
40
- export interface Sort {
41
- /**
42
- * Selector of the field to sort.
43
- */
44
- selector: PropertySelector;
45
- /**
46
- * Order to sort the field.
47
- */
48
- order: SortOrder;
49
- }
50
-
51
- /**
52
- * Options for picking items from an array of BasicNoteData.
53
- */
54
- interface GetOptions {
55
- /**
56
- * Configurations for selecting items.
57
- * Default: empty array.
58
- */
59
- selects?: Select[];
60
- /**
61
- * Configurations for sorting items.
62
- * Default: empty array.
63
- */
64
- sorts?: Sort[];
65
- /**
66
- * The number of items to retrieve per query.
67
- * Default: 0. No limit.
68
- */
69
- limit?: number;
70
- /**
71
- * The starting index for pagination.
72
- * Default: 0.
73
- */
74
- offset?: number;
75
- }
76
-
77
- /**
78
- * Data needed from to perform sort.
79
- */
80
- interface ContainsNote {
81
- /**
82
- * The note.
83
- */
84
- note: Note;
85
- }
86
-
87
- const selectPropertyFromPackedNoteContent = (noteData: Fr[], selector: PropertySelector): Fr => {
88
- const noteValueBuffer = noteData[selector.index].toBuffer();
89
- const noteValue = noteValueBuffer.subarray(selector.offset, selector.offset + selector.length);
90
- return Fr.fromBuffer(noteValue);
91
- };
92
-
93
- const selectNotes = <T extends ContainsNote>(noteDatas: T[], selects: Select[]): T[] =>
94
- noteDatas.filter(noteData =>
95
- selects.every(({ selector, value, comparator }) => {
96
- const noteValueFr = selectPropertyFromPackedNoteContent(noteData.note.items, selector);
97
- const comparatorSelector = {
98
- [Comparator.EQ]: () => noteValueFr.equals(value),
99
- [Comparator.NEQ]: () => !noteValueFr.equals(value),
100
- [Comparator.LT]: () => noteValueFr.lt(value),
101
- [Comparator.LTE]: () => noteValueFr.lt(value) || noteValueFr.equals(value),
102
- [Comparator.GT]: () => !noteValueFr.lt(value) && !noteValueFr.equals(value),
103
- [Comparator.GTE]: () => !noteValueFr.lt(value),
104
- };
105
-
106
- return comparatorSelector[comparator]();
107
- }),
108
- );
109
-
110
- const sortNotes = (a: Fr[], b: Fr[], sorts: Sort[], level = 0): number => {
111
- if (sorts[level] === undefined) {
112
- return 0;
113
- }
114
-
115
- const { selector, order } = sorts[level];
116
- if (order === (0 as SortOrder)) {
117
- return 0;
118
- }
119
-
120
- const aValue = selectPropertyFromPackedNoteContent(a, selector);
121
- const bValue = selectPropertyFromPackedNoteContent(b, selector);
122
-
123
- const dir = order === (1 as SortOrder) ? [-1, 1] : [1, -1];
124
- return aValue.toBigInt() === bValue.toBigInt()
125
- ? sortNotes(a, b, sorts, level + 1)
126
- : aValue.toBigInt() > bValue.toBigInt()
127
- ? dir[0]
128
- : dir[1];
129
- };
130
-
131
- /**
132
- * Pick from a note array a number of notes that meet the criteria.
133
- */
134
- export function pickNotes<T extends ContainsNote>(
135
- noteDatas: T[],
136
- { selects = [], sorts = [], limit = 0, offset = 0 }: GetOptions,
137
- ): T[] {
138
- return selectNotes(noteDatas, selects)
139
- .sort((a, b) => sortNotes(a.note.items, b.note.items, sorts))
140
- .slice(offset, limit ? offset + limit : undefined);
141
- }
@@ -1,160 +0,0 @@
1
- import { PRIVATE_CIRCUIT_PUBLIC_INPUTS_LENGTH, PRIVATE_CONTEXT_INPUTS_LENGTH } from '@aztec/constants';
2
- import { Fr } from '@aztec/foundation/fields';
3
- import { createLogger } from '@aztec/foundation/log';
4
- import { Timer } from '@aztec/foundation/timer';
5
- import { ProtocolContractAddress } from '@aztec/protocol-contracts';
6
- import {
7
- type FunctionArtifact,
8
- type FunctionArtifactWithContractName,
9
- type FunctionSelector,
10
- countArgumentsSize,
11
- } from '@aztec/stdlib/abi';
12
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
13
- import type { ContractInstance } from '@aztec/stdlib/contract';
14
- import type { AztecNode } from '@aztec/stdlib/interfaces/client';
15
- import { PrivateCircuitPublicInputs } from '@aztec/stdlib/kernel';
16
- import { SharedMutableValues, SharedMutableValuesWithHash } from '@aztec/stdlib/shared-mutable';
17
- import type { CircuitWitnessGenerationStats } from '@aztec/stdlib/stats';
18
- import { PrivateCallExecutionResult } from '@aztec/stdlib/tx';
19
-
20
- import { ExecutionError, resolveAssertionMessageFromError } from '../common/errors.js';
21
- import { witnessMapToFields } from './acvm/deserialize.js';
22
- import { type ACVMWitness, Oracle, extractCallStack } from './acvm/index.js';
23
- import type { ExecutionDataProvider } from './execution_data_provider.js';
24
- import type { PrivateExecutionOracle } from './private_execution_oracle.js';
25
- import type { SimulationProvider } from './providers/simulation_provider.js';
26
-
27
- /**
28
- * Execute a private function and return the execution result.
29
- */
30
- export async function executePrivateFunction(
31
- simulator: SimulationProvider,
32
- privateExecutionOracle: PrivateExecutionOracle,
33
- artifact: FunctionArtifactWithContractName,
34
- contractAddress: AztecAddress,
35
- functionSelector: FunctionSelector,
36
- log = createLogger('simulator:private_execution'),
37
- ): Promise<PrivateCallExecutionResult> {
38
- const functionName = await privateExecutionOracle.getDebugFunctionName();
39
- log.verbose(`Executing private function ${functionName}`, { contract: contractAddress });
40
- const initialWitness = privateExecutionOracle.getInitialWitness(artifact);
41
- const acvmCallback = new Oracle(privateExecutionOracle);
42
- const timer = new Timer();
43
- const acirExecutionResult = await simulator
44
- .executeUserCircuit(initialWitness, artifact, acvmCallback)
45
- .catch((err: Error) => {
46
- err.message = resolveAssertionMessageFromError(err, artifact);
47
- throw new ExecutionError(
48
- err.message,
49
- {
50
- contractAddress,
51
- functionSelector,
52
- },
53
- extractCallStack(err, artifact.debug),
54
- { cause: err },
55
- );
56
- });
57
- const duration = timer.ms();
58
- const partialWitness = acirExecutionResult.partialWitness;
59
- const publicInputs = extractPrivateCircuitPublicInputs(artifact, partialWitness);
60
-
61
- // TODO (alexg) estimate this size
62
- const initialWitnessSize = witnessMapToFields(initialWitness).length * Fr.SIZE_IN_BYTES;
63
- log.debug(`Ran external function ${contractAddress.toString()}:${functionSelector}`, {
64
- circuitName: 'app-circuit',
65
- duration,
66
- eventName: 'circuit-witness-generation',
67
- inputSize: initialWitnessSize,
68
- outputSize: publicInputs.toBuffer().length,
69
- appCircuitName: functionName,
70
- } satisfies CircuitWitnessGenerationStats);
71
-
72
- const contractClassLogs = privateExecutionOracle.getContractClassLogs();
73
-
74
- const rawReturnValues = await privateExecutionOracle.loadFromExecutionCache(publicInputs.returnsHash);
75
-
76
- const noteHashLeafIndexMap = privateExecutionOracle.getNoteHashLeafIndexMap();
77
- const newNotes = privateExecutionOracle.getNewNotes();
78
- const noteHashNullifierCounterMap = privateExecutionOracle.getNoteHashNullifierCounterMap();
79
- const nestedExecutions = privateExecutionOracle.getNestedExecutions();
80
-
81
- log.debug(`Returning from call to ${contractAddress.toString()}:${functionSelector}`);
82
-
83
- return new PrivateCallExecutionResult(
84
- artifact.bytecode,
85
- Buffer.from(artifact.verificationKey!, 'base64'),
86
- partialWitness,
87
- publicInputs,
88
- noteHashLeafIndexMap,
89
- newNotes,
90
- noteHashNullifierCounterMap,
91
- rawReturnValues,
92
- nestedExecutions,
93
- contractClassLogs,
94
- {
95
- timings: {
96
- witgen:
97
- // Due to the recursive nature of execution, we have to subtract the time taken by the first level of
98
- // child executions
99
- duration - nestedExecutions.reduce((acc, nested) => acc + (nested.profileResult?.timings.witgen ?? 0), 0),
100
- oracles: acirExecutionResult.oracles,
101
- },
102
- },
103
- );
104
- }
105
-
106
- /**
107
- * Get the private circuit public inputs from the partial witness.
108
- * @param artifact - The function artifact
109
- * @param partialWitness - The partial witness, result of simulating the function.
110
- * @returns - The public inputs.
111
- */
112
- export function extractPrivateCircuitPublicInputs(
113
- artifact: FunctionArtifact,
114
- partialWitness: ACVMWitness,
115
- ): PrivateCircuitPublicInputs {
116
- const parametersSize = countArgumentsSize(artifact) + PRIVATE_CONTEXT_INPUTS_LENGTH;
117
- const returnsSize = PRIVATE_CIRCUIT_PUBLIC_INPUTS_LENGTH;
118
- const returnData = [];
119
- // Return values always appear in the witness after arguments.
120
- for (let i = parametersSize; i < parametersSize + returnsSize; i++) {
121
- const returnedField = partialWitness.get(i);
122
- if (returnedField === undefined) {
123
- throw new Error(`Missing return value for index ${i}`);
124
- }
125
- returnData.push(Fr.fromString(returnedField));
126
- }
127
- return PrivateCircuitPublicInputs.fromFields(returnData);
128
- }
129
-
130
- export async function readCurrentClassId(
131
- contractAddress: AztecAddress,
132
- instance: ContractInstance,
133
- executionDataProvider: ExecutionDataProvider | AztecNode,
134
- blockNumber: number,
135
- ) {
136
- const { sharedMutableSlot } = await SharedMutableValuesWithHash.getContractUpdateSlots(contractAddress);
137
- const sharedMutableValues = await SharedMutableValues.readFromTree(sharedMutableSlot, slot =>
138
- executionDataProvider.getPublicStorageAt(blockNumber, ProtocolContractAddress.ContractInstanceDeployer, slot),
139
- );
140
- let currentClassId = sharedMutableValues.svc.getCurrentAt(blockNumber)[0];
141
- if (currentClassId.isZero()) {
142
- currentClassId = instance.originalContractClassId;
143
- }
144
- return currentClassId;
145
- }
146
-
147
- export async function verifyCurrentClassId(
148
- contractAddress: AztecAddress,
149
- executionDataProvider: ExecutionDataProvider,
150
- blockNumber?: number,
151
- ) {
152
- const instance = await executionDataProvider.getContractInstance(contractAddress);
153
- blockNumber = blockNumber ?? (await executionDataProvider.getBlockNumber());
154
- const currentClassId = await readCurrentClassId(contractAddress, instance, executionDataProvider, blockNumber);
155
- if (!instance.currentContractClassId.equals(currentClassId)) {
156
- throw new Error(
157
- `Contract ${contractAddress} is outdated, current class id is ${currentClassId}, local class id is ${instance.currentContractClassId}`,
158
- );
159
- }
160
- }