@aztec/aztec 0.0.1-commit.c31f2472 → 0.0.1-commit.c52d6e7

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 (158) hide show
  1. package/dest/bin/index.js +9 -3
  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 +69 -32
  8. package/dest/cli/aztec_start_options.d.ts +2 -2
  9. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  10. package/dest/cli/aztec_start_options.js +39 -23
  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 +3 -4
  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 +174 -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 +52 -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 +76 -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/prover.d.ts +4 -0
  30. package/dest/cli/cmds/prover.d.ts.map +1 -0
  31. package/dest/cli/cmds/prover.js +24 -0
  32. package/dest/cli/cmds/standby.d.ts +56 -0
  33. package/dest/cli/cmds/standby.d.ts.map +1 -0
  34. package/dest/cli/cmds/standby.js +140 -0
  35. package/dest/cli/cmds/start_bot.d.ts +3 -3
  36. package/dest/cli/cmds/start_bot.d.ts.map +1 -1
  37. package/dest/cli/cmds/start_bot.js +17 -9
  38. package/dest/cli/cmds/start_node.d.ts +3 -2
  39. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  40. package/dest/cli/cmds/start_node.js +82 -51
  41. package/dest/cli/cmds/start_prover_agent.d.ts +1 -1
  42. package/dest/cli/cmds/start_prover_agent.d.ts.map +1 -1
  43. package/dest/cli/cmds/start_prover_agent.js +6 -18
  44. package/dest/cli/cmds/start_prover_broker.d.ts +1 -1
  45. package/dest/cli/cmds/start_prover_broker.d.ts.map +1 -1
  46. package/dest/cli/cmds/start_prover_broker.js +24 -15
  47. package/dest/cli/cmds/start_txe.d.ts +2 -2
  48. package/dest/cli/cmds/start_txe.d.ts.map +1 -1
  49. package/dest/cli/cmds/start_txe.js +6 -5
  50. package/dest/cli/cmds/utils/artifacts.d.ts +26 -0
  51. package/dest/cli/cmds/utils/artifacts.d.ts.map +1 -0
  52. package/dest/cli/cmds/utils/artifacts.js +24 -0
  53. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts +21 -0
  54. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts.map +1 -0
  55. package/dest/cli/cmds/utils/collect_crate_dirs.js +114 -0
  56. package/dest/cli/cmds/utils/needs_recompile.d.ts +10 -0
  57. package/dest/cli/cmds/utils/needs_recompile.d.ts.map +1 -0
  58. package/dest/cli/cmds/utils/needs_recompile.js +90 -0
  59. package/dest/cli/cmds/utils/spawn.d.ts +3 -0
  60. package/dest/cli/cmds/utils/spawn.d.ts.map +1 -0
  61. package/dest/cli/cmds/utils/spawn.js +16 -0
  62. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts +4 -0
  63. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts.map +1 -0
  64. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.js +61 -0
  65. package/dest/cli/util.d.ts +13 -19
  66. package/dest/cli/util.d.ts.map +1 -1
  67. package/dest/cli/util.js +37 -100
  68. package/dest/examples/token.js +9 -9
  69. package/dest/local-network/auth_registry.d.ts +5 -0
  70. package/dest/local-network/auth_registry.d.ts.map +1 -0
  71. package/dest/local-network/auth_registry.js +17 -0
  72. package/dest/local-network/banana_fpc.d.ts +3 -2
  73. package/dest/local-network/banana_fpc.d.ts.map +1 -1
  74. package/dest/local-network/banana_fpc.js +12 -8
  75. package/dest/local-network/local-network.d.ts +12 -32
  76. package/dest/local-network/local-network.d.ts.map +1 -1
  77. package/dest/local-network/local-network.js +83 -72
  78. package/dest/testing/cheat_codes.d.ts +17 -23
  79. package/dest/testing/cheat_codes.d.ts.map +1 -1
  80. package/dest/testing/cheat_codes.js +17 -43
  81. package/dest/testing/epoch_test_settler.d.ts +2 -2
  82. package/dest/testing/epoch_test_settler.d.ts.map +1 -1
  83. package/dest/testing/epoch_test_settler.js +6 -26
  84. package/dest/testing/index.d.ts +3 -2
  85. package/dest/testing/index.d.ts.map +1 -1
  86. package/dest/testing/index.js +2 -1
  87. package/dest/testing/local-network.d.ts +51 -0
  88. package/dest/testing/local-network.d.ts.map +1 -0
  89. package/dest/testing/local-network.js +60 -0
  90. package/dest/testing/token_allowed_setup.d.ts +12 -0
  91. package/dest/testing/token_allowed_setup.d.ts.map +1 -0
  92. package/dest/testing/token_allowed_setup.js +24 -0
  93. package/package.json +35 -34
  94. package/scripts/add_crate.sh +53 -0
  95. package/scripts/aztec.sh +15 -5
  96. package/scripts/init.sh +23 -19
  97. package/scripts/new.sh +48 -24
  98. package/scripts/setup_workspace.sh +69 -0
  99. package/scripts/templates/blank/contract/Nargo.toml +6 -0
  100. package/scripts/templates/blank/contract/src/main.nr +10 -0
  101. package/scripts/templates/blank/test/Nargo.toml +7 -0
  102. package/scripts/templates/blank/test/src/lib.nr +11 -0
  103. package/scripts/templates/counter/contract/Nargo.toml +7 -0
  104. package/scripts/templates/counter/contract/src/main.nr +48 -0
  105. package/scripts/templates/counter/test/Nargo.toml +7 -0
  106. package/scripts/templates/counter/test/src/lib.nr +32 -0
  107. package/src/bin/index.ts +9 -3
  108. package/src/cli/admin_api_key_store.ts +128 -0
  109. package/src/cli/aztec_start_action.ts +69 -24
  110. package/src/cli/aztec_start_options.ts +48 -30
  111. package/src/cli/cli.ts +3 -4
  112. package/src/cli/cmds/compile.ts +205 -0
  113. package/src/cli/cmds/profile.ts +26 -0
  114. package/src/cli/cmds/profile_flamegraph.ts +64 -0
  115. package/src/cli/cmds/profile_gates.ts +84 -0
  116. package/src/cli/cmds/profile_utils.ts +58 -0
  117. package/src/cli/cmds/prover.ts +42 -0
  118. package/src/cli/cmds/standby.ts +184 -0
  119. package/src/cli/cmds/start_bot.ts +17 -11
  120. package/src/cli/cmds/start_node.ts +92 -52
  121. package/src/cli/cmds/start_prover_agent.ts +7 -10
  122. package/src/cli/cmds/start_prover_broker.ts +28 -25
  123. package/src/cli/cmds/start_txe.ts +7 -5
  124. package/src/cli/cmds/utils/artifacts.ts +49 -0
  125. package/src/cli/cmds/utils/collect_crate_dirs.ts +118 -0
  126. package/src/cli/cmds/utils/needs_recompile.ts +98 -0
  127. package/src/cli/cmds/utils/spawn.ts +16 -0
  128. package/src/cli/cmds/utils/warn_if_aztec_version_mismatch.ts +76 -0
  129. package/src/cli/util.ts +39 -118
  130. package/src/examples/token.ts +19 -9
  131. package/src/local-network/auth_registry.ts +19 -0
  132. package/src/local-network/banana_fpc.ts +13 -9
  133. package/src/local-network/local-network.ts +96 -81
  134. package/src/testing/cheat_codes.ts +18 -49
  135. package/src/testing/epoch_test_settler.ts +8 -32
  136. package/src/testing/index.ts +2 -1
  137. package/src/testing/local-network.ts +97 -0
  138. package/src/testing/token_allowed_setup.ts +26 -0
  139. package/dest/cli/cmds/start_archiver.d.ts +0 -9
  140. package/dest/cli/cmds/start_archiver.d.ts.map +0 -1
  141. package/dest/cli/cmds/start_archiver.js +0 -48
  142. package/dest/cli/cmds/start_prover_node.d.ts +0 -7
  143. package/dest/cli/cmds/start_prover_node.d.ts.map +0 -1
  144. package/dest/cli/cmds/start_prover_node.js +0 -108
  145. package/dest/cli/release_version.d.ts +0 -2
  146. package/dest/cli/release_version.d.ts.map +0 -1
  147. package/dest/cli/release_version.js +0 -14
  148. package/dest/testing/anvil_test_watcher.d.ts +0 -34
  149. package/dest/testing/anvil_test_watcher.d.ts.map +0 -1
  150. package/dest/testing/anvil_test_watcher.js +0 -144
  151. package/scripts/compile.sh +0 -44
  152. package/scripts/extract_function.js +0 -47
  153. package/scripts/flamegraph.sh +0 -59
  154. package/scripts/setup_project.sh +0 -31
  155. package/src/cli/cmds/start_archiver.ts +0 -50
  156. package/src/cli/cmds/start_prover_node.ts +0 -124
  157. package/src/cli/release_version.ts +0 -21
  158. package/src/testing/anvil_test_watcher.ts +0 -166
@@ -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,17 +1,20 @@
1
+ import { registerAztecNodeRpcHandlers } from '@aztec/aztec-node';
2
+ import { getActiveNetworkName } from '@aztec/foundation/config';
1
3
  import {
2
4
  type NamespacedApiHandlers,
3
5
  createNamespacedSafeJsonRpcServer,
6
+ getApiKeyAuthMiddleware,
4
7
  startHttpRpcServer,
5
8
  } from '@aztec/foundation/json-rpc/server';
6
9
  import type { LogFn, Logger } from '@aztec/foundation/log';
7
10
  import type { ChainConfig } from '@aztec/stdlib/config';
8
- import { AztecNodeApiSchema } from '@aztec/stdlib/interfaces/client';
11
+ import { getPackageVersion } from '@aztec/stdlib/update-checker';
9
12
  import { getVersioningMiddleware } from '@aztec/stdlib/versioning';
10
- import { getOtelJsonRpcPropagationMiddleware } from '@aztec/telemetry-client';
13
+ import { getOtelJsonRpcDiagnosticsMiddleware, getOtelJsonRpcPropagationMiddleware } from '@aztec/telemetry-client';
11
14
 
12
15
  import { createLocalNetwork } from '../local-network/index.js';
13
16
  import { github, splash } from '../splash.js';
14
- import { getCliVersion } from './release_version.js';
17
+ import { resolveAdminApiKey } from './admin_api_key_store.js';
15
18
  import { extractNamespacedOptions, installSignalHandlers } from './util.js';
16
19
  import { getVersions } from './versioning.js';
17
20
 
@@ -20,46 +23,39 @@ export async function aztecStart(options: any, userLog: LogFn, debugLogger: Logg
20
23
  const signalHandlers: Array<() => Promise<void>> = [];
21
24
  const services: NamespacedApiHandlers = {};
22
25
  const adminServices: NamespacedApiHandlers = {};
26
+ const packageVersion = getPackageVersion();
23
27
  let config: ChainConfig | undefined = undefined;
24
28
 
25
29
  if (options.localNetwork) {
26
- const cliVersion = getCliVersion();
27
- const localNetwork = extractNamespacedOptions(options, 'local-network');
28
- localNetwork.testAccounts = true;
30
+ const localNetwork = extractNamespacedOptions(options, 'localNetwork');
29
31
  userLog(`${splash}\n${github}\n\n`);
30
- userLog(`Setting up Aztec local network ${cliVersion}, please stand by...`);
32
+ userLog(`Setting up Aztec local network ${packageVersion}, please stand by...`);
31
33
 
32
34
  const { node, stop } = await createLocalNetwork(
33
35
  {
34
36
  l1Mnemonic: localNetwork.l1Mnemonic,
35
37
  l1RpcUrls: options.l1RpcUrls,
36
38
  testAccounts: localNetwork.testAccounts,
37
- realProofs: false,
38
- // Setting the epoch duration to 4 by default for local network. This allows the epoch to be "proven" faster, so
39
- // the users can consume out hash without having to wait for a long time.
40
- // Note: We are not proving anything in the local network (realProofs == false). But in `createLocalNetwork`,
41
- // the EpochTestSettler will set the out hash to the outbox when an epoch is complete.
42
- aztecEpochDuration: 4,
43
39
  },
44
40
  userLog,
45
41
  );
46
42
 
47
43
  // Start Node and PXE JSON-RPC server
48
44
  signalHandlers.push(stop);
49
- services.node = [node, AztecNodeApiSchema];
45
+ registerAztecNodeRpcHandlers(node, services, adminServices, { debug: true });
50
46
  } else {
47
+ // Route --prover-node through startNode
48
+ if (options.proverNode && !options.node) {
49
+ options.node = true;
50
+ }
51
+
51
52
  if (options.node) {
52
53
  const { startNode } = await import('./cmds/start_node.js');
53
- ({ config } = await startNode(options, signalHandlers, services, adminServices, userLog));
54
+ const networkName = getActiveNetworkName(options.network);
55
+ ({ config } = await startNode(options, signalHandlers, services, adminServices, userLog, networkName));
54
56
  } else if (options.bot) {
55
57
  const { startBot } = await import('./cmds/start_bot.js');
56
58
  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
- } else if (options.archiver) {
61
- const { startArchiver } = await import('./cmds/start_archiver.js');
62
- ({ config } = await startArchiver(options, signalHandlers, services));
63
59
  } else if (options.p2pBootstrap) {
64
60
  const { startP2PBootstrap } = await import('./cmds/start_p2p_bootstrap.js');
65
61
  ({ config } = await startP2PBootstrap(options, signalHandlers, services, userLog));
@@ -71,7 +67,7 @@ export async function aztecStart(options: any, userLog: LogFn, debugLogger: Logg
71
67
  await startProverBroker(options, signalHandlers, services, userLog);
72
68
  } else if (options.txe) {
73
69
  const { startTXE } = await import('./cmds/start_txe.js');
74
- await startTXE(options, debugLogger);
70
+ await startTXE(options, signalHandlers, debugLogger);
75
71
  } else if (options.sequencer) {
76
72
  userLog(`Cannot run a standalone sequencer without a node`);
77
73
  process.exit(1);
@@ -83,13 +79,21 @@ export async function aztecStart(options: any, userLog: LogFn, debugLogger: Logg
83
79
 
84
80
  installSignalHandlers(debugLogger.info, signalHandlers);
85
81
  const versions = getVersions(config);
82
+ const versioningOpts = { packageVersion };
86
83
 
87
84
  // Start the main JSON-RPC server
88
85
  if (Object.entries(services).length > 0) {
86
+ if (services.aztec) {
87
+ const { BarretenbergSync } = await import('@aztec/bb.js');
88
+ // JSON-RPC schema parsing may decompress compressed Chonk proofs before the node handler runs.
89
+ await BarretenbergSync.initSingleton();
90
+ }
91
+
89
92
  const rpcServer = createNamespacedSafeJsonRpcServer(services, {
93
+ diagnostic: getOtelJsonRpcDiagnosticsMiddleware(),
90
94
  http200OnError: false,
91
95
  log: debugLogger,
92
- middlewares: [getOtelJsonRpcPropagationMiddleware(), getVersioningMiddleware(versions)],
96
+ middlewares: [getOtelJsonRpcPropagationMiddleware(), getVersioningMiddleware(versions, versioningOpts)],
93
97
  maxBatchSize: options.rpcMaxBatchSize,
94
98
  maxBodySizeBytes: options.rpcMaxBodySize,
95
99
  });
@@ -99,14 +103,55 @@ 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, versioningOpts)];
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, {
125
+ diagnostic: getOtelJsonRpcDiagnosticsMiddleware(),
103
126
  http200OnError: false,
104
127
  log: debugLogger,
105
- middlewares: [getOtelJsonRpcPropagationMiddleware(), getVersioningMiddleware(versions)],
128
+ middlewares: adminMiddlewares,
106
129
  maxBatchSize: options.rpcMaxBatchSize,
107
130
  maxBodySizeBytes: options.rpcMaxBodySize,
108
131
  });
109
132
  const { port } = await startHttpRpcServer(rpcServer, { port: options.adminPort });
110
133
  debugLogger.info(`Aztec Server admin API listening on port ${port}`, versions);
134
+
135
+ // Display the API key after the server has started
136
+ // Uses userLog which is never filtered by LOG_LEVEL.
137
+ if (apiKeyResolution?.rawKey) {
138
+ const separator = '='.repeat(70);
139
+ userLog('');
140
+ userLog(separator);
141
+ userLog(' ADMIN API KEY (save this — it will NOT be shown again)');
142
+ userLog('');
143
+ userLog(` ${apiKeyResolution.rawKey}`);
144
+ userLog('');
145
+ userLog(` Use via header: x-api-key: <key>`);
146
+ userLog(` Or via header: Authorization: Bearer <key>`);
147
+ if (options.dataDirectory) {
148
+ userLog('');
149
+ userLog(' The key hash has been persisted — on next restart, the same key will be used.');
150
+ }
151
+ userLog('');
152
+ userLog(' To disable admin auth: --disable-admin-api-key or AZTEC_DISABLE_ADMIN_API_KEY=true');
153
+ userLog(separator);
154
+ userLog('');
155
+ }
111
156
  }
112
157
  }
@@ -12,7 +12,6 @@ import {
12
12
  isBooleanConfigValue,
13
13
  omitConfigMappings,
14
14
  } from '@aztec/foundation/config';
15
- import { dataConfigMappings } from '@aztec/kv-store/config';
16
15
  import { sharedNodeConfigMappings } from '@aztec/node-lib/config';
17
16
  import { bootnodeConfigMappings, p2pConfigMappings } from '@aztec/p2p/config';
18
17
  import { proverAgentConfigMappings, proverBrokerConfigMappings } from '@aztec/prover-client/broker/config';
@@ -20,6 +19,7 @@ import { proverNodeConfigMappings } from '@aztec/prover-node/config';
20
19
  import { allPxeConfigMappings } from '@aztec/pxe/config';
21
20
  import { sequencerClientConfigMappings } from '@aztec/sequencer-client/config';
22
21
  import { chainConfigMappings, nodeRpcConfigMappings } from '@aztec/stdlib/config';
22
+ import { dataConfigMappings } from '@aztec/stdlib/kv-store';
23
23
  import { telemetryClientConfigMappings } from '@aztec/telemetry-client/config';
24
24
  import { worldStateConfigMappings } from '@aztec/world-state/config';
25
25
 
@@ -36,7 +36,7 @@ export interface AztecStartOption {
36
36
  parseVal?: (val: string) => any;
37
37
  }
38
38
 
39
- export const getOptions = (namespace: string, configMappings: Record<string, ConfigMapping>) => {
39
+ export const getOptions = (namespace: string, configMappings: Record<string, ConfigMapping<unknown>>) => {
40
40
  const options: AztecStartOption[] = [];
41
41
  for (const [key, { env, defaultValue: def, parseEnv, description, printDefault, fallback }] of Object.entries(
42
42
  configMappings,
@@ -58,7 +58,11 @@ export const getOptions = (namespace: string, configMappings: Record<string, Con
58
58
  return options;
59
59
  };
60
60
 
61
- const configToFlag = (flag: string, configMapping: ConfigMapping, overrideDefaultValue?: any): AztecStartOption => {
61
+ const configToFlag = (
62
+ flag: string,
63
+ configMapping: ConfigMapping<unknown>,
64
+ overrideDefaultValue?: any,
65
+ ): AztecStartOption => {
62
66
  if (!configMapping.isBoolean) {
63
67
  flag += ' <value>';
64
68
  }
@@ -105,8 +109,7 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
105
109
  env: 'NETWORK',
106
110
  },
107
111
 
108
- configToFlag('--auto-update', sharedNodeConfigMappings.autoUpdate),
109
- configToFlag('--auto-update-url', sharedNodeConfigMappings.autoUpdateUrl),
112
+ configToFlag('--enable-auto-shutdown', sharedNodeConfigMappings.enableAutoShutdown),
110
113
 
111
114
  configToFlag('--sync-mode', sharedNodeConfigMappings.syncMode),
112
115
  configToFlag('--snapshots-urls', sharedNodeConfigMappings.snapshotsUrls),
@@ -126,6 +129,12 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
126
129
  defaultValue: DefaultMnemonic,
127
130
  env: 'MNEMONIC',
128
131
  },
132
+ {
133
+ flag: '--local-network.testAccounts',
134
+ description: 'Deploy test accounts on local network start',
135
+ env: 'TEST_ACCOUNTS',
136
+ ...booleanConfigHelper(true),
137
+ },
129
138
  ],
130
139
  API: [
131
140
  {
@@ -142,6 +151,37 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
142
151
  env: 'AZTEC_ADMIN_PORT',
143
152
  parseVal: val => parseInt(val, 10),
144
153
  },
154
+ {
155
+ flag: '--admin-api-key-hash <value>',
156
+ description:
157
+ '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.',
158
+ defaultValue: undefined,
159
+ env: 'AZTEC_ADMIN_API_KEY_HASH',
160
+ },
161
+ {
162
+ flag: '--disable-admin-api-key',
163
+ description:
164
+ 'Disable API key authentication on the admin RPC endpoint. By default, a key is auto-generated, displayed once, and its hash is persisted.',
165
+ defaultValue: false,
166
+ env: 'AZTEC_DISABLE_ADMIN_API_KEY',
167
+ // undefined means the flag was passed without a value (boolean toggle), treat as true.
168
+ parseVal: val => val === undefined || val === 'true' || val === '1',
169
+ },
170
+ {
171
+ flag: '--reset-admin-api-key',
172
+ description:
173
+ 'Force-generate a new admin API key, replacing any previously persisted key hash. The new key is displayed once at startup.',
174
+ defaultValue: false,
175
+ env: 'AZTEC_RESET_ADMIN_API_KEY',
176
+ parseVal: val => val === 'true' || val === '1',
177
+ },
178
+ {
179
+ flag: '--node-debug',
180
+ description: 'Expose debug endpoints (e.g. mineBlock) on the main RPC port',
181
+ defaultValue: false,
182
+ env: 'AZTEC_NODE_DEBUG',
183
+ parseVal: val => val === undefined || val === 'true' || val === '1',
184
+ },
145
185
  {
146
186
  flag: '--api-prefix <value>',
147
187
  description: 'Prefix for API routes on any service that is started',
@@ -170,7 +210,7 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
170
210
  'WORLD STATE': [
171
211
  configToFlag('--world-state-data-directory', worldStateConfigMappings.worldStateDataDirectory),
172
212
  configToFlag('--world-state-db-map-size-kb', worldStateConfigMappings.worldStateDbMapSizeKb),
173
- configToFlag('--world-state-block-history', worldStateConfigMappings.worldStateBlockHistory),
213
+ configToFlag('--world-state-checkpoint-history', worldStateConfigMappings.worldStateCheckpointHistory),
174
214
  ],
175
215
  // We can't easily auto-generate node options as they're parts of modules defined below
176
216
  'AZTEC NODE': [
@@ -182,12 +222,6 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
182
222
  },
183
223
  ],
184
224
  ARCHIVER: [
185
- {
186
- flag: '--archiver',
187
- description: 'Starts Aztec Archiver with options',
188
- defaultValue: undefined,
189
- env: undefined,
190
- },
191
225
  ...getOptions(
192
226
  'archiver',
193
227
  omitConfigMappings(archiverConfigMappings, Object.keys(l1ContractsConfigMappings) as (keyof ArchiverConfig)[]),
@@ -222,12 +256,8 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
222
256
  'proverNode',
223
257
  omitConfigMappings(proverNodeConfigMappings, [
224
258
  // filter out options passed separately
225
- ...getKeys(archiverConfigMappings),
226
259
  ...getKeys(proverBrokerConfigMappings),
227
260
  ...getKeys(proverAgentConfigMappings),
228
- ...getKeys(p2pConfigMappings),
229
- ...getKeys(worldStateConfigMappings),
230
- ...getKeys(sharedNodeConfigMappings),
231
261
  ]),
232
262
  ),
233
263
  ],
@@ -238,11 +268,7 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
238
268
  defaultValue: undefined,
239
269
  env: undefined,
240
270
  },
241
- ...getOptions(
242
- 'proverBroker',
243
- // filter out archiver options from prover node options as they're passed separately in --archiver
244
- proverBrokerConfigMappings,
245
- ),
271
+ ...getOptions('proverBroker', proverBrokerConfigMappings),
246
272
  ],
247
273
  'PROVER AGENT': [
248
274
  {
@@ -290,15 +316,7 @@ export const aztecStartOptions: { [key: string]: AztecStartOption[] } = {
290
316
  },
291
317
  ...getOptions('bot', botConfigMappings),
292
318
  ],
293
- PXE: [
294
- {
295
- flag: '--pxe',
296
- description: 'Starts Aztec PXE with options',
297
- defaultValue: undefined,
298
- env: undefined,
299
- },
300
- ...getOptions('pxe', allPxeConfigMappings),
301
- ],
319
+ PXE: [...getOptions('pxe', allPxeConfigMappings)],
302
320
  TXE: [
303
321
  {
304
322
  flag: '--txe',
package/src/cli/cli.ts CHANGED
@@ -37,10 +37,9 @@ export function injectAztecCommands(program: Command, userLog: LogFn, debugLogge
37
37
  `
38
38
  Additional commands:
39
39
 
40
- init [folder] [options] creates a new Aztec Noir project.
41
- new <path> [options] creates a new Aztec Noir project in a new directory.
42
- compile [options] compiles Aztec Noir contracts.
43
- test [options] starts a TXE and runs "nargo test" using it as the oracle resolver.
40
+ init creates a new Aztec Noir workspace in the current directory.
41
+ new <name> creates a new Aztec Noir workspace in its own directory (or creates a new contract-test crates pair and adds it to the current workspace if run in workspace).
42
+ test [options] starts a TXE and runs "nargo test" using it as the oracle resolver.
44
43
  `,
45
44
  );
46
45
  }
@@ -0,0 +1,205 @@
1
+ import { findBbBinary } from '@aztec/bb.js';
2
+ import type { LogFn } from '@aztec/foundation/log';
3
+ import { getPackageVersion } from '@aztec/stdlib/update-checker';
4
+
5
+ import { execFileSync } from 'child_process';
6
+ import type { Command } from 'commander';
7
+ import { readFile, writeFile } from 'fs/promises';
8
+ import { join } from 'path';
9
+
10
+ import { readArtifactFiles } from './utils/artifacts.js';
11
+ import { needsRecompile } from './utils/needs_recompile.js';
12
+ import { run } from './utils/spawn.js';
13
+ import { warnIfAztecVersionMismatch } from './utils/warn_if_aztec_version_mismatch.js';
14
+
15
+ /** Returns contract artifacts in the target directory along with whether each has already been postprocessed. */
16
+ async function collectContractArtifacts(): Promise<ContractArtifactInfo[]> {
17
+ let files;
18
+ try {
19
+ files = await readArtifactFiles('target');
20
+ } catch (err: any) {
21
+ if (err?.message?.includes('does not exist')) {
22
+ return [];
23
+ }
24
+ throw err;
25
+ }
26
+ return files
27
+ .filter(f => Array.isArray(f.content.functions))
28
+ .map(f => ({ filePath: f.filePath, transpiled: f.content.transpiled === true }));
29
+ }
30
+
31
+ /** Stamps the Aztec stack version into the contract artifacts. */
32
+ async function stampAztecVersion(artifactPaths: string[]): Promise<void> {
33
+ const version = getPackageVersion();
34
+ for (const path of artifactPaths) {
35
+ const artifact = JSON.parse(await readFile(path, 'utf-8'));
36
+ // eslint-disable-next-line camelcase
37
+ artifact.aztec_version = version;
38
+ await writeFile(path, JSON.stringify(artifact, null, 2) + '\n');
39
+ }
40
+ }
41
+
42
+ /** Returns the set of package names that are contract crates in the current workspace. */
43
+ async function getContractPackageNames(): Promise<Set<string>> {
44
+ const contractNames = new Set<string>();
45
+
46
+ let rootToml: string;
47
+ try {
48
+ rootToml = await readFile('Nargo.toml', 'utf-8');
49
+ } catch {
50
+ return contractNames;
51
+ }
52
+
53
+ const membersMatch = rootToml.match(/members\s*=\s*\[([^\]]*)\]/);
54
+ if (membersMatch) {
55
+ const members = membersMatch[1]
56
+ .split(',')
57
+ .map(m => m.trim().replace(/^"|"$/g, ''))
58
+ .filter(m => m.length > 0);
59
+
60
+ for (const member of members) {
61
+ try {
62
+ const memberToml = await readFile(join(member, 'Nargo.toml'), 'utf-8');
63
+ if (/type\s*=\s*"contract"/.test(memberToml)) {
64
+ const nameMatch = memberToml.match(/name\s*=\s*"([^"]+)"/);
65
+ if (nameMatch) {
66
+ contractNames.add(nameMatch[1]);
67
+ }
68
+ }
69
+ } catch {
70
+ // Member directory might not exist or have no Nargo.toml; skip.
71
+ }
72
+ }
73
+ } else {
74
+ // Single-crate project (no workspace): check if the root Nargo.toml itself is a contract.
75
+ if (/type\s*=\s*"contract"/.test(rootToml)) {
76
+ const nameMatch = rootToml.match(/name\s*=\s*"([^"]+)"/);
77
+ if (nameMatch) {
78
+ contractNames.add(nameMatch[1]);
79
+ }
80
+ }
81
+ }
82
+
83
+ return contractNames;
84
+ }
85
+
86
+ /** Checks that no tests exist in contract crates and fails with a helpful message if they do. */
87
+ async function checkNoTestsInContracts(nargo: string, log: LogFn): Promise<void> {
88
+ const contractPackages = await getContractPackageNames();
89
+ if (contractPackages.size === 0) {
90
+ return;
91
+ }
92
+
93
+ let output: string;
94
+ try {
95
+ // We list tests for all the crates in the workspace
96
+ output = execFileSync(nargo, ['test', '--list-tests', '--silence-warnings'], {
97
+ encoding: 'utf-8',
98
+ stdio: ['pipe', 'pipe', 'inherit'],
99
+ });
100
+ } catch {
101
+ // If listing tests fails (e.g. test crate has compile errors), skip the check.
102
+ return;
103
+ }
104
+
105
+ // The output of the `nargo test --list-tests` command is as follows:
106
+ // ```
107
+ // crate_name_1 test_name_1
108
+ // crate_name_2 test_name_2
109
+ // ...
110
+ // crate_name_n test_name_n
111
+ // ```
112
+ //
113
+ // We parse the individual lines and then we check if any contract crate appeared in the parsed output.
114
+ const lines = output
115
+ .trim()
116
+ .split('\n')
117
+ .filter(line => line.length > 0);
118
+ const testsInContracts: { packageName: string; testName: string }[] = [];
119
+
120
+ for (const line of lines) {
121
+ const spaceIndex = line.indexOf(' ');
122
+ if (spaceIndex === -1) {
123
+ continue;
124
+ }
125
+ const packageName = line.substring(0, spaceIndex);
126
+ const testName = line.substring(spaceIndex + 1);
127
+ if (contractPackages.has(packageName)) {
128
+ testsInContracts.push({ packageName, testName });
129
+ }
130
+ }
131
+
132
+ if (testsInContracts.length > 0) {
133
+ const details = testsInContracts.map(t => ` ${t.packageName}::${t.testName}`).join('\n');
134
+ log(
135
+ `WARNING: Found tests in contract crate(s):\n${details}\n\n` +
136
+ `Tests should be in a dedicated test crate, not in the contract crate.\n` +
137
+ `Learn more: https://docs.aztec.network/errors/1`,
138
+ );
139
+ }
140
+ }
141
+
142
+ /** Compiles Aztec Noir contracts and postprocesses artifacts. */
143
+ async function compileAztecContract(nargoArgs: string[], log: LogFn): Promise<void> {
144
+ await warnIfAztecVersionMismatch(log);
145
+
146
+ const nargo = process.env.NARGO ?? 'nargo';
147
+ const bb = process.env.BB ?? findBbBinary() ?? 'bb';
148
+
149
+ const shouldRecompile = await needsRecompile();
150
+ if (shouldRecompile) {
151
+ await run(nargo, ['compile', ...nargoArgs]);
152
+
153
+ // Ensure contract crates contain no tests (tests belong in the test crate).
154
+ await checkNoTestsInContracts(nargo, log);
155
+ }
156
+
157
+ // Postprocess any untranspiled artifacts: those just produced by nargo above, and any left behind by a bare
158
+ // `nargo compile` run outside `aztec compile`.
159
+ const unprocessed = (await collectContractArtifacts()).filter(a => !a.transpiled).map(a => a.filePath);
160
+
161
+ if (unprocessed.length > 0) {
162
+ log('Postprocessing contracts...');
163
+ const bbArgs = unprocessed.flatMap(a => ['-i', a]);
164
+ await run(bb, ['aztec_process', ...bbArgs]);
165
+
166
+ await stampAztecVersion(unprocessed);
167
+ }
168
+
169
+ if (shouldRecompile || unprocessed.length > 0) {
170
+ log('Compilation complete!');
171
+ } else {
172
+ log('No source changes detected, skipping compilation.');
173
+ }
174
+ }
175
+
176
+ export function injectCompileCommand(program: Command, log: LogFn): Command {
177
+ program
178
+ .command('compile')
179
+ .argument('[nargo-args...]')
180
+ .passThroughOptions()
181
+ .allowUnknownOption()
182
+ .description(
183
+ 'Compile Aztec Noir contracts using nargo and postprocess them to generate transpiled artifacts and verification keys. All options are forwarded to nargo compile.',
184
+ )
185
+ .addHelpText('after', () => {
186
+ // Show nargo's own compile options so users see all available flags in one place.
187
+ const nargo = process.env.NARGO ?? 'nargo';
188
+ try {
189
+ const output = execFileSync(nargo, ['compile', '--help'], { encoding: 'utf-8' });
190
+ return `\nUnderlying nargo compile options:\n\n${output}`;
191
+ } catch {
192
+ return '\n(Run "nargo compile --help" to see available nargo options)';
193
+ }
194
+ })
195
+ .action((nargoArgs: string[]) => compileAztecContract(nargoArgs, log));
196
+
197
+ return program;
198
+ }
199
+
200
+ interface ContractArtifactInfo {
201
+ /** Path to the artifact JSON in the target directory. */
202
+ filePath: string;
203
+ /** Whether the artifact has already been transpiled and had its verification keys generated. */
204
+ transpiled: boolean;
205
+ }