@aztec/txe 0.0.0-test.1 → 0.0.1-commit.5daedc8

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