@aztec/aztec 0.0.1-commit.8afd444 → 0.0.1-commit.9117c5f5a

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 (81) hide show
  1. package/dest/bin/index.js +5 -1
  2. package/dest/cli/admin_api_key_store.d.ts +45 -0
  3. package/dest/cli/admin_api_key_store.d.ts.map +1 -0
  4. package/dest/cli/admin_api_key_store.js +98 -0
  5. package/dest/cli/aztec_start_action.d.ts +1 -1
  6. package/dest/cli/aztec_start_action.d.ts.map +1 -1
  7. package/dest/cli/aztec_start_action.js +46 -10
  8. package/dest/cli/aztec_start_options.d.ts +1 -1
  9. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  10. package/dest/cli/aztec_start_options.js +23 -6
  11. package/dest/cli/cli.d.ts +1 -1
  12. package/dest/cli/cli.d.ts.map +1 -1
  13. package/dest/cli/cli.js +0 -1
  14. package/dest/cli/cmds/compile.d.ts +4 -0
  15. package/dest/cli/cmds/compile.d.ts.map +1 -0
  16. package/dest/cli/cmds/compile.js +160 -0
  17. package/dest/cli/cmds/profile.d.ts +4 -0
  18. package/dest/cli/cmds/profile.d.ts.map +1 -0
  19. package/dest/cli/cmds/profile.js +8 -0
  20. package/dest/cli/cmds/profile_flamegraph.d.ts +4 -0
  21. package/dest/cli/cmds/profile_flamegraph.d.ts.map +1 -0
  22. package/dest/cli/cmds/profile_flamegraph.js +51 -0
  23. package/dest/cli/cmds/profile_gates.d.ts +4 -0
  24. package/dest/cli/cmds/profile_gates.d.ts.map +1 -0
  25. package/dest/cli/cmds/profile_gates.js +57 -0
  26. package/dest/cli/cmds/profile_utils.d.ts +18 -0
  27. package/dest/cli/cmds/profile_utils.d.ts.map +1 -0
  28. package/dest/cli/cmds/profile_utils.js +50 -0
  29. package/dest/cli/cmds/start_bot.d.ts +3 -3
  30. package/dest/cli/cmds/start_bot.d.ts.map +1 -1
  31. package/dest/cli/cmds/start_bot.js +9 -5
  32. package/dest/cli/cmds/start_node.d.ts +1 -1
  33. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  34. package/dest/cli/cmds/start_node.js +62 -10
  35. package/dest/cli/cmds/utils/artifacts.d.ts +21 -0
  36. package/dest/cli/cmds/utils/artifacts.d.ts.map +1 -0
  37. package/dest/cli/cmds/utils/artifacts.js +24 -0
  38. package/dest/cli/cmds/utils/spawn.d.ts +3 -0
  39. package/dest/cli/cmds/utils/spawn.d.ts.map +1 -0
  40. package/dest/cli/cmds/utils/spawn.js +16 -0
  41. package/dest/cli/util.d.ts +5 -14
  42. package/dest/cli/util.d.ts.map +1 -1
  43. package/dest/cli/util.js +13 -8
  44. package/dest/examples/token.js +2 -2
  45. package/dest/local-network/local-network.d.ts +3 -1
  46. package/dest/local-network/local-network.d.ts.map +1 -1
  47. package/dest/local-network/local-network.js +32 -13
  48. package/dest/testing/anvil_test_watcher.d.ts +9 -1
  49. package/dest/testing/anvil_test_watcher.d.ts.map +1 -1
  50. package/dest/testing/anvil_test_watcher.js +52 -15
  51. package/package.json +34 -34
  52. package/scripts/aztec.sh +8 -5
  53. package/scripts/init.sh +23 -13
  54. package/scripts/new.sh +17 -16
  55. package/scripts/setup_workspace.sh +124 -0
  56. package/src/bin/index.ts +5 -1
  57. package/src/cli/admin_api_key_store.ts +128 -0
  58. package/src/cli/aztec_start_action.ts +50 -6
  59. package/src/cli/aztec_start_options.ts +25 -5
  60. package/src/cli/cli.ts +0 -1
  61. package/src/cli/cmds/compile.ts +184 -0
  62. package/src/cli/cmds/profile.ts +25 -0
  63. package/src/cli/cmds/profile_flamegraph.ts +63 -0
  64. package/src/cli/cmds/profile_gates.ts +67 -0
  65. package/src/cli/cmds/profile_utils.ts +58 -0
  66. package/src/cli/cmds/start_bot.ts +8 -5
  67. package/src/cli/cmds/start_node.ts +51 -9
  68. package/src/cli/cmds/utils/artifacts.ts +44 -0
  69. package/src/cli/cmds/utils/spawn.ts +16 -0
  70. package/src/cli/util.ts +16 -21
  71. package/src/examples/token.ts +2 -2
  72. package/src/local-network/local-network.ts +41 -14
  73. package/src/testing/anvil_test_watcher.ts +59 -15
  74. package/dest/cli/cmds/start_prover_node.d.ts +0 -7
  75. package/dest/cli/cmds/start_prover_node.d.ts.map +0 -1
  76. package/dest/cli/cmds/start_prover_node.js +0 -108
  77. package/scripts/compile.sh +0 -44
  78. package/scripts/extract_function.js +0 -47
  79. package/scripts/flamegraph.sh +0 -59
  80. package/scripts/setup_project.sh +0 -31
  81. package/src/cli/cmds/start_prover_node.ts +0 -124
@@ -0,0 +1,128 @@
1
+ import { randomBytes } from '@aztec/foundation/crypto/random';
2
+ import { sha256Hash } from '@aztec/foundation/json-rpc/server';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+
5
+ import { promises as fs } from 'fs';
6
+ import { join } from 'path';
7
+
8
+ /** Subdirectory under dataDirectory for admin API key storage. */
9
+ const ADMIN_STORE_DIR = 'admin';
10
+ const HASH_FILE_NAME = 'api_key_hash';
11
+
12
+ /**
13
+ * Result of resolving the admin API key.
14
+ * Contains the SHA-256 hex hash of the API key to be used by the auth middleware,
15
+ * and optionally the raw key when newly generated (so the caller can display it).
16
+ */
17
+ export interface AdminApiKeyResolution {
18
+ /** The SHA-256 hash of the API key. */
19
+ apiKeyHash: Buffer;
20
+ /**
21
+ * The raw API key, only present when a new key was generated during this call.
22
+ * The caller MUST display this to the operator — it will not be stored or returned again.
23
+ */
24
+ rawKey?: string;
25
+ }
26
+
27
+ export interface ResolveAdminApiKeyOptions {
28
+ /** SHA-256 hex hash of a pre-generated API key. When set, the node uses this hash directly. */
29
+ adminApiKeyHash?: string;
30
+ /** If true, disable admin API key auth entirely. */
31
+ disableAdminApiKey?: boolean;
32
+ /** If true, force-generate a new key even if one is already persisted. */
33
+ resetAdminApiKey?: boolean;
34
+ /** Root data directory for persistent storage. */
35
+ dataDirectory?: string;
36
+ }
37
+
38
+ /**
39
+ * Resolves the admin API key for the admin RPC endpoint.
40
+ *
41
+ * Strategy:
42
+ * 1. If opt-out flag is set (`disableAdminApiKey`), return undefined (no auth).
43
+ * 2. If a pre-generated hash is provided (`adminApiKeyHash`), use it directly.
44
+ * 3. If a data directory exists, look for a persisted hash file
45
+ * at `<dataDirectory>/admin/api_key_hash`:
46
+ * - If `resetAdminApiKey` is set, skip loading and force-generate a new key.
47
+ * - Found: use the stored hash (operator already saved the key from first run).
48
+ * - Not found: auto-generate a random key, display it once, persist the hash.
49
+ * 3. If no data directory: generate a random key
50
+ * each run and display it (cannot persist).
51
+ *
52
+ * @param options - The options for resolving the admin API key.
53
+ * @param log - Logger for outputting the key and status messages.
54
+ * @returns The resolved API key hash, or undefined if auth is disabled.
55
+ */
56
+ export async function resolveAdminApiKey(
57
+ options: ResolveAdminApiKeyOptions,
58
+ log: Logger,
59
+ ): Promise<AdminApiKeyResolution | undefined> {
60
+ // Operator explicitly opted out of admin auth
61
+ if (options.disableAdminApiKey) {
62
+ log.warn('Admin API key authentication is DISABLED (--disable-admin-api-key / AZTEC_DISABLE_ADMIN_API_KEY)');
63
+ return undefined;
64
+ }
65
+
66
+ // Operator provided a pre-generated hash (e.g. via AZTEC_ADMIN_API_KEY_HASH env var)
67
+ if (options.adminApiKeyHash) {
68
+ const hex = options.adminApiKeyHash.trim();
69
+ if (hex.length !== 64 || !/^[0-9a-f]{64}$/.test(hex)) {
70
+ throw new Error(`Invalid admin API key hash: expected 64-char hex string, got "${hex}"`);
71
+ }
72
+ log.info('Admin API key authentication enabled (using pre-configured key hash)');
73
+ return { apiKeyHash: Buffer.from(hex, 'hex') };
74
+ }
75
+
76
+ // Persistent storage available, load or generate key
77
+ if (options.dataDirectory) {
78
+ const adminDir = join(options.dataDirectory, ADMIN_STORE_DIR);
79
+ const hashFilePath = join(adminDir, HASH_FILE_NAME);
80
+
81
+ // Unless a reset is forced, try to load the existing hash from disk
82
+ if (!options.resetAdminApiKey) {
83
+ try {
84
+ const storedHash = (await fs.readFile(hashFilePath, 'utf-8')).trim();
85
+ if (storedHash.length === 64) {
86
+ log.info('Admin API key authentication enabled (loaded stored key hash from disk)');
87
+ return { apiKeyHash: Buffer.from(storedHash, 'hex') };
88
+ }
89
+ log.warn(`Invalid stored admin API key hash at ${hashFilePath}, regenerating...`);
90
+ } catch (err: any) {
91
+ if (err.code !== 'ENOENT') {
92
+ log.warn(`Failed to read admin API key hash from ${hashFilePath}: ${err.message}`);
93
+ }
94
+ // File doesn't exist — fall through to generate
95
+ }
96
+ } else {
97
+ log.warn('Admin API key reset requested — generating a new key');
98
+ }
99
+
100
+ // Generate a new key, persist the hash, and return the raw key for the caller to display
101
+ const { rawKey, hash } = generateApiKey();
102
+ await fs.mkdir(adminDir, { recursive: true });
103
+ await fs.writeFile(hashFilePath, hash.toString('hex'), 'utf-8');
104
+ // Set restrictive permissions (owner read/write only)
105
+ await fs.chmod(hashFilePath, 0o600);
106
+
107
+ log.info('Admin API key authentication enabled (new key generated and hash persisted to disk)');
108
+ return { apiKeyHash: hash, rawKey };
109
+ }
110
+
111
+ // No data directory, generate a temporary key per session
112
+ const { rawKey, hash } = generateApiKey();
113
+
114
+ log.warn('No data directory configured — admin API key cannot be persisted.');
115
+ log.warn('A temporary key has been generated for this session only.');
116
+
117
+ return { apiKeyHash: hash, rawKey };
118
+ }
119
+
120
+ /**
121
+ * Generates a cryptographically random API key and its SHA-256 hash.
122
+ * @returns The raw key (hex string) and its SHA-256 hash as a Buffer.
123
+ */
124
+ function generateApiKey(): { rawKey: string; hash: Buffer } {
125
+ const rawKey = randomBytes(32).toString('hex');
126
+ const hash = sha256Hash(rawKey);
127
+ return { rawKey, hash };
128
+ }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  type NamespacedApiHandlers,
3
3
  createNamespacedSafeJsonRpcServer,
4
+ getApiKeyAuthMiddleware,
4
5
  startHttpRpcServer,
5
6
  } from '@aztec/foundation/json-rpc/server';
6
7
  import type { LogFn, Logger } from '@aztec/foundation/log';
@@ -11,6 +12,7 @@ import { getOtelJsonRpcPropagationMiddleware } from '@aztec/telemetry-client';
11
12
 
12
13
  import { createLocalNetwork } from '../local-network/index.js';
13
14
  import { github, splash } from '../splash.js';
15
+ import { resolveAdminApiKey } from './admin_api_key_store.js';
14
16
  import { getCliVersion } from './release_version.js';
15
17
  import { extractNamespacedOptions, installSignalHandlers } from './util.js';
16
18
  import { getVersions } from './versioning.js';
@@ -35,11 +37,11 @@ export async function aztecStart(options: any, userLog: LogFn, debugLogger: Logg
35
37
  l1RpcUrls: options.l1RpcUrls,
36
38
  testAccounts: localNetwork.testAccounts,
37
39
  realProofs: false,
38
- // Setting the epoch duration to 4 by default for local network. This allows the epoch to be "proven" faster, so
40
+ // Setting the epoch duration to 2 by default for local network. This allows the epoch to be "proven" faster, so
39
41
  // the users can consume out hash without having to wait for a long time.
40
42
  // Note: We are not proving anything in the local network (realProofs == false). But in `createLocalNetwork`,
41
43
  // the EpochTestSettler will set the out hash to the outbox when an epoch is complete.
42
- aztecEpochDuration: 4,
44
+ aztecEpochDuration: 2,
43
45
  },
44
46
  userLog,
45
47
  );
@@ -48,15 +50,17 @@ export async function aztecStart(options: any, userLog: LogFn, debugLogger: Logg
48
50
  signalHandlers.push(stop);
49
51
  services.node = [node, AztecNodeApiSchema];
50
52
  } else {
53
+ // Route --prover-node through startNode
54
+ if (options.proverNode && !options.node) {
55
+ options.node = true;
56
+ }
57
+
51
58
  if (options.node) {
52
59
  const { startNode } = await import('./cmds/start_node.js');
53
60
  ({ config } = await startNode(options, signalHandlers, services, adminServices, userLog));
54
61
  } else if (options.bot) {
55
62
  const { startBot } = await import('./cmds/start_bot.js');
56
63
  await startBot(options, signalHandlers, services, userLog);
57
- } else if (options.proverNode) {
58
- const { startProverNode } = await import('./cmds/start_prover_node.js');
59
- ({ config } = await startProverNode(options, signalHandlers, services, userLog));
60
64
  } else if (options.archiver) {
61
65
  const { startArchiver } = await import('./cmds/start_archiver.js');
62
66
  ({ config } = await startArchiver(options, signalHandlers, services));
@@ -99,14 +103,54 @@ export async function aztecStart(options: any, userLog: LogFn, debugLogger: Logg
99
103
 
100
104
  // If there are any admin services, start a separate JSON-RPC server for them
101
105
  if (Object.entries(adminServices).length > 0) {
106
+ const adminMiddlewares = [getOtelJsonRpcPropagationMiddleware(), getVersioningMiddleware(versions)];
107
+
108
+ // Resolve the admin API key (auto-generated and persisted, or opt-out)
109
+ const apiKeyResolution = await resolveAdminApiKey(
110
+ {
111
+ adminApiKeyHash: options.adminApiKeyHash,
112
+ disableAdminApiKey: options.disableAdminApiKey,
113
+ resetAdminApiKey: options.resetAdminApiKey,
114
+ dataDirectory: options.dataDirectory,
115
+ },
116
+ debugLogger,
117
+ );
118
+ if (apiKeyResolution) {
119
+ adminMiddlewares.unshift(getApiKeyAuthMiddleware(apiKeyResolution.apiKeyHash));
120
+ } else {
121
+ debugLogger.warn('No admin API key set — admin endpoint is unauthenticated');
122
+ }
123
+
102
124
  const rpcServer = createNamespacedSafeJsonRpcServer(adminServices, {
103
125
  http200OnError: false,
104
126
  log: debugLogger,
105
- middlewares: [getOtelJsonRpcPropagationMiddleware(), getVersioningMiddleware(versions)],
127
+ middlewares: adminMiddlewares,
106
128
  maxBatchSize: options.rpcMaxBatchSize,
107
129
  maxBodySizeBytes: options.rpcMaxBodySize,
108
130
  });
109
131
  const { port } = await startHttpRpcServer(rpcServer, { port: options.adminPort });
110
132
  debugLogger.info(`Aztec Server admin API listening on port ${port}`, versions);
133
+
134
+ // Display the API key after the server has started
135
+ // Uses userLog which is never filtered by LOG_LEVEL.
136
+ if (apiKeyResolution?.rawKey) {
137
+ const separator = '='.repeat(70);
138
+ userLog('');
139
+ userLog(separator);
140
+ userLog(' ADMIN API KEY (save this — it will NOT be shown again)');
141
+ userLog('');
142
+ userLog(` ${apiKeyResolution.rawKey}`);
143
+ userLog('');
144
+ userLog(` Use via header: x-api-key: <key>`);
145
+ userLog(` Or via header: Authorization: Bearer <key>`);
146
+ if (options.dataDirectory) {
147
+ userLog('');
148
+ userLog(' The key hash has been persisted — on next restart, the same key will be used.');
149
+ }
150
+ userLog('');
151
+ userLog(' To disable admin auth: --disable-admin-api-key or AZTEC_DISABLE_ADMIN_API_KEY=true');
152
+ userLog(separator);
153
+ userLog('');
154
+ }
111
155
  }
112
156
  }
@@ -142,6 +142,30 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
142
142
  env: 'AZTEC_ADMIN_PORT',
143
143
  parseVal: val => parseInt(val, 10),
144
144
  },
145
+ {
146
+ flag: '--admin-api-key-hash <value>',
147
+ description:
148
+ 'SHA-256 hex hash of a pre-generated admin API key. When set, the node uses this hash for authentication instead of auto-generating a key.',
149
+ defaultValue: undefined,
150
+ env: 'AZTEC_ADMIN_API_KEY_HASH',
151
+ },
152
+ {
153
+ flag: '--disable-admin-api-key',
154
+ description:
155
+ 'Disable API key authentication on the admin RPC endpoint. By default, a key is auto-generated, displayed once, and its hash is persisted.',
156
+ defaultValue: false,
157
+ env: 'AZTEC_DISABLE_ADMIN_API_KEY',
158
+ // undefined means the flag was passed without a value (boolean toggle), treat as true.
159
+ parseVal: val => val === undefined || val === 'true' || val === '1',
160
+ },
161
+ {
162
+ flag: '--reset-admin-api-key',
163
+ description:
164
+ 'Force-generate a new admin API key, replacing any previously persisted key hash. The new key is displayed once at startup.',
165
+ defaultValue: false,
166
+ env: 'AZTEC_RESET_ADMIN_API_KEY',
167
+ parseVal: val => val === 'true' || val === '1',
168
+ },
145
169
  {
146
170
  flag: '--api-prefix <value>',
147
171
  description: 'Prefix for API routes on any service that is started',
@@ -170,7 +194,7 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
170
194
  'WORLD STATE': [
171
195
  configToFlag('--world-state-data-directory', worldStateConfigMappings.worldStateDataDirectory),
172
196
  configToFlag('--world-state-db-map-size-kb', worldStateConfigMappings.worldStateDbMapSizeKb),
173
- configToFlag('--world-state-block-history', worldStateConfigMappings.worldStateBlockHistory),
197
+ configToFlag('--world-state-checkpoint-history', worldStateConfigMappings.worldStateCheckpointHistory),
174
198
  ],
175
199
  // We can't easily auto-generate node options as they're parts of modules defined below
176
200
  'AZTEC NODE': [
@@ -222,12 +246,8 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
222
246
  'proverNode',
223
247
  omitConfigMappings(proverNodeConfigMappings, [
224
248
  // filter out options passed separately
225
- ...getKeys(archiverConfigMappings),
226
249
  ...getKeys(proverBrokerConfigMappings),
227
250
  ...getKeys(proverAgentConfigMappings),
228
- ...getKeys(p2pConfigMappings),
229
- ...getKeys(worldStateConfigMappings),
230
- ...getKeys(sharedNodeConfigMappings),
231
251
  ]),
232
252
  ),
233
253
  ],
package/src/cli/cli.ts CHANGED
@@ -39,7 +39,6 @@ Additional commands:
39
39
 
40
40
  init [folder] [options] creates a new Aztec Noir project.
41
41
  new <path> [options] creates a new Aztec Noir project in a new directory.
42
- compile [options] compiles Aztec Noir contracts.
43
42
  test [options] starts a TXE and runs "nargo test" using it as the oracle resolver.
44
43
  `,
45
44
  );
@@ -0,0 +1,184 @@
1
+ import type { LogFn } from '@aztec/foundation/log';
2
+
3
+ import { execFileSync } from 'child_process';
4
+ import type { Command } from 'commander';
5
+ import { readFile, writeFile } from 'fs/promises';
6
+ import { join } from 'path';
7
+
8
+ import { readArtifactFiles } from './utils/artifacts.js';
9
+ import { run } from './utils/spawn.js';
10
+
11
+ /** Returns paths to contract artifacts in the target directory. */
12
+ async function collectContractArtifacts(): Promise<string[]> {
13
+ let files;
14
+ try {
15
+ files = await readArtifactFiles('target');
16
+ } catch (err: any) {
17
+ if (err?.message?.includes('does not exist')) {
18
+ return [];
19
+ }
20
+ throw err;
21
+ }
22
+ return files.filter(f => Array.isArray(f.content.functions)).map(f => f.filePath);
23
+ }
24
+
25
+ /** Strips the `__aztec_nr_internals__` prefix from function names in contract artifacts. */
26
+ async function stripInternalPrefixes(artifactPaths: string[]): Promise<void> {
27
+ for (const path of artifactPaths) {
28
+ const artifact = JSON.parse(await readFile(path, 'utf-8'));
29
+ for (const fn of artifact.functions) {
30
+ if (typeof fn.name === 'string') {
31
+ fn.name = fn.name.replace(/^__aztec_nr_internals__/, '');
32
+ }
33
+ }
34
+ await writeFile(path, JSON.stringify(artifact, null, 2) + '\n');
35
+ }
36
+ }
37
+
38
+ /** Returns the set of package names that are contract crates in the current workspace. */
39
+ async function getContractPackageNames(): Promise<Set<string>> {
40
+ const contractNames = new Set<string>();
41
+
42
+ let rootToml: string;
43
+ try {
44
+ rootToml = await readFile('Nargo.toml', 'utf-8');
45
+ } catch {
46
+ return contractNames;
47
+ }
48
+
49
+ const membersMatch = rootToml.match(/members\s*=\s*\[([^\]]*)\]/);
50
+ if (membersMatch) {
51
+ const members = membersMatch[1]
52
+ .split(',')
53
+ .map(m => m.trim().replace(/^"|"$/g, ''))
54
+ .filter(m => m.length > 0);
55
+
56
+ for (const member of members) {
57
+ try {
58
+ const memberToml = await readFile(join(member, 'Nargo.toml'), 'utf-8');
59
+ if (/type\s*=\s*"contract"/.test(memberToml)) {
60
+ const nameMatch = memberToml.match(/name\s*=\s*"([^"]+)"/);
61
+ if (nameMatch) {
62
+ contractNames.add(nameMatch[1]);
63
+ }
64
+ }
65
+ } catch {
66
+ // Member directory might not exist or have no Nargo.toml; skip.
67
+ }
68
+ }
69
+ } else {
70
+ // Single-crate project (no workspace): check if the root Nargo.toml itself is a contract.
71
+ if (/type\s*=\s*"contract"/.test(rootToml)) {
72
+ const nameMatch = rootToml.match(/name\s*=\s*"([^"]+)"/);
73
+ if (nameMatch) {
74
+ contractNames.add(nameMatch[1]);
75
+ }
76
+ }
77
+ }
78
+
79
+ return contractNames;
80
+ }
81
+
82
+ /** Checks that no tests exist in contract crates and fails with a helpful message if they do. */
83
+ async function checkNoTestsInContracts(nargo: string, log: LogFn): Promise<void> {
84
+ const contractPackages = await getContractPackageNames();
85
+ if (contractPackages.size === 0) {
86
+ return;
87
+ }
88
+
89
+ let output: string;
90
+ try {
91
+ // We list tests for all the crates in the workspace
92
+ output = execFileSync(nargo, ['test', '--list-tests', '--silence-warnings'], {
93
+ encoding: 'utf-8',
94
+ stdio: ['pipe', 'pipe', 'inherit'],
95
+ });
96
+ } catch {
97
+ // If listing tests fails (e.g. test crate has compile errors), skip the check.
98
+ return;
99
+ }
100
+
101
+ // The output of the `nargo test --list-tests` command is as follows:
102
+ // ```
103
+ // crate_name_1 test_name_1
104
+ // crate_name_2 test_name_2
105
+ // ...
106
+ // crate_name_n test_name_n
107
+ // ```
108
+ //
109
+ // We parse the individual lines and then we check if any contract crate appeared in the parsed output.
110
+ const lines = output
111
+ .trim()
112
+ .split('\n')
113
+ .filter(line => line.length > 0);
114
+ const testsInContracts: { packageName: string; testName: string }[] = [];
115
+
116
+ for (const line of lines) {
117
+ const spaceIndex = line.indexOf(' ');
118
+ if (spaceIndex === -1) {
119
+ continue;
120
+ }
121
+ const packageName = line.substring(0, spaceIndex);
122
+ const testName = line.substring(spaceIndex + 1);
123
+ if (contractPackages.has(packageName)) {
124
+ testsInContracts.push({ packageName, testName });
125
+ }
126
+ }
127
+
128
+ if (testsInContracts.length > 0) {
129
+ const details = testsInContracts.map(t => ` ${t.packageName}::${t.testName}`).join('\n');
130
+ log(
131
+ `WARNING: Found tests in contract crate(s):\n${details}\n\n` +
132
+ `Tests should be in a dedicated test crate, not in the contract crate.\n` +
133
+ `Learn more: https://docs.aztec.network/errors/1`,
134
+ );
135
+ }
136
+ }
137
+
138
+ /** Compiles Aztec Noir contracts and postprocesses artifacts. */
139
+ async function compileAztecContract(nargoArgs: string[], log: LogFn): Promise<void> {
140
+ const nargo = process.env.NARGO ?? 'nargo';
141
+ const bb = process.env.BB ?? 'bb';
142
+
143
+ await run(nargo, ['compile', ...nargoArgs]);
144
+
145
+ // Ensure contract crates contain no tests (tests belong in the test crate).
146
+ await checkNoTestsInContracts(nargo, log);
147
+
148
+ const artifacts = await collectContractArtifacts();
149
+
150
+ if (artifacts.length > 0) {
151
+ log('Postprocessing contracts...');
152
+ const bbArgs = artifacts.flatMap(a => ['-i', a]);
153
+ await run(bb, ['aztec_process', ...bbArgs]);
154
+
155
+ // TODO: This should be part of bb aztec_process!
156
+ await stripInternalPrefixes(artifacts);
157
+ }
158
+
159
+ log('Compilation complete!');
160
+ }
161
+
162
+ export function injectCompileCommand(program: Command, log: LogFn): Command {
163
+ program
164
+ .command('compile')
165
+ .argument('[nargo-args...]')
166
+ .passThroughOptions()
167
+ .allowUnknownOption()
168
+ .description(
169
+ 'Compile Aztec Noir contracts using nargo and postprocess them to generate transpiled artifacts and verification keys. All options are forwarded to nargo compile.',
170
+ )
171
+ .addHelpText('after', () => {
172
+ // Show nargo's own compile options so users see all available flags in one place.
173
+ const nargo = process.env.NARGO ?? 'nargo';
174
+ try {
175
+ const output = execFileSync(nargo, ['compile', '--help'], { encoding: 'utf-8' });
176
+ return `\nUnderlying nargo compile options:\n\n${output}`;
177
+ } catch {
178
+ return '\n(Run "nargo compile --help" to see available nargo options)';
179
+ }
180
+ })
181
+ .action((nargoArgs: string[]) => compileAztecContract(nargoArgs, log));
182
+
183
+ return program;
184
+ }
@@ -0,0 +1,25 @@
1
+ import type { LogFn } from '@aztec/foundation/log';
2
+
3
+ import type { Command } from 'commander';
4
+
5
+ import { profileFlamegraph } from './profile_flamegraph.js';
6
+ import { profileGates } from './profile_gates.js';
7
+
8
+ export function injectProfileCommand(program: Command, log: LogFn): Command {
9
+ const profile = program.command('profile').description('Profile compiled Aztec artifacts.');
10
+
11
+ profile
12
+ .command('gates')
13
+ .argument('[target-dir]', 'Path to the compiled artifacts directory', './target')
14
+ .description('Display gate counts for all compiled Aztec artifacts in a target directory.')
15
+ .action((targetDir: string) => profileGates(targetDir, log));
16
+
17
+ profile
18
+ .command('flamegraph')
19
+ .argument('<contract-artifact>', 'Path to the compiled contract artifact JSON')
20
+ .argument('<function>', 'Name of the contract function to profile')
21
+ .description('Generate a gate count flamegraph SVG for a contract function.')
22
+ .action((artifactPath: string, functionName: string) => profileFlamegraph(artifactPath, functionName, log));
23
+
24
+ return program;
25
+ }
@@ -0,0 +1,63 @@
1
+ import type { LogFn } from '@aztec/foundation/log';
2
+
3
+ import { readFile, rename, rm, writeFile } from 'fs/promises';
4
+ import { basename, dirname, join } from 'path';
5
+
6
+ import { makeFunctionArtifact } from './profile_utils.js';
7
+ import type { CompiledArtifact } from './utils/artifacts.js';
8
+ import { run } from './utils/spawn.js';
9
+
10
+ /** Generates a gate count flamegraph SVG for a single contract function. */
11
+ export async function profileFlamegraph(artifactPath: string, functionName: string, log: LogFn): Promise<void> {
12
+ const raw = await readFile(artifactPath, 'utf-8');
13
+ const artifact: CompiledArtifact = JSON.parse(raw);
14
+
15
+ if (!Array.isArray(artifact.functions)) {
16
+ throw new Error(`${artifactPath} does not appear to be a contract artifact (no functions array)`);
17
+ }
18
+
19
+ const func = artifact.functions.find(f => f.name === functionName);
20
+ if (!func) {
21
+ const available = artifact.functions.map(f => f.name).join(', ');
22
+ throw new Error(`Function "${functionName}" not found in artifact. Available: ${available}`);
23
+ }
24
+ if (func.is_unconstrained) {
25
+ throw new Error(`Function "${functionName}" is unconstrained and cannot be profiled`);
26
+ }
27
+
28
+ const outputDir = dirname(artifactPath);
29
+ const contractName = basename(artifactPath, '.json');
30
+ const functionArtifact = join(outputDir, `${contractName}-${functionName}.json`);
31
+
32
+ try {
33
+ await writeFile(functionArtifact, makeFunctionArtifact(artifact, func));
34
+
35
+ const profiler = process.env.PROFILER_PATH ?? 'noir-profiler';
36
+ const bb = process.env.BB ?? 'bb';
37
+
38
+ await run(profiler, [
39
+ 'gates',
40
+ '--artifact-path',
41
+ functionArtifact,
42
+ '--backend-path',
43
+ bb,
44
+ '--backend-gates-command',
45
+ 'gates',
46
+ '--output',
47
+ outputDir,
48
+ '--scheme',
49
+ 'chonk',
50
+ '--include_gates_per_opcode',
51
+ ]);
52
+
53
+ // noir-profiler names the SVG using the internal function name which
54
+ // retains the __aztec_nr_internals__ prefix in the bytecode metadata.
55
+ const srcSvg = join(outputDir, `__aztec_nr_internals__${functionName}_gates.svg`);
56
+ const destSvg = join(outputDir, `${contractName}-${functionName}-flamegraph.svg`);
57
+ await rename(srcSvg, destSvg);
58
+
59
+ log(`Flamegraph written to ${destSvg}`);
60
+ } finally {
61
+ await rm(functionArtifact, { force: true });
62
+ }
63
+ }
@@ -0,0 +1,67 @@
1
+ import { asyncPool } from '@aztec/foundation/async-pool';
2
+ import type { LogFn } from '@aztec/foundation/log';
3
+
4
+ import { execFile as execFileCb } from 'child_process';
5
+ import { rm } from 'fs/promises';
6
+ import { promisify } from 'util';
7
+
8
+ import { MAX_CONCURRENT, discoverArtifacts } from './profile_utils.js';
9
+
10
+ const execFile = promisify(execFileCb);
11
+
12
+ interface GateCountResult {
13
+ name: string;
14
+ gateCount: number;
15
+ }
16
+
17
+ /** Parses circuit_size from bb gates JSON output: { "functions": [{ "circuit_size": N }] } */
18
+ function parseGateCount(stdout: string): number {
19
+ const parsed = JSON.parse(stdout);
20
+ const size = parsed?.functions?.[0]?.circuit_size;
21
+ if (typeof size !== 'number') {
22
+ throw new Error('Failed to parse circuit_size from bb gates output');
23
+ }
24
+ return size;
25
+ }
26
+
27
+ /** Runs bb gates on a single artifact file and returns the gate count. */
28
+ async function getGateCount(bb: string, artifactPath: string): Promise<number> {
29
+ const { stdout } = await execFile(bb, ['gates', '--scheme', 'chonk', '-b', artifactPath]);
30
+ return parseGateCount(stdout);
31
+ }
32
+
33
+ /** Profiles all compiled artifacts in a target directory and prints gate counts. */
34
+ export async function profileGates(targetDir: string, log: LogFn): Promise<void> {
35
+ const bb = process.env.BB ?? 'bb';
36
+ const { artifacts, tmpDir } = await discoverArtifacts(targetDir);
37
+
38
+ if (artifacts.length === 0) {
39
+ log('No artifacts found in target directory.');
40
+ return;
41
+ }
42
+
43
+ try {
44
+ const results: GateCountResult[] = await asyncPool(MAX_CONCURRENT, artifacts, async artifact => ({
45
+ name: artifact.name,
46
+ gateCount: await getGateCount(bb, artifact.filePath),
47
+ }));
48
+ results.sort((a, b) => a.name.localeCompare(b.name));
49
+
50
+ if (results.length === 0) {
51
+ log('No constrained circuits found.');
52
+ return;
53
+ }
54
+
55
+ const maxNameLen = Math.max(...results.map(r => r.name.length));
56
+ log('');
57
+ log('Gate counts:');
58
+ log('-'.repeat(maxNameLen + 16));
59
+ for (const { name, gateCount } of results) {
60
+ log(`${name.padEnd(maxNameLen)} ${gateCount.toLocaleString().padStart(12)}`);
61
+ }
62
+ log('-'.repeat(maxNameLen + 16));
63
+ log(`Total: ${results.length} circuit(s)`);
64
+ } finally {
65
+ await rm(tmpDir, { recursive: true, force: true });
66
+ }
67
+ }