@aztec/txe 0.0.0-test.0 → 0.0.1-commit.001888fc

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 (96) hide show
  1. package/dest/bin/index.d.ts +1 -1
  2. package/dest/bin/index.js +3 -2
  3. package/dest/constants.d.ts +3 -0
  4. package/dest/constants.d.ts.map +1 -0
  5. package/dest/constants.js +2 -0
  6. package/dest/index.d.ts +1 -1
  7. package/dest/index.d.ts.map +1 -1
  8. package/dest/index.js +146 -82
  9. package/dest/oracle/interfaces.d.ts +58 -0
  10. package/dest/oracle/interfaces.d.ts.map +1 -0
  11. package/dest/oracle/interfaces.js +3 -0
  12. package/dest/oracle/txe_oracle_public_context.d.ts +34 -0
  13. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -0
  14. package/dest/oracle/txe_oracle_public_context.js +122 -0
  15. package/dest/oracle/txe_oracle_top_level_context.d.ts +65 -0
  16. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
  17. package/dest/oracle/txe_oracle_top_level_context.js +542 -0
  18. package/dest/rpc_translator.d.ts +254 -0
  19. package/dest/rpc_translator.d.ts.map +1 -0
  20. package/dest/rpc_translator.js +791 -0
  21. package/dest/state_machine/archiver.d.ts +31 -0
  22. package/dest/state_machine/archiver.d.ts.map +1 -0
  23. package/dest/state_machine/archiver.js +85 -0
  24. package/dest/state_machine/dummy_p2p_client.d.ts +59 -0
  25. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -0
  26. package/dest/state_machine/dummy_p2p_client.js +153 -0
  27. package/dest/state_machine/global_variable_builder.d.ts +11 -0
  28. package/dest/state_machine/global_variable_builder.d.ts.map +1 -0
  29. package/dest/state_machine/global_variable_builder.js +22 -0
  30. package/dest/state_machine/index.d.ts +18 -0
  31. package/dest/state_machine/index.d.ts.map +1 -0
  32. package/dest/state_machine/index.js +72 -0
  33. package/dest/state_machine/mock_epoch_cache.d.ts +29 -0
  34. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -0
  35. package/dest/state_machine/mock_epoch_cache.js +58 -0
  36. package/dest/state_machine/synchronizer.d.ts +33 -0
  37. package/dest/state_machine/synchronizer.d.ts.map +1 -0
  38. package/dest/state_machine/synchronizer.js +59 -0
  39. package/dest/txe_session.d.ts +78 -0
  40. package/dest/txe_session.d.ts.map +1 -0
  41. package/dest/txe_session.js +364 -0
  42. package/dest/util/encoding.d.ts +641 -24
  43. package/dest/util/encoding.d.ts.map +1 -1
  44. package/dest/util/encoding.js +66 -11
  45. package/dest/util/expected_failure_error.d.ts +1 -1
  46. package/dest/util/expected_failure_error.d.ts.map +1 -1
  47. package/dest/util/txe_account_store.d.ts +10 -0
  48. package/dest/util/txe_account_store.d.ts.map +1 -0
  49. package/dest/util/{txe_account_data_provider.js → txe_account_store.js} +1 -1
  50. package/dest/util/txe_public_contract_data_source.d.ts +11 -11
  51. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  52. package/dest/util/txe_public_contract_data_source.js +21 -59
  53. package/dest/utils/block_creation.d.ts +28 -0
  54. package/dest/utils/block_creation.d.ts.map +1 -0
  55. package/dest/utils/block_creation.js +58 -0
  56. package/dest/utils/tx_effect_creation.d.ts +5 -0
  57. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  58. package/dest/utils/tx_effect_creation.js +13 -0
  59. package/package.json +30 -24
  60. package/src/bin/index.ts +3 -2
  61. package/src/constants.ts +3 -0
  62. package/src/index.ts +171 -103
  63. package/src/oracle/interfaces.ts +87 -0
  64. package/src/oracle/txe_oracle_public_context.ts +158 -0
  65. package/src/oracle/txe_oracle_top_level_context.ts +782 -0
  66. package/src/rpc_translator.ts +1218 -0
  67. package/src/state_machine/archiver.ts +97 -0
  68. package/src/state_machine/dummy_p2p_client.ts +227 -0
  69. package/src/state_machine/global_variable_builder.ts +38 -0
  70. package/src/state_machine/index.ts +120 -0
  71. package/src/state_machine/mock_epoch_cache.ts +72 -0
  72. package/src/state_machine/synchronizer.ts +88 -0
  73. package/src/txe_session.ts +556 -0
  74. package/src/util/encoding.ts +85 -11
  75. package/src/util/{txe_account_data_provider.ts → txe_account_store.ts} +1 -1
  76. package/src/util/txe_public_contract_data_source.ts +28 -69
  77. package/src/utils/block_creation.ts +97 -0
  78. package/src/utils/tx_effect_creation.ts +30 -0
  79. package/dest/node/txe_node.d.ts +0 -358
  80. package/dest/node/txe_node.d.ts.map +0 -1
  81. package/dest/node/txe_node.js +0 -504
  82. package/dest/oracle/txe_oracle.d.ts +0 -152
  83. package/dest/oracle/txe_oracle.d.ts.map +0 -1
  84. package/dest/oracle/txe_oracle.js +0 -833
  85. package/dest/txe_service/txe_service.d.ts +0 -212
  86. package/dest/txe_service/txe_service.d.ts.map +0 -1
  87. package/dest/txe_service/txe_service.js +0 -572
  88. package/dest/util/txe_account_data_provider.d.ts +0 -10
  89. package/dest/util/txe_account_data_provider.d.ts.map +0 -1
  90. package/dest/util/txe_world_state_db.d.ts +0 -14
  91. package/dest/util/txe_world_state_db.d.ts.map +0 -1
  92. package/dest/util/txe_world_state_db.js +0 -27
  93. package/src/node/txe_node.ts +0 -725
  94. package/src/oracle/txe_oracle.ts +0 -1241
  95. package/src/txe_service/txe_service.ts +0 -749
  96. package/src/util/txe_world_state_db.ts +0 -38
package/src/index.ts CHANGED
@@ -1,25 +1,30 @@
1
1
  import { SchnorrAccountContractArtifact } from '@aztec/accounts/schnorr';
2
+ import { type NoirCompiledContract, loadContractArtifact } from '@aztec/aztec.js/abi';
3
+ import { AztecAddress } from '@aztec/aztec.js/addresses';
2
4
  import {
3
- AztecAddress,
4
- type ContractArtifact,
5
5
  type ContractInstanceWithAddress,
6
- Fr,
7
- PublicKeys,
8
- deriveKeys,
9
- getContractInstanceFromDeployParams,
10
- loadContractArtifact,
11
- } from '@aztec/aztec.js';
6
+ getContractInstanceFromInstantiationParams,
7
+ } from '@aztec/aztec.js/contracts';
8
+ import { Fr } from '@aztec/aztec.js/fields';
9
+ import { PublicKeys, deriveKeys } from '@aztec/aztec.js/keys';
12
10
  import { createSafeJsonRpcServer } from '@aztec/foundation/json-rpc/server';
13
11
  import type { Logger } from '@aztec/foundation/log';
14
- import { type ProtocolContract, protocolContractNames } from '@aztec/protocol-contracts';
12
+ import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
13
+ import { protocolContractNames } from '@aztec/protocol-contracts';
15
14
  import { BundledProtocolContractsProvider } from '@aztec/protocol-contracts/providers/bundle';
16
- import type { ApiSchemaFor, ZodFor } from '@aztec/stdlib/schemas';
15
+ import { ContractStore } from '@aztec/pxe/server';
16
+ import { computeArtifactHash } from '@aztec/stdlib/contract';
17
+ import type { ContractArtifactWithHash } from '@aztec/stdlib/contract';
18
+ import type { ApiSchemaFor } from '@aztec/stdlib/schemas';
19
+ import { zodFor } from '@aztec/stdlib/schemas';
17
20
 
21
+ import { createHash } from 'crypto';
22
+ import { createReadStream } from 'fs';
18
23
  import { readFile, readdir } from 'fs/promises';
19
- import { join } from 'path';
24
+ import { join, parse } from 'path';
20
25
  import { z } from 'zod';
21
26
 
22
- import { TXEService } from './txe_service/txe_service.js';
27
+ import { type TXEOracleFunctionName, TXESession } from './txe_session.js';
23
28
  import {
24
29
  type ForeignCallArgs,
25
30
  ForeignCallArgsSchema,
@@ -27,107 +32,154 @@ import {
27
32
  type ForeignCallResult,
28
33
  ForeignCallResultSchema,
29
34
  type ForeignCallSingle,
35
+ addressFromSingle,
30
36
  fromArray,
31
37
  fromSingle,
32
- toForeignCallResult,
33
38
  toSingle,
34
39
  } from './util/encoding.js';
35
40
 
36
- const TXESessions = new Map<number, TXEService>();
41
+ const sessions = new Map<number, TXESession>();
37
42
 
38
- const TXEArtifactsCache = new Map<string, { artifact: ContractArtifact; instance: ContractInstanceWithAddress }>();
39
-
40
- type MethodNames<T> = {
41
- [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
42
- }[keyof T];
43
+ /*
44
+ * TXE typically has to load the same contract artifacts over and over again for multiple tests,
45
+ * so we cache them here to avoid loading from disk repeatedly.
46
+ *
47
+ * The in-flight map coalesces concurrent requests for the same cache key so that
48
+ * computeArtifactHash (very expensive) is only run once even under parallelism.
49
+ */
50
+ const TXEArtifactsCache = new Map<
51
+ string,
52
+ { artifact: ContractArtifactWithHash; instance: ContractInstanceWithAddress }
53
+ >();
54
+ const TXEArtifactsCacheInFlight = new Map<
55
+ string,
56
+ Promise<{ artifact: ContractArtifactWithHash; instance: ContractInstanceWithAddress }>
57
+ >();
43
58
 
44
59
  type TXEForeignCallInput = {
45
60
  session_id: number;
46
- function: MethodNames<TXEService> | 'reset';
61
+ function: TXEOracleFunctionName;
47
62
  root_path: string;
48
63
  package_name: string;
49
64
  inputs: ForeignCallArgs;
50
65
  };
51
66
 
52
- const TXEForeignCallInputSchema = z.object({
53
- // eslint-disable-next-line camelcase
54
- session_id: z.number().int().nonnegative(),
55
- function: z.string() as ZodFor<MethodNames<TXEService> | 'reset'>,
56
- // eslint-disable-next-line camelcase
57
- root_path: z.string(),
58
- // eslint-disable-next-line camelcase
59
- package_name: z.string(),
60
- inputs: ForeignCallArgsSchema,
61
- }) satisfies ZodFor<TXEForeignCallInput>;
67
+ const TXEForeignCallInputSchema = zodFor<TXEForeignCallInput>()(
68
+ z.object({
69
+ // eslint-disable-next-line camelcase
70
+ session_id: z.number().int().nonnegative(),
71
+ function: z.string() as z.ZodType<TXEOracleFunctionName>,
72
+ // eslint-disable-next-line camelcase
73
+ root_path: z.string(),
74
+ // eslint-disable-next-line camelcase
75
+ package_name: z.string(),
76
+ inputs: ForeignCallArgsSchema,
77
+ }),
78
+ );
62
79
 
63
80
  class TXEDispatcher {
64
- private protocolContracts!: ProtocolContract[];
81
+ private contractStore!: ContractStore;
65
82
 
66
83
  constructor(private logger: Logger) {}
67
84
 
85
+ private fastHashFile(path: string) {
86
+ return new Promise(resolve => {
87
+ const fd = createReadStream(path);
88
+ const hash = createHash('sha1');
89
+ hash.setEncoding('hex');
90
+
91
+ fd.on('end', function () {
92
+ hash.end();
93
+ resolve(hash.read());
94
+ });
95
+
96
+ fd.pipe(hash);
97
+ });
98
+ }
99
+
68
100
  async #processDeployInputs({ inputs, root_path: rootPath, package_name: packageName }: TXEForeignCallInput) {
69
- const [pathStr, contractName, initializer] = inputs.slice(0, 3).map(input =>
101
+ const [contractPath, initializer] = inputs.slice(0, 2).map(input =>
70
102
  fromArray(input as ForeignCallArray)
71
103
  .map(char => String.fromCharCode(char.toNumber()))
72
104
  .join(''),
73
105
  );
74
106
 
75
- const decodedArgs = fromArray(inputs[4] as ForeignCallArray);
76
- const secret = fromSingle(inputs[5] as ForeignCallSingle);
107
+ const decodedArgs = fromArray(inputs[3] as ForeignCallArray);
108
+ const secret = fromSingle(inputs[4] as ForeignCallSingle);
109
+ const salt = fromSingle(inputs[5] as ForeignCallSingle);
110
+ const deployer = addressFromSingle(inputs[6] as ForeignCallSingle);
77
111
  const publicKeys = secret.equals(Fr.ZERO) ? PublicKeys.default() : (await deriveKeys(secret)).publicKeys;
78
112
  const publicKeysHash = await publicKeys.hash();
79
113
 
80
- const cacheKey = `${pathStr}-${contractName}-${initializer}-${decodedArgs
114
+ let artifactPath = '';
115
+ const { dir: contractDirectory, base: contractFilename } = parse(contractPath);
116
+ if (contractDirectory) {
117
+ if (contractDirectory.includes('@')) {
118
+ // We're deploying a contract that belongs in a workspace
119
+ // env.deploy("../path/to/workspace/root@packageName/contractName")
120
+ const [workspace, pkg] = contractDirectory.split('@');
121
+ const targetPath = join(rootPath, workspace, '/target');
122
+ this.logger.debug(`Looking for compiled artifact in workspace ${targetPath}`);
123
+ artifactPath = join(targetPath, `${pkg}-${contractFilename}.json`);
124
+ } else {
125
+ // We're deploying a standalone external contract
126
+ // env.deploy("../path/to/contract/root/contractName")
127
+ const targetPath = join(rootPath, contractDirectory, '/target');
128
+ this.logger.debug(`Looking for compiled artifact in ${targetPath}`);
129
+ [artifactPath] = (await readdir(targetPath)).filter(file => file.endsWith(`-${contractFilename}.json`));
130
+ }
131
+ } else {
132
+ // We're deploying a local contract
133
+ // env.deploy("contractName")
134
+ artifactPath = join(rootPath, './target', `${packageName}-${contractFilename}.json`);
135
+ }
136
+
137
+ const fileHash = await this.fastHashFile(artifactPath);
138
+
139
+ const cacheKey = `${contractDirectory ?? ''}-${contractFilename}-${initializer}-${decodedArgs
81
140
  .map(arg => arg.toString())
82
- .join('-')}-${publicKeysHash.toString()}`;
141
+ .join('-')}-${publicKeysHash}-${salt}-${deployer}-${fileHash}`;
83
142
 
84
- let artifact;
85
143
  let instance;
144
+ let artifact: ContractArtifactWithHash;
86
145
 
87
146
  if (TXEArtifactsCache.has(cacheKey)) {
88
147
  this.logger.debug(`Using cached artifact for ${cacheKey}`);
89
148
  ({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
90
149
  } else {
91
- let artifactPath = '';
92
- // We're deploying the contract under test
93
- // env.deploy_self("contractName")
94
- if (!pathStr) {
95
- artifactPath = join(rootPath, './target', `${packageName}-${contractName}.json`);
96
- } else {
97
- // We're deploying a contract that belongs in a workspace
98
- // env.deploy("../path/to/workspace/root@packageName", "contractName")
99
- if (pathStr.includes('@')) {
100
- const [workspace, pkg] = pathStr.split('@');
101
- const targetPath = join(rootPath, workspace, './target');
102
- this.logger.debug(`Looking for compiled artifact in workspace ${targetPath}`);
103
- artifactPath = join(targetPath, `${pkg}-${contractName}.json`);
104
- } else {
105
- // We're deploying a standalone contract
106
- // env.deploy("../path/to/contract/root", "contractName")
107
- const targetPath = join(rootPath, pathStr, './target');
108
- this.logger.debug(`Looking for compiled artifact in ${targetPath}`);
109
- [artifactPath] = (await readdir(targetPath)).filter(file => file.endsWith(`-${contractName}.json`));
110
- }
150
+ if (!TXEArtifactsCacheInFlight.has(cacheKey)) {
151
+ this.logger.debug(`Loading compiled artifact ${artifactPath}`);
152
+ const compute = async () => {
153
+ const artifactJSON = JSON.parse(await readFile(artifactPath, 'utf-8')) as NoirCompiledContract;
154
+ const artifactWithoutHash = loadContractArtifact(artifactJSON);
155
+ const computedArtifact: ContractArtifactWithHash = {
156
+ ...artifactWithoutHash,
157
+ // Artifact hash is *very* expensive to compute, so we do it here once
158
+ // and the TXE contract data provider can cache it
159
+ artifactHash: await computeArtifactHash(artifactWithoutHash),
160
+ };
161
+ this.logger.debug(
162
+ `Deploy ${computedArtifact.name} with initializer ${initializer}(${decodedArgs}) and public keys hash ${publicKeysHash.toString()}`,
163
+ );
164
+ const computedInstance = await getContractInstanceFromInstantiationParams(computedArtifact, {
165
+ constructorArgs: decodedArgs,
166
+ skipArgsDecoding: true,
167
+ salt,
168
+ publicKeys,
169
+ constructorArtifact: initializer ? initializer : undefined,
170
+ deployer,
171
+ });
172
+ const result = { artifact: computedArtifact, instance: computedInstance };
173
+ TXEArtifactsCache.set(cacheKey, result);
174
+ TXEArtifactsCacheInFlight.delete(cacheKey);
175
+ return result;
176
+ };
177
+ TXEArtifactsCacheInFlight.set(cacheKey, compute());
111
178
  }
112
- this.logger.debug(`Loading compiled artifact ${artifactPath}`);
113
- artifact = loadContractArtifact(JSON.parse(await readFile(artifactPath, 'utf-8')));
114
- this.logger.debug(
115
- `Deploy ${
116
- artifact.name
117
- } with initializer ${initializer}(${decodedArgs}) and public keys hash ${publicKeysHash.toString()}`,
118
- );
119
- instance = await getContractInstanceFromDeployParams(artifact, {
120
- constructorArgs: decodedArgs,
121
- skipArgsDecoding: true,
122
- salt: Fr.ONE,
123
- publicKeys,
124
- constructorArtifact: initializer ? initializer : undefined,
125
- deployer: AztecAddress.ZERO,
126
- });
127
- TXEArtifactsCache.set(cacheKey, { artifact, instance });
179
+ ({ artifact, instance } = await TXEArtifactsCacheInFlight.get(cacheKey)!);
128
180
  }
129
181
 
130
- inputs.splice(0, 2, artifact, instance, toSingle(secret));
182
+ inputs.splice(0, 1, artifact, instance, toSingle(secret));
131
183
  }
132
184
 
133
185
  async #processAddAccountInputs({ inputs }: TXEForeignCallInput) {
@@ -135,25 +187,42 @@ class TXEDispatcher {
135
187
 
136
188
  const cacheKey = `SchnorrAccountContract-${secret}`;
137
189
 
138
- let artifact;
190
+ let artifact: ContractArtifactWithHash;
139
191
  let instance;
140
192
 
141
193
  if (TXEArtifactsCache.has(cacheKey)) {
142
194
  this.logger.debug(`Using cached artifact for ${cacheKey}`);
143
195
  ({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
144
196
  } else {
145
- const keys = await deriveKeys(secret);
146
- const args = [keys.publicKeys.masterIncomingViewingPublicKey.x, keys.publicKeys.masterIncomingViewingPublicKey.y];
147
- artifact = SchnorrAccountContractArtifact;
148
- instance = await getContractInstanceFromDeployParams(artifact, {
149
- constructorArgs: args,
150
- skipArgsDecoding: true,
151
- salt: Fr.ONE,
152
- publicKeys: keys.publicKeys,
153
- constructorArtifact: 'constructor',
154
- deployer: AztecAddress.ZERO,
155
- });
156
- TXEArtifactsCache.set(cacheKey, { artifact, instance });
197
+ if (!TXEArtifactsCacheInFlight.has(cacheKey)) {
198
+ const compute = async () => {
199
+ const keys = await deriveKeys(secret);
200
+ const args = [
201
+ keys.publicKeys.masterIncomingViewingPublicKey.x,
202
+ keys.publicKeys.masterIncomingViewingPublicKey.y,
203
+ ];
204
+ const computedArtifact: ContractArtifactWithHash = {
205
+ ...SchnorrAccountContractArtifact,
206
+ // Artifact hash is *very* expensive to compute, so we do it here once
207
+ // and the TXE contract data provider can cache it
208
+ artifactHash: await computeArtifactHash(SchnorrAccountContractArtifact),
209
+ };
210
+ const computedInstance = await getContractInstanceFromInstantiationParams(computedArtifact, {
211
+ constructorArgs: args,
212
+ skipArgsDecoding: true,
213
+ salt: Fr.ONE,
214
+ publicKeys: keys.publicKeys,
215
+ constructorArtifact: 'constructor',
216
+ deployer: AztecAddress.ZERO,
217
+ });
218
+ const result = { artifact: computedArtifact, instance: computedInstance };
219
+ TXEArtifactsCache.set(cacheKey, result);
220
+ TXEArtifactsCacheInFlight.delete(cacheKey);
221
+ return result;
222
+ };
223
+ TXEArtifactsCacheInFlight.set(cacheKey, compute());
224
+ }
225
+ ({ artifact, instance } = await TXEArtifactsCacheInFlight.get(cacheKey)!);
157
226
  }
158
227
 
159
228
  inputs.splice(0, 0, artifact, instance);
@@ -164,35 +233,34 @@ class TXEDispatcher {
164
233
  const { session_id: sessionId, function: functionName, inputs } = callData;
165
234
  this.logger.debug(`Calling ${functionName} on session ${sessionId}`);
166
235
 
167
- if (!TXESessions.has(sessionId) && functionName != 'reset') {
236
+ if (!sessions.has(sessionId)) {
168
237
  this.logger.debug(`Creating new session ${sessionId}`);
169
- if (!this.protocolContracts) {
170
- this.protocolContracts = await Promise.all(
171
- protocolContractNames.map(name => new BundledProtocolContractsProvider().getProtocolContractArtifact(name)),
172
- );
238
+ if (!this.contractStore) {
239
+ const kvStore = await openTmpStore('txe-contracts');
240
+ this.contractStore = new ContractStore(kvStore);
241
+ const provider = new BundledProtocolContractsProvider();
242
+ for (const name of protocolContractNames) {
243
+ const { instance, artifact } = await provider.getProtocolContractArtifact(name);
244
+ await this.contractStore.addContractArtifact(artifact);
245
+ await this.contractStore.addContractInstance(instance);
246
+ }
247
+ this.logger.debug('Registered protocol contracts in shared contract store');
173
248
  }
174
- TXESessions.set(sessionId, await TXEService.init(this.logger, this.protocolContracts));
249
+ sessions.set(sessionId, await TXESession.init(this.contractStore));
175
250
  }
176
251
 
177
252
  switch (functionName) {
178
- case 'reset': {
179
- TXESessions.delete(sessionId) &&
180
- this.logger.debug(`Called reset on session ${sessionId}, yeeting it out of existence`);
181
- return toForeignCallResult([]);
182
- }
183
- case 'deploy': {
253
+ case 'aztec_txe_deploy': {
184
254
  await this.#processDeployInputs(callData);
185
255
  break;
186
256
  }
187
- case 'addAccount': {
257
+ case 'aztec_txe_addAccount': {
188
258
  await this.#processAddAccountInputs(callData);
189
259
  break;
190
260
  }
191
261
  }
192
262
 
193
- const txeService = TXESessions.get(sessionId);
194
- const response = await (txeService as any)[functionName](...inputs);
195
- return response;
263
+ return await sessions.get(sessionId)!.processFunction(functionName, inputs);
196
264
  }
197
265
  }
198
266
 
@@ -0,0 +1,87 @@
1
+ import type { ContractArtifact } from '@aztec/aztec.js/abi';
2
+ import { CompleteAddress } from '@aztec/aztec.js/addresses';
3
+ import type { ContractInstanceWithAddress } from '@aztec/aztec.js/contracts';
4
+ import { TxHash } from '@aztec/aztec.js/tx';
5
+ import { BlockNumber } from '@aztec/foundation/branded-types';
6
+ import type { Fr } from '@aztec/foundation/curves/bn254';
7
+ import type { EventSelector, FunctionSelector } from '@aztec/stdlib/abi';
8
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
9
+ import type { UInt64 } from '@aztec/stdlib/types';
10
+
11
+ // These interfaces complement the ones defined in PXE, and combined with those contain the full list of oracles used by
12
+ // aztec-nr. In particular, these include the ones needed to run Brillig code associated to #[external("public")] functions that has
13
+ // not been transpiled (e.g. in the context of a Noir test) as well as the ones associated with managing the state of
14
+ // such a Noir test (deploying contracts, manipulating block time, making calls, etc) - the so called 'top level test
15
+ // context'.
16
+
17
+ /**
18
+ * Oracle methods associated with the execution of an Aztec #[external("public")] function.
19
+ *
20
+ * Note that real contracts have their Brillig calls to these be transpiled into opcodes, the oracles are only executed
21
+ * as such when running the original Brillig code, e.g. when invoking functions that interact with a PublicContext
22
+ * directly in a Noir test.
23
+ */
24
+ export interface IAvmExecutionOracle {
25
+ isAvm: true;
26
+
27
+ address(): Promise<AztecAddress>;
28
+ sender(): Promise<AztecAddress>;
29
+ blockNumber(): Promise<BlockNumber>;
30
+ timestamp(): Promise<bigint>;
31
+ isStaticCall(): Promise<boolean>;
32
+ chainId(): Promise<Fr>;
33
+ version(): Promise<Fr>;
34
+ emitNullifier(nullifier: Fr): Promise<void>;
35
+ emitNoteHash(noteHash: Fr): Promise<void>;
36
+ nullifierExists(siloedNullifier: Fr): Promise<boolean>;
37
+ storageWrite(slot: Fr, value: Fr): Promise<void>;
38
+ storageRead(slot: Fr, contractAddress: AztecAddress): Promise<Fr>;
39
+ }
40
+
41
+ /**
42
+ * Oracle methods associated with the execution of an Aztec Noir test.
43
+ */
44
+ export interface ITxeExecutionOracle {
45
+ isTxe: true;
46
+
47
+ getDefaultAddress(): AztecAddress;
48
+ getNextBlockNumber(): Promise<BlockNumber>;
49
+ getNextBlockTimestamp(): Promise<UInt64>;
50
+ advanceBlocksBy(blocks: number): Promise<void>;
51
+ advanceTimestampBy(duration: UInt64): void;
52
+ deploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, foreignSecret: Fr): Promise<void>;
53
+ createAccount(secret: Fr): Promise<CompleteAddress>;
54
+ addAccount(artifact: ContractArtifact, instance: ContractInstanceWithAddress, secret: Fr): Promise<CompleteAddress>;
55
+ addAuthWitness(address: AztecAddress, messageHash: Fr): Promise<void>;
56
+ getLastBlockTimestamp(): Promise<bigint>;
57
+ getLastTxEffects(): Promise<{
58
+ txHash: TxHash;
59
+ noteHashes: Fr[];
60
+ nullifiers: Fr[];
61
+ }>;
62
+ getPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise<Fr[][]>;
63
+ privateCallNewFlow(
64
+ from: AztecAddress,
65
+ targetContractAddress: AztecAddress,
66
+ functionSelector: FunctionSelector,
67
+ args: Fr[],
68
+ argsHash: Fr,
69
+ isStaticCall: boolean,
70
+ jobId: string,
71
+ ): Promise<Fr[]>;
72
+ executeUtilityFunction(
73
+ targetContractAddress: AztecAddress,
74
+ functionSelector: FunctionSelector,
75
+ args: Fr[],
76
+ jobId: string,
77
+ ): Promise<Fr[]>;
78
+ publicCallNewFlow(
79
+ from: AztecAddress,
80
+ targetContractAddress: AztecAddress,
81
+ calldata: Fr[],
82
+ isStaticCall: boolean,
83
+ ): Promise<Fr[]>;
84
+ // TODO(F-335): Drop this from here as it's not a real oracle handler - it's only called from
85
+ // RPCTranslator::txeGetPrivateEvents and never from Noir.
86
+ syncContractNonOracleMethod(contractAddress: AztecAddress, scope: AztecAddress, jobId: string): Promise<void>;
87
+ }
@@ -0,0 +1,158 @@
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
+ import { PublicDataWrite } from '@aztec/stdlib/avm';
5
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
6
+ import type { L2Block } from '@aztec/stdlib/block';
7
+ import { computePublicDataTreeLeafSlot, siloNoteHash, siloNullifier } from '@aztec/stdlib/hash';
8
+ import {
9
+ MerkleTreeId,
10
+ type MerkleTreeWriteOperations,
11
+ PublicDataTreeLeaf,
12
+ PublicDataTreeLeafPreimage,
13
+ } from '@aztec/stdlib/trees';
14
+ import { GlobalVariables, TxEffect, TxHash } from '@aztec/stdlib/tx';
15
+
16
+ import { insertTxEffectIntoWorldTrees, makeTXEBlock } from '../utils/block_creation.js';
17
+ import type { IAvmExecutionOracle } from './interfaces.js';
18
+
19
+ export class TXEOraclePublicContext implements IAvmExecutionOracle {
20
+ isAvm = true as const;
21
+
22
+ private logger: Logger;
23
+ private transientUniqueNoteHashes: Fr[] = [];
24
+ private transientSiloedNullifiers: Fr[] = [];
25
+ private publicDataWrites: PublicDataWrite[] = [];
26
+
27
+ constructor(
28
+ private contractAddress: AztecAddress,
29
+ private forkedWorldTrees: MerkleTreeWriteOperations,
30
+ private txRequestHash: Fr,
31
+ private globalVariables: GlobalVariables,
32
+ ) {
33
+ this.logger = createLogger('txe:public_context');
34
+
35
+ this.logger.debug('Entering Public Context', {
36
+ contractAddress,
37
+ blockNumber: globalVariables.blockNumber,
38
+ timestamp: globalVariables.timestamp,
39
+ });
40
+ }
41
+
42
+ address(): Promise<AztecAddress> {
43
+ return Promise.resolve(this.contractAddress);
44
+ }
45
+
46
+ sender(): Promise<AztecAddress> {
47
+ return Promise.resolve(AztecAddress.ZERO); // todo: change?
48
+ }
49
+
50
+ blockNumber(): Promise<BlockNumber> {
51
+ return Promise.resolve(this.globalVariables.blockNumber);
52
+ }
53
+
54
+ timestamp(): Promise<bigint> {
55
+ return Promise.resolve(this.globalVariables.timestamp);
56
+ }
57
+
58
+ isStaticCall(): Promise<boolean> {
59
+ return Promise.resolve(false);
60
+ }
61
+
62
+ chainId(): Promise<Fr> {
63
+ return Promise.resolve(this.globalVariables.chainId);
64
+ }
65
+
66
+ version(): Promise<Fr> {
67
+ return Promise.resolve(this.globalVariables.version);
68
+ }
69
+
70
+ async emitNullifier(nullifier: Fr) {
71
+ const siloedNullifier = await siloNullifier(this.contractAddress, nullifier);
72
+ this.transientSiloedNullifiers.push(siloedNullifier);
73
+ }
74
+
75
+ async emitNoteHash(noteHash: Fr) {
76
+ const siloedNoteHash = await siloNoteHash(this.contractAddress, noteHash);
77
+ // TODO: make the note hash unique - they are only siloed right now
78
+ this.transientUniqueNoteHashes.push(siloedNoteHash);
79
+ }
80
+
81
+ async nullifierExists(siloedNullifier: Fr): Promise<boolean> {
82
+ const treeIndex = (
83
+ await this.forkedWorldTrees.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, [siloedNullifier.toBuffer()])
84
+ )[0];
85
+ const transientIndex = this.transientSiloedNullifiers.find(n => n.equals(siloedNullifier));
86
+
87
+ return treeIndex !== undefined || transientIndex !== undefined;
88
+ }
89
+
90
+ async storageWrite(slot: Fr, value: Fr) {
91
+ this.logger.debug('AVM storage write', { slot, value });
92
+
93
+ const dataWrite = new PublicDataWrite(await computePublicDataTreeLeafSlot(this.contractAddress, slot), value);
94
+
95
+ this.publicDataWrites.push(dataWrite);
96
+
97
+ await this.forkedWorldTrees.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE, [
98
+ new PublicDataTreeLeaf(dataWrite.leafSlot, dataWrite.value).toBuffer(),
99
+ ]);
100
+ }
101
+
102
+ async storageRead(slot: Fr, contractAddress: AztecAddress): Promise<Fr> {
103
+ const leafSlot = await computePublicDataTreeLeafSlot(contractAddress, slot);
104
+
105
+ const lowLeafResult = await this.forkedWorldTrees.getPreviousValueIndex(
106
+ MerkleTreeId.PUBLIC_DATA_TREE,
107
+ leafSlot.toBigInt(),
108
+ );
109
+
110
+ const value =
111
+ !lowLeafResult || !lowLeafResult.alreadyPresent
112
+ ? Fr.ZERO
113
+ : (
114
+ (await this.forkedWorldTrees.getLeafPreimage(
115
+ MerkleTreeId.PUBLIC_DATA_TREE,
116
+ lowLeafResult.index,
117
+ )) as PublicDataTreeLeafPreimage
118
+ ).leaf.value;
119
+
120
+ this.logger.debug('AVM storage read', { slot, contractAddress, value });
121
+
122
+ return value;
123
+ }
124
+
125
+ async close(): Promise<L2Block> {
126
+ this.logger.debug('Exiting Public Context, building block with collected side effects', {
127
+ blockNumber: this.globalVariables.blockNumber,
128
+ });
129
+
130
+ const txEffect = this.makeTxEffect();
131
+ await insertTxEffectIntoWorldTrees(txEffect, this.forkedWorldTrees);
132
+
133
+ const block = await makeTXEBlock(this.forkedWorldTrees, this.globalVariables, [txEffect]);
134
+
135
+ await this.forkedWorldTrees.close();
136
+
137
+ this.logger.debug('Exited PublicContext with built block', {
138
+ blockNumber: block.number,
139
+ txEffects: block.body.txEffects,
140
+ });
141
+
142
+ return block;
143
+ }
144
+
145
+ private makeTxEffect(): TxEffect {
146
+ const txEffect = TxEffect.empty();
147
+
148
+ txEffect.noteHashes = this.transientUniqueNoteHashes;
149
+ txEffect.nullifiers = [this.txRequestHash, ...this.transientSiloedNullifiers];
150
+
151
+ txEffect.publicDataWrites = this.publicDataWrites;
152
+ // TODO: support public logs
153
+
154
+ txEffect.txHash = new TxHash(new Fr(this.globalVariables.blockNumber));
155
+
156
+ return txEffect;
157
+ }
158
+ }