@aztec/txe 0.0.1-commit.4d79d1f2d → 0.0.1-commit.4d9804df

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 (174) hide show
  1. package/dest/AuthRegistry-QVGDDH5X.js +3 -0
  2. package/dest/AuthRegistry-QVGDDH5X.js.map +7 -0
  3. package/dest/ContractClassRegistry-VWR3F42P.js +3 -0
  4. package/dest/ContractClassRegistry-VWR3F42P.js.map +7 -0
  5. package/dest/ContractInstanceRegistry-FHIWE33X.js +3 -0
  6. package/dest/ContractInstanceRegistry-FHIWE33X.js.map +7 -0
  7. package/dest/FeeJuice-SAOWVGG7.js +3 -0
  8. package/dest/FeeJuice-SAOWVGG7.js.map +7 -0
  9. package/dest/HandshakeRegistry-GY5CPEPS.js +3 -0
  10. package/dest/HandshakeRegistry-GY5CPEPS.js.map +7 -0
  11. package/dest/MultiCallEntrypoint-QG5H33ZZ.js +3 -0
  12. package/dest/MultiCallEntrypoint-QG5H33ZZ.js.map +7 -0
  13. package/dest/SchnorrAccount-NME3E45O.js +3 -0
  14. package/dest/SchnorrAccount-NME3E45O.js.map +7 -0
  15. package/dest/SchnorrInitializerlessAccount-WTGXU6SW.js +3 -0
  16. package/dest/SchnorrInitializerlessAccount-WTGXU6SW.js.map +7 -0
  17. package/dest/bin/check_txe_oracle_version.d.ts +2 -0
  18. package/dest/bin/check_txe_oracle_version.d.ts.map +1 -0
  19. package/dest/bin/check_txe_oracle_version.js +53 -0
  20. package/dest/bin/index.js +3 -30
  21. package/dest/bin/index.js.map +7 -0
  22. package/dest/bin/oracle_test_server.d.ts +3 -0
  23. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  24. package/dest/bin/oracle_test_server.js +41 -0
  25. package/dest/chunk-32UHX7YY.js +3 -0
  26. package/dest/chunk-32UHX7YY.js.map +7 -0
  27. package/dest/chunk-GSUKUCKV.js +260 -0
  28. package/dest/chunk-GSUKUCKV.js.map +7 -0
  29. package/dest/chunk-UP4KKUVA.js +304 -0
  30. package/dest/chunk-UP4KKUVA.js.map +7 -0
  31. package/dest/constants.d.ts +5 -1
  32. package/dest/constants.d.ts.map +1 -1
  33. package/dest/constants.js +9 -1
  34. package/dest/dispatcher_pool.d.ts +67 -0
  35. package/dest/dispatcher_pool.d.ts.map +1 -0
  36. package/dest/dispatcher_pool.js +286 -0
  37. package/dest/index.d.ts +51 -7
  38. package/dest/index.d.ts.map +1 -1
  39. package/dest/index.js +73 -157
  40. package/dest/metafile.json +38759 -0
  41. package/dest/msgpackr_fr_extension.d.ts +2 -0
  42. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  43. package/dest/msgpackr_fr_extension.js +21 -0
  44. package/dest/oracle/interfaces.d.ts +69 -30
  45. package/dest/oracle/interfaces.d.ts.map +1 -1
  46. package/dest/oracle/tagging_secret_strategy.d.ts +12 -0
  47. package/dest/oracle/tagging_secret_strategy.d.ts.map +1 -0
  48. package/dest/oracle/tagging_secret_strategy.js +12 -0
  49. package/dest/oracle/test-resolver/default_fixtures.d.ts +16 -0
  50. package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -0
  51. package/dest/oracle/test-resolver/default_fixtures.js +200 -0
  52. package/dest/oracle/test-resolver/index.d.ts +9 -0
  53. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  54. package/dest/oracle/test-resolver/index.js +32 -0
  55. package/dest/oracle/test-resolver/resolver.d.ts +48 -0
  56. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  57. package/dest/oracle/test-resolver/resolver.js +181 -0
  58. package/dest/oracle/txe_oracle_public_context.d.ts +38 -14
  59. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  60. package/dest/oracle/txe_oracle_public_context.js +61 -13
  61. package/dest/oracle/txe_oracle_registry.d.ts +172 -0
  62. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  63. package/dest/oracle/txe_oracle_registry.js +767 -0
  64. package/dest/oracle/txe_oracle_top_level_context.d.ts +69 -29
  65. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  66. package/dest/oracle/txe_oracle_top_level_context.js +585 -316
  67. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  68. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  69. package/dest/oracle/txe_oracle_version.js +14 -0
  70. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  71. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  72. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  73. package/dest/rpc_server.d.ts +14 -0
  74. package/dest/rpc_server.d.ts.map +1 -0
  75. package/dest/rpc_server.js +78 -0
  76. package/dest/rpc_translator.d.ts +115 -228
  77. package/dest/rpc_translator.d.ts.map +1 -1
  78. package/dest/rpc_translator.js +901 -624
  79. package/dest/server.bundle.js +3 -0
  80. package/dest/server.bundle.js.map +7 -0
  81. package/dest/state_machine/archiver.d.ts +6 -5
  82. package/dest/state_machine/archiver.d.ts.map +1 -1
  83. package/dest/state_machine/archiver.js +28 -20
  84. package/dest/state_machine/dummy_p2p_client.d.ts +22 -10
  85. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  86. package/dest/state_machine/dummy_p2p_client.js +38 -8
  87. package/dest/state_machine/global_variable_builder.d.ts +10 -6
  88. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  89. package/dest/state_machine/global_variable_builder.js +8 -5
  90. package/dest/state_machine/index.d.ts +11 -5
  91. package/dest/state_machine/index.d.ts.map +1 -1
  92. package/dest/state_machine/index.js +50 -10
  93. package/dest/state_machine/mock_epoch_cache.d.ts +16 -3
  94. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  95. package/dest/state_machine/mock_epoch_cache.js +29 -2
  96. package/dest/state_machine/synchronizer.d.ts +14 -6
  97. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  98. package/dest/state_machine/synchronizer.js +22 -9
  99. package/dest/txe_session.d.ts +90 -16
  100. package/dest/txe_session.d.ts.map +1 -1
  101. package/dest/txe_session.js +331 -67
  102. package/dest/utils/block_creation.d.ts +2 -2
  103. package/dest/utils/block_creation.d.ts.map +1 -1
  104. package/dest/utils/block_creation.js +2 -2
  105. package/dest/utils/encoding.d.ts +192 -0
  106. package/dest/utils/encoding.d.ts.map +1 -0
  107. package/dest/{util → utils}/encoding.js +7 -2
  108. package/dest/{util → utils}/expected_failure_error.d.ts +1 -1
  109. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  110. package/dest/utils/tx_effect_creation.d.ts +1 -1
  111. package/dest/utils/tx_effect_creation.d.ts.map +1 -1
  112. package/dest/utils/tx_effect_creation.js +0 -1
  113. package/dest/{util → utils}/txe_account_store.d.ts +1 -1
  114. package/dest/utils/txe_account_store.d.ts.map +1 -0
  115. package/dest/utils/txe_artifact_resolver.d.ts +37 -0
  116. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  117. package/dest/utils/txe_artifact_resolver.js +161 -0
  118. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  119. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  120. package/dest/utils/txe_public_contract_data_source.js +51 -0
  121. package/dest/worker.bundle.js +3 -0
  122. package/dest/worker.bundle.js.map +7 -0
  123. package/dest/worker.d.ts +2 -0
  124. package/dest/worker.d.ts.map +1 -0
  125. package/dest/worker.js +92 -0
  126. package/package.json +38 -21
  127. package/src/bin/check_txe_oracle_version.ts +67 -0
  128. package/src/bin/index.ts +11 -2
  129. package/src/bin/oracle_test_server.ts +51 -0
  130. package/src/constants.ts +11 -1
  131. package/src/dispatcher_pool.ts +317 -0
  132. package/src/index.ts +99 -190
  133. package/src/msgpackr_fr_extension.ts +23 -0
  134. package/src/oracle/interfaces.ts +75 -35
  135. package/src/oracle/tagging_secret_strategy.ts +25 -0
  136. package/src/oracle/test-resolver/default_fixtures.ts +271 -0
  137. package/src/oracle/test-resolver/index.ts +44 -0
  138. package/src/oracle/test-resolver/resolver.ts +245 -0
  139. package/src/oracle/txe_oracle_public_context.ts +74 -12
  140. package/src/oracle/txe_oracle_registry.ts +556 -0
  141. package/src/oracle/txe_oracle_top_level_context.ts +411 -137
  142. package/src/oracle/txe_oracle_version.ts +17 -0
  143. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  144. package/src/rpc_server.ts +87 -0
  145. package/src/rpc_translator.ts +1116 -1006
  146. package/src/state_machine/archiver.ts +41 -20
  147. package/src/state_machine/dummy_p2p_client.ts +62 -17
  148. package/src/state_machine/global_variable_builder.ts +12 -11
  149. package/src/state_machine/index.ts +63 -27
  150. package/src/state_machine/mock_epoch_cache.ts +38 -3
  151. package/src/state_machine/synchronizer.ts +31 -10
  152. package/src/txe_session.ts +570 -77
  153. package/src/utils/block_creation.ts +2 -1
  154. package/src/{util → utils}/encoding.ts +8 -2
  155. package/src/utils/tx_effect_creation.ts +0 -2
  156. package/src/utils/txe_artifact_resolver.ts +217 -0
  157. package/src/utils/txe_public_contract_data_source.ts +60 -0
  158. package/src/worker.ts +98 -0
  159. package/dest/util/encoding.d.ts +0 -720
  160. package/dest/util/encoding.d.ts.map +0 -1
  161. package/dest/util/expected_failure_error.d.ts.map +0 -1
  162. package/dest/util/txe_account_store.d.ts.map +0 -1
  163. package/dest/util/txe_contract_store.d.ts +0 -12
  164. package/dest/util/txe_contract_store.d.ts.map +0 -1
  165. package/dest/util/txe_contract_store.js +0 -22
  166. package/dest/util/txe_public_contract_data_source.d.ts +0 -21
  167. package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
  168. package/dest/util/txe_public_contract_data_source.js +0 -67
  169. package/src/util/txe_contract_store.ts +0 -36
  170. package/src/util/txe_public_contract_data_source.ts +0 -86
  171. /package/dest/{util → utils}/expected_failure_error.js +0 -0
  172. /package/dest/{util → utils}/txe_account_store.js +0 -0
  173. /package/src/{util → utils}/expected_failure_error.ts +0 -0
  174. /package/src/{util → utils}/txe_account_store.ts +0 -0
package/src/index.ts CHANGED
@@ -1,52 +1,35 @@
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';
4
- import {
5
- type ContractInstanceWithAddress,
6
- getContractInstanceFromInstantiationParams,
7
- } from '@aztec/aztec.js/contracts';
8
1
  import { Fr } from '@aztec/aztec.js/fields';
9
- import { PublicKeys, deriveKeys } from '@aztec/aztec.js/keys';
10
- import { createSafeJsonRpcServer } from '@aztec/foundation/json-rpc/server';
11
2
  import type { Logger } from '@aztec/foundation/log';
12
- import { type ProtocolContract, protocolContractNames } from '@aztec/protocol-contracts';
13
- import { BundledProtocolContractsProvider } from '@aztec/protocol-contracts/providers/bundle';
14
- import { computeArtifactHash } from '@aztec/stdlib/contract';
3
+ import { cloneEphemeralStoreFrom } from '@aztec/kv-store/lmdb-v2';
4
+ import type { ProtocolContractName } from '@aztec/protocol-contracts';
5
+ import { ContractStore } from '@aztec/pxe/client/lazy';
15
6
  import type { ApiSchemaFor } from '@aztec/stdlib/schemas';
16
7
  import { zodFor } from '@aztec/stdlib/schemas';
17
8
 
18
- import { createHash } from 'crypto';
19
- import { createReadStream } from 'fs';
20
- import { readFile, readdir } from 'fs/promises';
21
- import { join, parse } from 'path';
9
+ import { join } from 'path';
22
10
  import { z } from 'zod';
23
11
 
12
+ // Side-effect import: registers the msgpackr Fr extension for the bundled `Fr` class. Must
13
+ // be loaded before any `sendMessage` call. See msgpackr_fr_extension.ts for the why.
14
+ import './msgpackr_fr_extension.js';
24
15
  import { type TXEOracleFunctionName, TXESession } from './txe_session.js';
25
16
  import {
26
17
  type ForeignCallArgs,
27
18
  ForeignCallArgsSchema,
28
- type ForeignCallArray,
29
19
  type ForeignCallResult,
30
20
  ForeignCallResultSchema,
31
- type ForeignCallSingle,
32
- fromArray,
33
- fromSingle,
34
- toSingle,
35
- } from './util/encoding.js';
36
- import type { ContractArtifactWithHash } from './util/txe_contract_store.js';
21
+ } from './utils/encoding.js';
22
+ import { TXEArtifactResolver } from './utils/txe_artifact_resolver.js';
37
23
 
38
- const sessions = new Map<number, TXESession>();
24
+ export const TXE_REQUIRED_PROTOCOL_CONTRACTS: ProtocolContractName[] = [
25
+ 'ContractClassRegistry',
26
+ 'ContractInstanceRegistry',
27
+ 'FeeJuice',
28
+ ];
39
29
 
40
- /*
41
- * TXE typically has to load the same contract artifacts over and over again for multiple tests,
42
- * so we cache them here to avoid both loading them from disk repeatedly and computing their artifact hashes
43
- */
44
- const TXEArtifactsCache = new Map<
45
- string,
46
- { artifact: ContractArtifactWithHash; instance: ContractInstanceWithAddress }
47
- >();
30
+ const sessions = new Map<number, TXESession>();
48
31
 
49
- type TXEForeignCallInput = {
32
+ export type TXEForeignCallInput = {
50
33
  session_id: number;
51
34
  function: TXEOracleFunctionName;
52
35
  root_path: string;
@@ -54,10 +37,13 @@ type TXEForeignCallInput = {
54
37
  inputs: ForeignCallArgs;
55
38
  };
56
39
 
57
- const TXEForeignCallInputSchema = zodFor<TXEForeignCallInput>()(
40
+ export const TXEForeignCallInputSchema: z.ZodType<TXEForeignCallInput> = zodFor<TXEForeignCallInput>()(
58
41
  z.object({
42
+ // Nargo generates session_id as a u64, which may exceed Number.MAX_SAFE_INTEGER.
43
+ // Zod 4's `.int()` enforces the safe-integer bound, so we drop it here and only require
44
+ // the value to be a non-negative number (it is used solely as a Map key).
59
45
  // eslint-disable-next-line camelcase
60
- session_id: z.number().int().nonnegative(),
46
+ session_id: z.number().nonnegative(),
61
47
  function: z.string() as z.ZodType<TXEOracleFunctionName>,
62
48
  // eslint-disable-next-line camelcase
63
49
  root_path: z.string(),
@@ -67,178 +53,101 @@ const TXEForeignCallInputSchema = zodFor<TXEForeignCallInput>()(
67
53
  }),
68
54
  );
69
55
 
70
- class TXEDispatcher {
71
- private protocolContracts!: ProtocolContract[];
72
-
73
- constructor(private logger: Logger) {}
74
-
75
- private fastHashFile(path: string) {
76
- return new Promise(resolve => {
77
- const fd = createReadStream(path);
78
- const hash = createHash('sha1');
79
- hash.setEncoding('hex');
80
-
81
- fd.on('end', function () {
82
- hash.end();
83
- resolve(hash.read());
84
- });
85
-
86
- fd.pipe(hash);
87
- });
88
- }
89
-
90
- async #processDeployInputs({ inputs, root_path: rootPath, package_name: packageName }: TXEForeignCallInput) {
91
- const [contractPath, initializer] = inputs.slice(0, 2).map(input =>
92
- fromArray(input as ForeignCallArray)
93
- .map(char => String.fromCharCode(char.toNumber()))
94
- .join(''),
95
- );
96
-
97
- const decodedArgs = fromArray(inputs[3] as ForeignCallArray);
98
- const secret = fromSingle(inputs[4] as ForeignCallSingle);
99
- const publicKeys = secret.equals(Fr.ZERO) ? PublicKeys.default() : (await deriveKeys(secret)).publicKeys;
100
- const publicKeysHash = await publicKeys.hash();
101
-
102
- let artifactPath = '';
103
- const { dir: contractDirectory, base: contractFilename } = parse(contractPath);
104
- if (contractDirectory) {
105
- if (contractDirectory.includes('@')) {
106
- // We're deploying a contract that belongs in a workspace
107
- // env.deploy("../path/to/workspace/root@packageName/contractName")
108
- const [workspace, pkg] = contractDirectory.split('@');
109
- const targetPath = join(rootPath, workspace, '/target');
110
- this.logger.debug(`Looking for compiled artifact in workspace ${targetPath}`);
111
- artifactPath = join(targetPath, `${pkg}-${contractFilename}.json`);
112
- } else {
113
- // We're deploying a standalone external contract
114
- // env.deploy("../path/to/contract/root/contractName")
115
- const targetPath = join(rootPath, contractDirectory, '/target');
116
- this.logger.debug(`Looking for compiled artifact in ${targetPath}`);
117
- [artifactPath] = (await readdir(targetPath)).filter(file => file.endsWith(`-${contractFilename}.json`));
118
- }
119
- } else {
120
- // We're deploying a local contract
121
- // env.deploy("contractName")
122
- artifactPath = join(rootPath, './target', `${packageName}-${contractFilename}.json`);
123
- }
124
-
125
- const fileHash = await this.fastHashFile(artifactPath);
126
-
127
- const cacheKey = `${contractDirectory ?? ''}-${contractFilename}-${initializer}-${decodedArgs
128
- .map(arg => arg.toString())
129
- .join('-')}-${publicKeysHash}-${fileHash}`;
130
-
131
- let instance;
132
- let artifact: ContractArtifactWithHash;
133
-
134
- if (TXEArtifactsCache.has(cacheKey)) {
135
- this.logger.debug(`Using cached artifact for ${cacheKey}`);
136
- ({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
137
- } else {
138
- this.logger.debug(`Loading compiled artifact ${artifactPath}`);
139
- const artifactJSON = JSON.parse(await readFile(artifactPath, 'utf-8')) as NoirCompiledContract;
140
- const artifactWithoutHash = loadContractArtifact(artifactJSON);
141
- artifact = {
142
- ...artifactWithoutHash,
143
- // Artifact hash is *very* expensive to compute, so we do it here once
144
- // and the TXE contract data provider can cache it
145
- artifactHash: await computeArtifactHash(artifactWithoutHash),
146
- };
147
- this.logger.debug(
148
- `Deploy ${
149
- artifact.name
150
- } with initializer ${initializer}(${decodedArgs}) and public keys hash ${publicKeysHash.toString()}`,
151
- );
152
- instance = await getContractInstanceFromInstantiationParams(artifact, {
153
- constructorArgs: decodedArgs,
154
- skipArgsDecoding: true,
155
- salt: Fr.ONE,
156
- publicKeys,
157
- constructorArtifact: initializer ? initializer : undefined,
158
- deployer: AztecAddress.ZERO,
159
- });
160
- TXEArtifactsCache.set(cacheKey, { artifact, instance });
161
- }
56
+ export interface TXEDispatcherOptions {
57
+ /**
58
+ * Path to an LMDB directory holding the required protocol contracts (see
59
+ * {@link TXE_REQUIRED_PROTOCOL_CONTRACTS}) and the SchnorrAccount artifact. When set, the
60
+ * dispatcher clones this directory into a fresh tmpdir on first use instead of registering
61
+ * the contracts itself.
62
+ */
63
+ contractStoreSourceDir: string;
64
+ /**
65
+ * Class id (hex) of the SchnorrAccount artifact pre-registered in the shared LMDB. The
66
+ * {@link TXEArtifactResolver} looks the artifact up from the cloned store via this class id
67
+ * instead of recomputing it via `getSchnorrAccountContractArtifact()` + `computeArtifactHash()`.
68
+ */
69
+ schnorrClassId: string;
70
+ }
162
71
 
163
- inputs.splice(0, 1, artifact, instance, toSingle(secret));
72
+ export class TXEDispatcher {
73
+ private contractStore!: ContractStore;
74
+ private artifactResolver!: TXEArtifactResolver;
75
+ private readonly contractStoreSourceDir: string;
76
+ private readonly schnorrClassId: Fr;
77
+
78
+ constructor(
79
+ private logger: Logger,
80
+ opts: TXEDispatcherOptions,
81
+ ) {
82
+ this.contractStoreSourceDir = opts.contractStoreSourceDir;
83
+ this.schnorrClassId = Fr.fromString(opts.schnorrClassId);
164
84
  }
165
85
 
166
- async #processAddAccountInputs({ inputs }: TXEForeignCallInput) {
167
- const secret = fromSingle(inputs[0] as ForeignCallSingle);
168
-
169
- const cacheKey = `SchnorrAccountContract-${secret}`;
170
-
171
- let artifact: ContractArtifactWithHash;
172
- let instance;
173
-
174
- if (TXEArtifactsCache.has(cacheKey)) {
175
- this.logger.debug(`Using cached artifact for ${cacheKey}`);
176
- ({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
177
- } else {
178
- const keys = await deriveKeys(secret);
179
- const args = [keys.publicKeys.masterIncomingViewingPublicKey.x, keys.publicKeys.masterIncomingViewingPublicKey.y];
180
- artifact = {
181
- ...SchnorrAccountContractArtifact,
182
- // Artifact hash is *very* expensive to compute, so we do it here once
183
- // and the TXE contract data provider can cache it
184
- artifactHash: await computeArtifactHash(SchnorrAccountContractArtifact),
185
- };
186
- instance = await getContractInstanceFromInstantiationParams(artifact, {
187
- constructorArgs: args,
188
- skipArgsDecoding: true,
189
- salt: Fr.ONE,
190
- publicKeys: keys.publicKeys,
191
- constructorArtifact: 'constructor',
192
- deployer: AztecAddress.ZERO,
193
- });
194
- TXEArtifactsCache.set(cacheKey, { artifact, instance });
86
+ /**
87
+ * Clones the pre-populated LMDB at `contractStoreSourceDir` into a fresh per-instance tmpdir
88
+ * on first use, so this dispatcher has a writable store already containing the required
89
+ * protocol contracts + SchnorrAccount. Idempotent — subsequent calls are no-ops.
90
+ */
91
+ private async warmUp(): Promise<void> {
92
+ if (this.contractStore) {
93
+ return;
195
94
  }
196
-
197
- inputs.splice(0, 0, artifact, instance);
95
+ const t0 = Date.now();
96
+ const kvStore = await cloneEphemeralStoreFrom(
97
+ join(this.contractStoreSourceDir, 'data.mdb'),
98
+ 'txe-contracts',
99
+ undefined,
100
+ 2,
101
+ );
102
+ this.contractStore = new ContractStore(kvStore);
103
+ this.artifactResolver = new TXEArtifactResolver(this.contractStore, this.schnorrClassId);
104
+ this.logger.debug('Cloned shared protocol-contracts store', { totalMs: Date.now() - t0 });
198
105
  }
199
106
 
200
107
  // eslint-disable-next-line camelcase
201
108
  async resolve_foreign_call(callData: TXEForeignCallInput): Promise<ForeignCallResult> {
202
- const { session_id: sessionId, function: functionName, inputs } = callData;
109
+ const {
110
+ session_id: sessionId,
111
+ function: functionName,
112
+ inputs,
113
+ root_path: rootPath,
114
+ package_name: packageName,
115
+ } = callData;
203
116
  this.logger.debug(`Calling ${functionName} on session ${sessionId}`);
204
117
 
205
118
  if (!sessions.has(sessionId)) {
206
119
  this.logger.debug(`Creating new session ${sessionId}`);
207
- if (!this.protocolContracts) {
208
- this.protocolContracts = await Promise.all(
209
- protocolContractNames.map(name => new BundledProtocolContractsProvider().getProtocolContractArtifact(name)),
210
- );
211
- }
212
- sessions.set(sessionId, await TXESession.init(this.protocolContracts));
213
- }
214
-
215
- switch (functionName) {
216
- case 'txeDeploy': {
217
- await this.#processDeployInputs(callData);
218
- break;
219
- }
220
- case 'txeAddAccount': {
221
- await this.#processAddAccountInputs(callData);
222
- break;
223
- }
120
+ await this.warmUp();
121
+ sessions.set(sessionId, await TXESession.init(this.contractStore, this.artifactResolver, rootPath, packageName));
224
122
  }
225
123
 
226
124
  return await sessions.get(sessionId)!.processFunction(functionName, inputs);
227
125
  }
126
+
127
+ /**
128
+ * Releases a session and its resources (per-session LMDB + `NativeWorldStateService`).
129
+ * Called by the dispatcher pool when nargo closes its TCP connection for a test (see
130
+ * `rpc_server.ts`'s socket tracker). No-op if the session was never created — that happens
131
+ * when nargo opens a connection but errors before sending a request.
132
+ */
133
+ async disposeSession(sessionId: number): Promise<void> {
134
+ const session = sessions.get(sessionId);
135
+ if (!session) {
136
+ return;
137
+ }
138
+ sessions.delete(sessionId);
139
+ await session.dispose();
140
+ }
141
+ }
142
+
143
+ /** Diagnostic-only: number of sessions currently held by this worker. */
144
+ export function activeSessionCount(): number {
145
+ return sessions.size;
228
146
  }
229
147
 
230
- const TXEDispatcherApiSchema: ApiSchemaFor<TXEDispatcher> = {
148
+ export const TXEDispatcherApiSchema: ApiSchemaFor<TXEDispatcher> = {
231
149
  // eslint-disable-next-line camelcase
232
- resolve_foreign_call: z.function().args(TXEForeignCallInputSchema).returns(ForeignCallResultSchema),
150
+ resolve_foreign_call: z.function({ input: z.tuple([TXEForeignCallInputSchema]), output: ForeignCallResultSchema }),
151
+ // disposeSession is invoked over IPC from the worker, not via RPC; required by ApiSchemaFor.
152
+ disposeSession: z.function({ input: z.tuple([z.number().nonnegative()]), output: z.void() }),
233
153
  };
234
-
235
- /**
236
- * Creates an RPC server that forwards calls to the TXE.
237
- * @param logger - Logger to output to
238
- * @returns A TXE RPC server.
239
- */
240
- export function createTXERpcServer(logger: Logger) {
241
- return createSafeJsonRpcServer(new TXEDispatcher(logger), TXEDispatcherApiSchema, {
242
- http200OnError: true,
243
- });
244
- }
@@ -0,0 +1,23 @@
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
+
3
+ import { addExtension } from 'msgpackr';
4
+
5
+ // `@aztec/native/msgpack_channel` registers a msgpackr extension that packs `Fr` instances to
6
+ // their raw 32-byte buffer for the C++ world-state side to deserialize. Because `@aztec/native`
7
+ // is externalized in TXE's esbuild config (it loads a `.node` binary that can't be bundled),
8
+ // the `Fr` class the extension is keyed on belongs to the *external* `@aztec/foundation`
9
+ // module instance — a different class identity than the `Fr` bundled into the TXE worker /
10
+ // bin. msgpackr's extension match uses `instanceof`, so bundled `Fr` instances slip through
11
+ // and msgpackr falls back to `Fr.toJSON()` (returns `Fr.toString()` — a `0x...` hex string).
12
+ // The C++ side then sees a string where a 32-byte binary was expected and throws
13
+ // `msgpack::type_error` whose `what()` is literally `"std::bad_cast"`.
14
+ //
15
+ // Fix: register the same extension under the BUNDLED `Fr` class identity. msgpackr's extension
16
+ // table holds an entry per `Class`, so both Fr classes now resolve to the same `write` callback
17
+ // and produce the same wire format. Imported as a side-effect from `./index.js` so both the
18
+ // worker (via `./worker.ts`) and the main-thread RPC server (via `./rpc_server.ts`) get the
19
+ // registration before any `sendMessage` runs.
20
+ addExtension({
21
+ Class: Fr,
22
+ write: (fr: Fr) => fr.toBuffer(),
23
+ });
@@ -1,11 +1,14 @@
1
- import type { ContractArtifact } from '@aztec/aztec.js/abi';
2
1
  import { CompleteAddress } from '@aztec/aztec.js/addresses';
3
- import type { ContractInstanceWithAddress } from '@aztec/aztec.js/contracts';
4
2
  import { TxHash } from '@aztec/aztec.js/tx';
5
3
  import { BlockNumber } from '@aztec/foundation/branded-types';
6
4
  import type { Fr } from '@aztec/foundation/curves/bn254';
5
+ import type { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { TaggingSecretStrategy } from '@aztec/pxe/server';
7
+ import type { Option } from '@aztec/pxe/simulator';
7
8
  import type { EventSelector, FunctionSelector } from '@aztec/stdlib/abi';
8
9
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
10
+ import type { GasSettings } from '@aztec/stdlib/gas';
11
+ import type { PrivateLog } from '@aztec/stdlib/logs';
9
12
  import type { UInt64 } from '@aztec/stdlib/types';
10
13
 
11
14
  // These interfaces complement the ones defined in PXE, and combined with those contain the full list of oracles used by
@@ -24,18 +27,27 @@ import type { UInt64 } from '@aztec/stdlib/types';
24
27
  export interface IAvmExecutionOracle {
25
28
  isAvm: true;
26
29
 
27
- avmOpcodeAddress(): Promise<AztecAddress>;
28
- avmOpcodeSender(): Promise<AztecAddress>;
29
- avmOpcodeBlockNumber(): Promise<BlockNumber>;
30
- avmOpcodeTimestamp(): Promise<bigint>;
31
- avmOpcodeIsStaticCall(): Promise<boolean>;
32
- avmOpcodeChainId(): Promise<Fr>;
33
- avmOpcodeVersion(): Promise<Fr>;
34
- avmOpcodeEmitNullifier(nullifier: Fr): Promise<void>;
35
- avmOpcodeEmitNoteHash(noteHash: Fr): Promise<void>;
36
- avmOpcodeNullifierExists(siloedNullifier: Fr): Promise<boolean>;
37
- avmOpcodeStorageWrite(slot: Fr, value: Fr): Promise<void>;
38
- avmOpcodeStorageRead(slot: Fr, contractAddress: AztecAddress): Promise<Fr>;
30
+ address(): Promise<AztecAddress>;
31
+ sender(): Promise<AztecAddress>;
32
+ blockNumber(): Promise<BlockNumber>;
33
+ timestamp(): Promise<bigint>;
34
+ isStaticCall(): Promise<boolean>;
35
+ chainId(): Promise<Fr>;
36
+ version(): Promise<Fr>;
37
+ emitNullifier(nullifier: Fr): Promise<void>;
38
+ emitNoteHash(noteHash: Fr): Promise<void>;
39
+ nullifierExists(siloedNullifier: Fr): Promise<boolean>;
40
+ storageWrite(slot: Fr, value: Fr): Promise<void>;
41
+ storageRead(slot: Fr, contractAddress: AztecAddress): Promise<Fr>;
42
+ getContractInstanceDeployer(address: AztecAddress): Promise<{ member: Fr; exists: boolean }[]>;
43
+ getContractInstanceClassId(address: AztecAddress): Promise<{ member: Fr; exists: boolean }[]>;
44
+ getContractInstanceInitializationHash(address: AztecAddress): Promise<{ member: Fr; exists: boolean }[]>;
45
+ getContractInstanceImmutablesHash(address: AztecAddress): Promise<{ member: Fr; exists: boolean }[]>;
46
+ returndataSize(): Promise<number>;
47
+ returndataCopy(rdOffset: number, copySize: number): Promise<Fr[]>;
48
+ call(l2Gas: number, daGas: number, address: AztecAddress, argsLength: number, args: Fr[]): Promise<void>;
49
+ staticCall(l2Gas: number, daGas: number, address: AztecAddress, argsLength: number, args: Fr[]): Promise<void>;
50
+ successCopy(): Promise<boolean>;
39
51
  }
40
52
 
41
53
  /**
@@ -44,43 +56,71 @@ export interface IAvmExecutionOracle {
44
56
  export interface ITxeExecutionOracle {
45
57
  isTxe: true;
46
58
 
47
- txeGetDefaultAddress(): AztecAddress;
48
- txeGetNextBlockNumber(): Promise<BlockNumber>;
49
- txeGetNextBlockTimestamp(): Promise<UInt64>;
50
- txeAdvanceBlocksBy(blocks: number): Promise<void>;
51
- txeAdvanceTimestampBy(duration: UInt64): void;
52
- txeDeploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, foreignSecret: Fr): Promise<void>;
53
- txeCreateAccount(secret: Fr): Promise<CompleteAddress>;
54
- txeAddAccount(
55
- artifact: ContractArtifact,
56
- instance: ContractInstanceWithAddress,
59
+ getDefaultAddress(): AztecAddress;
60
+ getNextBlockNumber(): Promise<BlockNumber>;
61
+ getNextBlockTimestamp(): Promise<UInt64>;
62
+ advanceBlocksBy(blocks: number): Promise<void>;
63
+ advanceTimestampBy(duration: UInt64): void;
64
+ deploy(
65
+ contractPath: string,
66
+ initializer: string,
67
+ args: Fr[],
57
68
  secret: Fr,
58
- ): Promise<CompleteAddress>;
59
- txeAddAuthWitness(address: AztecAddress, messageHash: Fr): Promise<void>;
60
- txeGetLastBlockTimestamp(): Promise<bigint>;
61
- txeGetLastTxEffects(): Promise<{
69
+ salt: Fr,
70
+ deployer: AztecAddress,
71
+ ): Promise<Fr[]>;
72
+ createAccount(secret: Fr, partialAddress: Fr): Promise<CompleteAddress>;
73
+ addAccount(secret: Fr): Promise<CompleteAddress>;
74
+ addAuthWitness(address: AztecAddress, messageHash: Fr): Promise<void>;
75
+ sendL1ToL2Message(content: Fr, secretHash: Fr, sender: EthAddress, recipient: AztecAddress): Promise<Fr>;
76
+ /**
77
+ * Configures the tagging secret strategy the test's simulated wallet resolves for each delivery mode. A `none`
78
+ * clears that mode, so it falls back to the default strategy (or, when both modes end up unset, to no hook at all).
79
+ */
80
+ setTaggingSecretStrategies(
81
+ unconstrainedStrategy: Option<TaggingSecretStrategy>,
82
+ constrainedStrategy: Option<TaggingSecretStrategy>,
83
+ ): void;
84
+ /**
85
+ * Configures whether the test's simulated wallet authorizes every cross-contract utility call target.
86
+ */
87
+ setAuthorizeAllUtilityCallTargets(authorizeAll: boolean): void;
88
+ getLastBlockTimestamp(): Promise<bigint>;
89
+ getLastTxEffects(): Promise<{
62
90
  txHash: TxHash;
63
91
  noteHashes: Fr[];
64
92
  nullifiers: Fr[];
93
+ privateLogs: PrivateLog[];
65
94
  }>;
66
- txeGetPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise<Fr[][]>;
67
- txePrivateCallNewFlow(
68
- from: AztecAddress,
95
+ getPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise<Fr[][]>;
96
+ privateCallNewFlow(
97
+ from: AztecAddress | undefined,
69
98
  targetContractAddress: AztecAddress,
70
99
  functionSelector: FunctionSelector,
71
100
  args: Fr[],
72
101
  argsHash: Fr,
73
102
  isStaticCall: boolean,
74
- ): Promise<Fr[]>;
75
- txeSimulateUtilityFunction(
103
+ additionalScopes: AztecAddress[],
104
+ jobId: string,
105
+ authorizedUtilityCallTargets: AztecAddress[],
106
+ gasSettings: GasSettings,
107
+ ): Promise<{ returnValues: Fr[]; offchainEffects: Fr[][] }>;
108
+ executeUtilityFunction(
109
+ from: AztecAddress | undefined,
76
110
  targetContractAddress: AztecAddress,
77
111
  functionSelector: FunctionSelector,
78
112
  args: Fr[],
113
+ jobId: string,
114
+ authorizedUtilityCallTargets: AztecAddress[],
79
115
  ): Promise<Fr[]>;
80
- txePublicCallNewFlow(
81
- from: AztecAddress,
116
+ publicCallNewFlow(
117
+ from: AztecAddress | undefined,
82
118
  targetContractAddress: AztecAddress,
83
119
  calldata: Fr[],
84
120
  isStaticCall: boolean,
121
+ gasSettings: GasSettings,
85
122
  ): Promise<Fr[]>;
123
+ // TODO(F-335): Drop this from here as it's not a real oracle handler - it's only called from
124
+ // RPCTranslator::txeGetPrivateEvents and never from Noir.
125
+ syncContractNonOracleMethod(contractAddress: AztecAddress, scope: AztecAddress, jobId: string): Promise<void>;
86
126
  }
@@ -0,0 +1,25 @@
1
+ import {
2
+ DEFAULT_TAGGING_SECRET_STRATEGY,
3
+ type ResolveTaggingSecretStrategy,
4
+ type TaggingSecretStrategy,
5
+ } from '@aztec/pxe/server';
6
+ import type { AppTaggingSecretKind } from '@aztec/stdlib/logs';
7
+
8
+ /** The tagging secret strategies a TXE test has configured, keyed by delivery mode. Absence means "not configured". */
9
+ export type TXETaggingSecretStrategies = Map<AppTaggingSecretKind, TaggingSecretStrategy>;
10
+
11
+ /**
12
+ * Builds the `resolveTaggingSecretStrategy` hook backing the `aztec_txe_setTaggingSecretStrategies` oracle. Returns
13
+ * `undefined` when no strategy is configured, so PXE's own no-hook default path is exercised. When at least one mode
14
+ * is configured, modes without an entry resolve to {@link DEFAULT_TAGGING_SECRET_STRATEGY}, matching what PXE would
15
+ * apply without a hook.
16
+ */
17
+ export function makeResolveTaggingSecretStrategyHook(
18
+ strategies: TXETaggingSecretStrategies,
19
+ ): ResolveTaggingSecretStrategy | undefined {
20
+ if (strategies.size === 0) {
21
+ return undefined;
22
+ }
23
+
24
+ return ({ deliveryMode }) => Promise.resolve(strategies.get(deliveryMode) ?? DEFAULT_TAGGING_SECRET_STRATEGY);
25
+ }