-
Notifications
You must be signed in to change notification settings - Fork 184
/
simulator.ts
319 lines (293 loc) · 10.4 KB
/
simulator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import { type AztecNode, type FunctionCall, type Note, type TxExecutionRequest } from '@aztec/circuit-types';
import { CallContext, FunctionData } from '@aztec/circuits.js';
import { Grumpkin } from '@aztec/circuits.js/barretenberg';
import {
type ArrayType,
type FunctionArtifactWithDebugMetadata,
FunctionSelector,
FunctionType,
encodeArguments,
} from '@aztec/foundation/abi';
import { AztecAddress } from '@aztec/foundation/aztec-address';
import { type EthAddress } from '@aztec/foundation/eth-address';
import { Fr } from '@aztec/foundation/fields';
import { type DebugLogger, createDebugLogger } from '@aztec/foundation/log';
import { type WasmBlackBoxFunctionSolver, createBlackBoxSolver } from '@noir-lang/acvm_js';
import { createSimulationError } from '../common/errors.js';
import { PackedArgsCache } from '../common/packed_args_cache.js';
import { ClientExecutionContext } from './client_execution_context.js';
import { type DBOracle } from './db_oracle.js';
import { ExecutionNoteCache } from './execution_note_cache.js';
import { type ExecutionResult } from './execution_result.js';
import { executePrivateFunction } from './private_execution.js';
import { executeUnconstrainedFunction } from './unconstrained_execution.js';
import { ViewDataOracle } from './view_data_oracle.js';
/**
* The ACIR simulator.
*/
export class AcirSimulator {
private static solver: Promise<WasmBlackBoxFunctionSolver>; // ACVM's backend
private log: DebugLogger;
constructor(private db: DBOracle, private node: AztecNode) {
this.log = createDebugLogger('aztec:simulator');
}
/**
* Gets or initializes the ACVM WasmBlackBoxFunctionSolver.
*
* @remarks
*
* Occurs only once across all instances of AcirSimulator.
* Speeds up execution by only performing setup tasks (like pedersen
* generator initialization) one time.
* TODO(https://github.com/AztecProtocol/aztec-packages/issues/1627):
* determine whether this requires a lock
*
* @returns ACVM WasmBlackBoxFunctionSolver
*/
public static getSolver(): Promise<WasmBlackBoxFunctionSolver> {
if (!this.solver) {
this.solver = createBlackBoxSolver();
}
return this.solver;
}
/**
* Runs a private function.
* @param request - The transaction request.
* @param entryPointArtifact - The artifact of the entry point function.
* @param contractAddress - The address of the contract (should match request.origin)
* @param portalContractAddress - The address of the portal contract.
* @param msgSender - The address calling the function. This can be replaced to simulate a call from another contract or a specific account.
* @returns The result of the execution.
*/
public async run(
request: TxExecutionRequest,
entryPointArtifact: FunctionArtifactWithDebugMetadata,
contractAddress: AztecAddress,
portalContractAddress: EthAddress,
msgSender = AztecAddress.ZERO,
): Promise<ExecutionResult> {
if (entryPointArtifact.functionType !== FunctionType.SECRET) {
throw new Error(`Cannot run ${entryPointArtifact.functionType} function as secret`);
}
if (request.origin !== contractAddress) {
this.log.warn(
`Request origin does not match contract address in simulation. Request origin: ${request.origin}, contract address: ${contractAddress}`,
);
}
const curve = new Grumpkin();
const header = await this.db.getHeader();
// reserve the first side effect for the tx hash (inserted by the private kernel)
const startSideEffectCounter = 1;
const callContext = new CallContext(
msgSender,
contractAddress,
portalContractAddress,
FunctionSelector.fromNameAndParameters(entryPointArtifact.name, entryPointArtifact.parameters),
false,
false,
startSideEffectCounter,
);
const context = new ClientExecutionContext(
contractAddress,
request.argsHash,
request.txContext,
callContext,
header,
request.authWitnesses,
PackedArgsCache.create(request.packedArguments),
new ExecutionNoteCache(),
this.db,
curve,
this.node,
startSideEffectCounter,
);
try {
const executionResult = await executePrivateFunction(
context,
entryPointArtifact,
contractAddress,
request.functionData,
);
return executionResult;
} catch (err) {
throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during private execution'));
}
}
/**
* Runs an unconstrained function.
* @param request - The transaction request.
* @param entryPointArtifact - The artifact of the entry point function.
* @param contractAddress - The address of the contract.
* @param aztecNode - The AztecNode instance.
*/
public async runUnconstrained(
request: FunctionCall,
entryPointArtifact: FunctionArtifactWithDebugMetadata,
contractAddress: AztecAddress,
) {
if (entryPointArtifact.functionType !== FunctionType.UNCONSTRAINED) {
throw new Error(`Cannot run ${entryPointArtifact.functionType} function as constrained`);
}
const context = new ViewDataOracle(contractAddress, [], this.db, this.node);
try {
return await executeUnconstrainedFunction(
context,
entryPointArtifact,
contractAddress,
request.functionData,
request.args,
);
} catch (err) {
throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during private execution'));
}
}
/**
* Computes the inner nullifier of a note.
* @param contractAddress - The address of the contract.
* @param nonce - The nonce of the note hash.
* @param storageSlot - The storage slot.
* @param noteTypeId - The note type identifier.
* @param note - The note.
* @returns The nullifier.
*/
public async computeNoteHashAndNullifier(
contractAddress: AztecAddress,
nonce: Fr,
storageSlot: Fr,
noteTypeId: Fr,
note: Note,
) {
const artifact: FunctionArtifactWithDebugMetadata | undefined = await this.db.getFunctionArtifactByName(
contractAddress,
'compute_note_hash_and_nullifier',
);
if (!artifact) {
throw new Error(
`Mandatory implementation of "compute_note_hash_and_nullifier" missing in noir contract ${contractAddress.toString()}.`,
);
}
if (artifact.parameters.length != 5) {
throw new Error(
`Expected 5 parameters in mandatory implementation of "compute_note_hash_and_nullifier", but found ${
artifact.parameters.length
} in noir contract ${contractAddress.toString()}.`,
);
}
const maxNoteFields = (artifact.parameters[artifact.parameters.length - 1].type as ArrayType).length;
if (maxNoteFields < note.items.length) {
throw new Error(
`The note being processed has ${note.items.length} fields, while "compute_note_hash_and_nullifier" can only handle a maximum of ${maxNoteFields} fields. Please consider increasing the allowed field size to accommodate all notes generated from the contract.`,
);
}
const extendedNoteItems = note.items.concat(Array(maxNoteFields - note.items.length).fill(Fr.ZERO));
const execRequest: FunctionCall = {
to: contractAddress,
functionData: FunctionData.empty(),
args: encodeArguments(artifact, [contractAddress, nonce, storageSlot, noteTypeId, extendedNoteItems]),
};
const [innerNoteHash, siloedNoteHash, uniqueSiloedNoteHash, innerNullifier] = (await this.runUnconstrained(
execRequest,
artifact,
contractAddress,
)) as bigint[];
return {
innerNoteHash: new Fr(innerNoteHash),
siloedNoteHash: new Fr(siloedNoteHash),
uniqueSiloedNoteHash: new Fr(uniqueSiloedNoteHash),
innerNullifier: new Fr(innerNullifier),
};
}
/**
* Computes the inner note hash of a note, which contains storage slot and the custom note hash.
* @param contractAddress - The address of the contract.
* @param storageSlot - The storage slot.
* @param noteTypeId - The note type identifier.
* @param note - The note.
* @returns The note hash.
*/
public async computeInnerNoteHash(contractAddress: AztecAddress, storageSlot: Fr, noteTypeId: Fr, note: Note) {
const { innerNoteHash } = await this.computeNoteHashAndNullifier(
contractAddress,
Fr.ZERO,
storageSlot,
noteTypeId,
note,
);
return innerNoteHash;
}
/**
* Computes the unique note hash of a note.
* @param contractAddress - The address of the contract.
* @param nonce - The nonce of the note hash.
* @param storageSlot - The storage slot.
* @param noteTypeId - The note type identifier.
* @param note - The note.
* @returns The note hash.
*/
public async computeUniqueSiloedNoteHash(
contractAddress: AztecAddress,
nonce: Fr,
storageSlot: Fr,
noteTypeId: Fr,
note: Note,
) {
const { uniqueSiloedNoteHash } = await this.computeNoteHashAndNullifier(
contractAddress,
nonce,
storageSlot,
noteTypeId,
note,
);
return uniqueSiloedNoteHash;
}
/**
* Computes the siloed note hash of a note.
* @param contractAddress - The address of the contract.
* @param nonce - The nonce of the note hash.
* @param storageSlot - The storage slot.
* @param noteTypeId - The note type identifier.
* @param note - The note.
* @returns The note hash.
*/
public async computeSiloedNoteHash(
contractAddress: AztecAddress,
nonce: Fr,
storageSlot: Fr,
noteTypeId: Fr,
note: Note,
) {
const { siloedNoteHash } = await this.computeNoteHashAndNullifier(
contractAddress,
nonce,
storageSlot,
noteTypeId,
note,
);
return siloedNoteHash;
}
/**
* Computes the inner note hash of a note, which contains storage slot and the custom note hash.
* @param contractAddress - The address of the contract.
* @param nonce - The nonce of the unique note hash.
* @param storageSlot - The storage slot.
* @param noteTypeId - The note type identifier.
* @param note - The note.
* @returns The note hash.
*/
public async computeInnerNullifier(
contractAddress: AztecAddress,
nonce: Fr,
storageSlot: Fr,
noteTypeId: Fr,
note: Note,
) {
const { innerNullifier } = await this.computeNoteHashAndNullifier(
contractAddress,
nonce,
storageSlot,
noteTypeId,
note,
);
return innerNullifier;
}
}