@aztec/end-to-end 4.0.0-nightly.20260120 → 4.0.0-nightly.20260122

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 (56) hide show
  1. package/dest/shared/cross_chain_test_harness.d.ts +3 -4
  2. package/dest/shared/cross_chain_test_harness.d.ts.map +1 -1
  3. package/dest/shared/submit-transactions.d.ts +1 -1
  4. package/dest/shared/submit-transactions.d.ts.map +1 -1
  5. package/dest/shared/submit-transactions.js +1 -4
  6. package/dest/spartan/tx_metrics.d.ts +11 -1
  7. package/dest/spartan/tx_metrics.d.ts.map +1 -1
  8. package/dest/spartan/tx_metrics.js +133 -4
  9. package/dest/spartan/utils/bot.d.ts +27 -0
  10. package/dest/spartan/utils/bot.d.ts.map +1 -0
  11. package/dest/spartan/utils/bot.js +141 -0
  12. package/dest/spartan/utils/chaos.d.ts +79 -0
  13. package/dest/spartan/utils/chaos.d.ts.map +1 -0
  14. package/dest/spartan/utils/chaos.js +142 -0
  15. package/dest/spartan/utils/clients.d.ts +25 -0
  16. package/dest/spartan/utils/clients.d.ts.map +1 -0
  17. package/dest/spartan/utils/clients.js +101 -0
  18. package/dest/spartan/utils/config.d.ts +36 -0
  19. package/dest/spartan/utils/config.d.ts.map +1 -0
  20. package/dest/spartan/utils/config.js +20 -0
  21. package/dest/spartan/utils/health.d.ts +63 -0
  22. package/dest/spartan/utils/health.d.ts.map +1 -0
  23. package/dest/spartan/utils/health.js +202 -0
  24. package/dest/spartan/utils/helm.d.ts +15 -0
  25. package/dest/spartan/utils/helm.d.ts.map +1 -0
  26. package/dest/spartan/utils/helm.js +47 -0
  27. package/dest/spartan/utils/index.d.ts +9 -0
  28. package/dest/spartan/utils/index.d.ts.map +1 -0
  29. package/dest/spartan/utils/index.js +18 -0
  30. package/dest/spartan/utils/k8s.d.ts +59 -0
  31. package/dest/spartan/utils/k8s.d.ts.map +1 -0
  32. package/dest/spartan/utils/k8s.js +185 -0
  33. package/dest/spartan/utils/nodes.d.ts +31 -0
  34. package/dest/spartan/utils/nodes.d.ts.map +1 -0
  35. package/dest/spartan/utils/nodes.js +273 -0
  36. package/dest/spartan/utils/scripts.d.ts +16 -0
  37. package/dest/spartan/utils/scripts.d.ts.map +1 -0
  38. package/dest/spartan/utils/scripts.js +66 -0
  39. package/dest/spartan/utils.d.ts +2 -260
  40. package/dest/spartan/utils.d.ts.map +1 -1
  41. package/dest/spartan/utils.js +1 -942
  42. package/package.json +39 -39
  43. package/src/shared/cross_chain_test_harness.ts +2 -3
  44. package/src/shared/submit-transactions.ts +1 -6
  45. package/src/spartan/tx_metrics.ts +82 -4
  46. package/src/spartan/utils/bot.ts +185 -0
  47. package/src/spartan/utils/chaos.ts +253 -0
  48. package/src/spartan/utils/clients.ts +106 -0
  49. package/src/spartan/utils/config.ts +26 -0
  50. package/src/spartan/utils/health.ts +256 -0
  51. package/src/spartan/utils/helm.ts +84 -0
  52. package/src/spartan/utils/index.ts +58 -0
  53. package/src/spartan/utils/k8s.ts +279 -0
  54. package/src/spartan/utils/nodes.ts +308 -0
  55. package/src/spartan/utils/scripts.ts +63 -0
  56. package/src/spartan/utils.ts +1 -1246
@@ -1,942 +1 @@
1
- import { createLogger } from '@aztec/aztec.js/log';
2
- import { promiseWithResolvers } from '@aztec/foundation/promise';
3
- import { makeBackoff, retry } from '@aztec/foundation/retry';
4
- import { schemas } from '@aztec/foundation/schemas';
5
- import { sleep } from '@aztec/foundation/sleep';
6
- import { createAztecNodeAdminClient, createAztecNodeClient } from '@aztec/stdlib/interfaces/client';
7
- import { exec, execSync, spawn } from 'child_process';
8
- import path from 'path';
9
- import { promisify } from 'util';
10
- import { createPublicClient, fallback, http } from 'viem';
11
- import { z } from 'zod';
12
- const execAsync = promisify(exec);
13
- const logger = createLogger('e2e:k8s-utils');
14
- const testConfigSchema = z.object({
15
- NAMESPACE: z.string().default('scenario'),
16
- REAL_VERIFIER: schemas.Boolean.optional().default(true),
17
- CREATE_ETH_DEVNET: schemas.Boolean.optional().default(false),
18
- L1_RPC_URLS_JSON: z.string().optional(),
19
- L1_ACCOUNT_MNEMONIC: z.string().optional(),
20
- AZTEC_SLOT_DURATION: z.coerce.number().optional().default(24),
21
- AZTEC_EPOCH_DURATION: z.coerce.number().optional().default(32),
22
- AZTEC_PROOF_SUBMISSION_WINDOW: z.coerce.number().optional().default(5),
23
- AZTEC_LAG_IN_EPOCHS_FOR_VALIDATOR_SET: z.coerce.number().optional().default(2)
24
- });
25
- export function setupEnvironment(env) {
26
- const config = testConfigSchema.parse(env);
27
- logger.warn(`Loaded env config`, config);
28
- return config;
29
- }
30
- /**
31
- * @param path - The path to the script, relative to the project root
32
- * @param args - The arguments to pass to the script
33
- * @param logger - The logger to use
34
- * @returns The exit code of the script
35
- */ function runScript(path, args, logger, env) {
36
- const childProcess = spawn(path, args, {
37
- stdio: [
38
- 'ignore',
39
- 'pipe',
40
- 'pipe'
41
- ],
42
- env: env ? {
43
- ...process.env,
44
- ...env
45
- } : process.env
46
- });
47
- return new Promise((resolve, reject)=>{
48
- childProcess.on('close', (code)=>resolve(code ?? 0));
49
- childProcess.on('error', reject);
50
- childProcess.stdout?.on('data', (data)=>{
51
- logger.info(data.toString());
52
- });
53
- childProcess.stderr?.on('data', (data)=>{
54
- logger.error(data.toString());
55
- });
56
- });
57
- }
58
- export function getAztecBin() {
59
- return path.join(getGitProjectRoot(), 'yarn-project/aztec/dest/bin/index.js');
60
- }
61
- /**
62
- * Runs the Aztec binary
63
- * @param args - The arguments to pass to the Aztec binary
64
- * @param logger - The logger to use
65
- * @param env - Optional environment variables to set for the process
66
- * @returns The exit code of the Aztec binary
67
- */ export function runAztecBin(args, logger, env) {
68
- return runScript('node', [
69
- getAztecBin(),
70
- ...args
71
- ], logger, env);
72
- }
73
- export function runProjectScript(script, args, logger, env) {
74
- const scriptPath = script.startsWith('/') ? script : path.join(getGitProjectRoot(), script);
75
- return runScript(scriptPath, args, logger, env);
76
- }
77
- export async function startPortForward({ resource, namespace, containerPort, hostPort }) {
78
- const hostPortAsString = hostPort ? hostPort.toString() : '';
79
- logger.debug(`kubectl port-forward -n ${namespace} ${resource} ${hostPortAsString}:${containerPort}`);
80
- const process1 = spawn('kubectl', [
81
- 'port-forward',
82
- '-n',
83
- namespace,
84
- resource,
85
- `${hostPortAsString}:${containerPort}`
86
- ], {
87
- detached: true,
88
- windowsHide: true,
89
- stdio: [
90
- 'ignore',
91
- 'pipe',
92
- 'pipe'
93
- ]
94
- });
95
- let isResolved = false;
96
- const connected = new Promise((resolve, reject)=>{
97
- process1.stdout?.on('data', (data)=>{
98
- const str = data.toString();
99
- if (!isResolved && str.includes('Forwarding from')) {
100
- isResolved = true;
101
- logger.debug(`Port forward for ${resource}: ${str}`);
102
- const port = str.search(/:\d+/);
103
- if (port === -1) {
104
- reject(new Error('Port not found in port forward output'));
105
- return;
106
- }
107
- const portNumber = parseInt(str.slice(port + 1));
108
- logger.verbose(`Port forwarded for ${resource} at ${portNumber}:${containerPort}`);
109
- resolve(portNumber);
110
- } else {
111
- logger.silent(str);
112
- }
113
- });
114
- process1.stderr?.on('data', (data)=>{
115
- logger.verbose(`Port forward for ${resource}: ${data.toString()}`);
116
- // It's a strange thing:
117
- // If we don't pipe stderr, then the port forwarding does not work.
118
- // Log to silent because this doesn't actually report errors,
119
- // just extremely verbose debug logs.
120
- logger.silent(data.toString());
121
- });
122
- process1.on('close', ()=>{
123
- if (!isResolved) {
124
- isResolved = true;
125
- const msg = `Port forward for ${resource} closed before connection established`;
126
- logger.warn(msg);
127
- reject(new Error(msg));
128
- }
129
- });
130
- process1.on('error', (error)=>{
131
- if (!isResolved) {
132
- isResolved = true;
133
- const msg = `Port forward for ${resource} error: ${error}`;
134
- logger.error(msg);
135
- reject(new Error(msg));
136
- }
137
- });
138
- process1.on('exit', (code)=>{
139
- if (!isResolved) {
140
- isResolved = true;
141
- const msg = `Port forward for ${resource} exited with code ${code}`;
142
- logger.verbose(msg);
143
- reject(new Error(msg));
144
- }
145
- });
146
- });
147
- const port = await connected;
148
- return {
149
- process: process1,
150
- port
151
- };
152
- }
153
- export function getExternalIP(namespace, serviceName) {
154
- const { promise, resolve, reject } = promiseWithResolvers();
155
- const process1 = spawn('kubectl', [
156
- 'get',
157
- 'service',
158
- '-n',
159
- namespace,
160
- `${namespace}-${serviceName}`,
161
- '--output',
162
- "jsonpath='{.status.loadBalancer.ingress[0].ip}'"
163
- ], {
164
- stdio: 'pipe'
165
- });
166
- let ip = '';
167
- process1.stdout.on('data', (data)=>{
168
- ip += data;
169
- });
170
- process1.on('error', (err)=>{
171
- reject(err);
172
- });
173
- process1.on('exit', ()=>{
174
- // kubectl prints JSON. Remove the quotes
175
- resolve(ip.replace(/"|'/g, ''));
176
- });
177
- return promise;
178
- }
179
- export function startPortForwardForPrometeheus(namespace) {
180
- return startPortForward({
181
- resource: `svc/${namespace}-prometheus-server`,
182
- namespace,
183
- containerPort: 80
184
- });
185
- }
186
- export function startPortForwardForRPC(namespace, index = 0) {
187
- return startPortForward({
188
- resource: `pod/${namespace}-rpc-aztec-node-${index}`,
189
- namespace,
190
- containerPort: 8080
191
- });
192
- }
193
- export function startPortForwardForEthereum(namespace) {
194
- return startPortForward({
195
- resource: `services/${namespace}-eth-execution`,
196
- namespace,
197
- containerPort: 8545
198
- });
199
- }
200
- export async function deleteResourceByName({ resource, namespace, name, force = false }) {
201
- const command = `kubectl delete ${resource} ${name} -n ${namespace} --ignore-not-found=true --wait=true ${force ? '--force' : ''}`;
202
- logger.info(`command: ${command}`);
203
- const { stdout } = await execAsync(command);
204
- return stdout;
205
- }
206
- export async function deleteResourceByLabel({ resource, namespace, label, timeout = '5m', force = false }) {
207
- try {
208
- // Match both plain and group-qualified names (e.g., "podchaos" or "podchaos.chaos-mesh.org")
209
- const escaped = resource.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
210
- const regex = `(^|\\.)${escaped}(\\.|$)`;
211
- await execAsync(`kubectl api-resources --no-headers -o name | grep -Eq '${regex}'`);
212
- } catch (error) {
213
- logger.warn(`Resource type '${resource}' not found in cluster, skipping deletion ${error}`);
214
- return '';
215
- }
216
- const command = `kubectl delete ${resource} -l ${label} -n ${namespace} --ignore-not-found=true --wait=true --timeout=${timeout} ${force ? '--force' : ''}`;
217
- logger.info(`command: ${command}`);
218
- const { stdout } = await execAsync(command);
219
- return stdout;
220
- }
221
- export async function waitForResourceByLabel({ resource, label, namespace, condition = 'Ready', timeout = '10m' }) {
222
- const command = `kubectl wait ${resource} -l ${label} --for=condition=${condition} -n ${namespace} --timeout=${timeout}`;
223
- logger.info(`command: ${command}`);
224
- const { stdout } = await execAsync(command);
225
- return stdout;
226
- }
227
- export async function waitForResourceByName({ resource, name, namespace, condition = 'Ready', timeout = '10m' }) {
228
- const command = `kubectl wait ${resource}/${name} --for=condition=${condition} -n ${namespace} --timeout=${timeout}`;
229
- logger.info(`command: ${command}`);
230
- const { stdout } = await execAsync(command);
231
- return stdout;
232
- }
233
- export async function waitForResourcesByName({ resource, names, namespace, condition = 'Ready', timeout = '10m' }) {
234
- if (!names.length) {
235
- throw new Error(`No ${resource} names provided to waitForResourcesByName`);
236
- }
237
- // Wait all in parallel; if any fails, surface which one.
238
- await Promise.all(names.map(async (name)=>{
239
- try {
240
- await waitForResourceByName({
241
- resource,
242
- name,
243
- namespace,
244
- condition,
245
- timeout
246
- });
247
- } catch (err) {
248
- throw new Error(`Failed waiting for ${resource}/${name} condition=${condition} timeout=${timeout} namespace=${namespace}: ${String(err)}`);
249
- }
250
- }));
251
- }
252
- export function getChartDir(spartanDir, chartName) {
253
- return path.join(spartanDir.trim(), chartName);
254
- }
255
- function shellQuote(value) {
256
- // Single-quote safe shell escaping: ' -> '\''
257
- return `'${value.replace(/'/g, "'\\''")}'`;
258
- }
259
- function valuesToArgs(values) {
260
- return Object.entries(values).map(([key, value])=>typeof value === 'number' || typeof value === 'boolean' ? `--set ${key}=${value}` : `--set-string ${key}=${shellQuote(String(value))}`).join(' ');
261
- }
262
- function createHelmCommand({ instanceName, helmChartDir, namespace, valuesFile, timeout, values, reuseValues = false }) {
263
- const valuesFileArgs = valuesFile ? `--values ${helmChartDir}/values/${valuesFile}` : '';
264
- const reuseValuesArgs = reuseValues ? '--reuse-values' : '';
265
- return `helm upgrade --install ${instanceName} ${helmChartDir} --namespace ${namespace} ${valuesFileArgs} ${reuseValuesArgs} --wait --timeout=${timeout} ${valuesToArgs(values)}`;
266
- }
267
- async function execHelmCommand(args) {
268
- const helmCommand = createHelmCommand(args);
269
- logger.info(`helm command: ${helmCommand}`);
270
- const { stdout } = await execAsync(helmCommand);
271
- return stdout;
272
- }
273
- async function getHelmReleaseStatus(instanceName, namespace) {
274
- try {
275
- const { stdout } = await execAsync(`helm list --namespace ${namespace} --all --filter '^${instanceName}$' --output json | cat`);
276
- const parsed = JSON.parse(stdout);
277
- const row = parsed.find((r)=>r.name === instanceName);
278
- return row?.status;
279
- } catch {
280
- return undefined;
281
- }
282
- }
283
- async function forceDeleteHelmReleaseRecord(instanceName, namespace, logger) {
284
- const labelSelector = `owner=helm,name=${instanceName}`;
285
- const cmd = `kubectl delete secret -n ${namespace} -l ${labelSelector} --ignore-not-found=true`;
286
- logger.warn(`Force deleting Helm release record: ${cmd}`);
287
- await execAsync(cmd).catch(()=>undefined);
288
- }
289
- async function hasDeployedHelmRelease(instanceName, namespace) {
290
- try {
291
- const status = await getHelmReleaseStatus(instanceName, namespace);
292
- return status?.toLowerCase() === 'deployed';
293
- } catch {
294
- return false;
295
- }
296
- }
297
- export async function uninstallChaosMesh(instanceName, namespace, logger) {
298
- // uninstall the helm chart if it exists
299
- logger.info(`Uninstalling helm chart ${instanceName}`);
300
- await execAsync(`helm uninstall ${instanceName} --namespace ${namespace} --wait --ignore-not-found`);
301
- // and delete the chaos-mesh resources created by this release
302
- const deleteByLabel = async (resource)=>{
303
- const args = {
304
- resource,
305
- namespace: namespace,
306
- label: `app.kubernetes.io/instance=${instanceName}`
307
- };
308
- logger.info(`Deleting ${resource} resources for release ${instanceName}`);
309
- await deleteResourceByLabel(args).catch((e)=>{
310
- logger.error(`Error deleting ${resource}: ${e}`);
311
- logger.info(`Force deleting ${resource}`);
312
- return deleteResourceByLabel({
313
- ...args,
314
- force: true
315
- });
316
- });
317
- };
318
- await deleteByLabel('podchaos');
319
- await deleteByLabel('networkchaos');
320
- await deleteByLabel('podnetworkchaos');
321
- await deleteByLabel('workflows');
322
- await deleteByLabel('workflownodes');
323
- }
324
- /**
325
- * Installs a Helm chart with the given parameters.
326
- * @param instanceName - The name of the Helm chart instance.
327
- * @param targetNamespace - The namespace with the resources to be affected by the Helm chart.
328
- * @param valuesFile - The values file to use for the Helm chart.
329
- * @param chaosMeshNamespace - The namespace to install the Helm chart in.
330
- * @param timeout - The timeout for the Helm command.
331
- * @param clean - Whether to clean up the Helm chart before installing it.
332
- * @returns The stdout of the Helm command.
333
- * @throws If the Helm command fails.
334
- *
335
- * Example usage:
336
- * ```typescript
337
- * const stdout = await installChaosMeshChart({ instanceName: 'force-reorg', targetNamespace: 'smoke', valuesFile: 'prover-failure.yaml'});
338
- * console.log(stdout);
339
- * ```
340
- */ export async function installChaosMeshChart({ instanceName, targetNamespace, valuesFile, helmChartDir, timeout = '10m', clean = true, values = {}, logger }) {
341
- if (clean) {
342
- await uninstallChaosMesh(instanceName, targetNamespace, logger);
343
- }
344
- return execHelmCommand({
345
- instanceName,
346
- helmChartDir,
347
- namespace: targetNamespace,
348
- valuesFile,
349
- timeout,
350
- values: {
351
- ...values,
352
- 'global.targetNamespace': targetNamespace
353
- }
354
- });
355
- }
356
- export function applyProverFailure({ namespace, spartanDir, durationSeconds, logger }) {
357
- return installChaosMeshChart({
358
- instanceName: 'prover-failure',
359
- targetNamespace: namespace,
360
- valuesFile: 'prover-failure.yaml',
361
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
362
- values: {
363
- 'proverFailure.duration': `${durationSeconds}s`
364
- },
365
- logger
366
- });
367
- }
368
- export function applyValidatorFailure({ namespace, spartanDir, logger, values, instanceName }) {
369
- return installChaosMeshChart({
370
- instanceName: instanceName ?? 'validator-failure',
371
- targetNamespace: namespace,
372
- valuesFile: 'validator-failure.yaml',
373
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
374
- values,
375
- logger
376
- });
377
- }
378
- export function applyProverKill({ namespace, spartanDir, logger, values }) {
379
- return installChaosMeshChart({
380
- instanceName: 'prover-kill',
381
- targetNamespace: namespace,
382
- valuesFile: 'prover-kill.yaml',
383
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
384
- chaosMeshNamespace: namespace,
385
- clean: true,
386
- logger,
387
- values
388
- });
389
- }
390
- export function applyProverBrokerKill({ namespace, spartanDir, logger, values }) {
391
- return installChaosMeshChart({
392
- instanceName: 'prover-broker-kill',
393
- targetNamespace: namespace,
394
- valuesFile: 'prover-broker-kill.yaml',
395
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
396
- clean: true,
397
- logger,
398
- values
399
- });
400
- }
401
- export function applyBootNodeFailure({ instanceName = 'boot-node-failure', namespace, spartanDir, durationSeconds, logger, values }) {
402
- return installChaosMeshChart({
403
- instanceName,
404
- targetNamespace: namespace,
405
- valuesFile: 'boot-node-failure.yaml',
406
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
407
- values: {
408
- 'bootNodeFailure.duration': `${durationSeconds}s`,
409
- ...values ?? {}
410
- },
411
- logger
412
- });
413
- }
414
- export function applyValidatorKill({ instanceName = 'validator-kill', namespace, spartanDir, logger, values, clean = true }) {
415
- return installChaosMeshChart({
416
- instanceName: instanceName ?? 'validator-kill',
417
- targetNamespace: namespace,
418
- valuesFile: 'validator-kill.yaml',
419
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
420
- clean,
421
- logger,
422
- values
423
- });
424
- }
425
- export function applyNetworkShaping({ instanceName = 'network-shaping', valuesFile, namespace, spartanDir, logger }) {
426
- return installChaosMeshChart({
427
- instanceName,
428
- targetNamespace: namespace,
429
- valuesFile,
430
- helmChartDir: getChartDir(spartanDir, 'aztec-chaos-scenarios'),
431
- logger
432
- });
433
- }
434
- export async function awaitCheckpointNumber(rollupCheatCodes, checkpointNumber, timeoutSeconds, logger) {
435
- logger.info(`Waiting for checkpoint ${checkpointNumber}`);
436
- let tips = await rollupCheatCodes.getTips();
437
- const endTime = Date.now() + timeoutSeconds * 1000;
438
- while(tips.pending < checkpointNumber && Date.now() < endTime){
439
- logger.info(`At checkpoint ${tips.pending}`);
440
- await sleep(1000);
441
- tips = await rollupCheatCodes.getTips();
442
- }
443
- if (tips.pending < checkpointNumber) {
444
- throw new Error(`Timeout waiting for checkpoint ${checkpointNumber}, only reached ${tips.pending}`);
445
- } else {
446
- logger.info(`Reached checkpoint ${tips.pending}`);
447
- }
448
- }
449
- export async function restartBot(namespace, logger) {
450
- logger.info(`Restarting bot`);
451
- await deleteResourceByLabel({
452
- resource: 'pods',
453
- namespace,
454
- label: 'app.kubernetes.io/name=bot'
455
- });
456
- await sleep(10 * 1000);
457
- // Some bot images may take time to report Ready due to heavy boot-time proving.
458
- // Waiting for PodReadyToStartContainers ensures the pod is scheduled and starting without blocking on full readiness.
459
- await waitForResourceByLabel({
460
- resource: 'pods',
461
- namespace,
462
- label: 'app.kubernetes.io/name=bot',
463
- condition: 'PodReadyToStartContainers'
464
- });
465
- logger.info(`Bot restarted`);
466
- }
467
- /**
468
- * Installs or upgrades the transfer bot Helm release for the given namespace.
469
- * Intended for test setup to enable L2 traffic generation only when needed.
470
- */ export async function installTransferBot({ namespace, spartanDir, logger, replicas = 1, txIntervalSeconds = 10, followChain = 'PENDING', mnemonic = process.env.LABS_INFRA_MNEMONIC ?? 'test test test test test test test test test test test junk', mnemonicStartIndex, botPrivateKey = process.env.BOT_TRANSFERS_L2_PRIVATE_KEY ?? '0xcafe01', nodeUrl, timeout = '15m', reuseValues = true, aztecSlotDuration = Number(process.env.AZTEC_SLOT_DURATION ?? 12) }) {
471
- const instanceName = `${namespace}-bot-transfers`;
472
- const helmChartDir = getChartDir(spartanDir, 'aztec-bot');
473
- const resolvedNodeUrl = nodeUrl ?? `http://${namespace}-rpc-aztec-node.${namespace}.svc.cluster.local:8080`;
474
- logger.info(`Installing/upgrading transfer bot: replicas=${replicas}, followChain=${followChain}`);
475
- const values = {
476
- 'bot.replicaCount': replicas,
477
- 'bot.txIntervalSeconds': txIntervalSeconds,
478
- 'bot.followChain': followChain,
479
- 'bot.botPrivateKey': botPrivateKey,
480
- 'bot.nodeUrl': resolvedNodeUrl,
481
- 'bot.mnemonic': mnemonic,
482
- 'bot.feePaymentMethod': 'fee_juice',
483
- 'aztec.slotDuration': aztecSlotDuration,
484
- // Ensure bot can reach its own PXE started in-process (default rpc.port is 8080)
485
- // Note: since aztec-bot depends on aztec-node with alias `bot`, env vars go under `bot.node.env`.
486
- 'bot.node.env.BOT_PXE_URL': 'http://127.0.0.1:8080',
487
- // Provide L1 execution RPC for bridging fee juice
488
- 'bot.node.env.ETHEREUM_HOSTS': `http://${namespace}-eth-execution.${namespace}.svc.cluster.local:8545`,
489
- // Provide L1 mnemonic for bridging (falls back to labs mnemonic)
490
- 'bot.node.env.BOT_L1_MNEMONIC': mnemonic,
491
- // The bot does not need Kubernetes API access. Disable RBAC + ServiceAccount creation so the chart
492
- // can be installed by users without cluster-scoped RBAC permissions.
493
- 'bot.rbac.create': false,
494
- 'bot.serviceAccount.create': false,
495
- 'bot.serviceAccount.name': 'default'
496
- };
497
- // Ensure we derive a funded L1 key (index 0 is funded on anvil default mnemonic)
498
- if (mnemonicStartIndex === undefined) {
499
- values['bot.mnemonicStartIndex'] = 0;
500
- }
501
- // Also pass a funded private key directly if available
502
- if (process.env.FUNDING_PRIVATE_KEY) {
503
- values['bot.node.env.BOT_L1_PRIVATE_KEY'] = process.env.FUNDING_PRIVATE_KEY;
504
- }
505
- // Align bot image with the running network image: prefer env var, else detect from a validator pod
506
- let repositoryFromEnv;
507
- let tagFromEnv;
508
- const aztecDockerImage = process.env.AZTEC_DOCKER_IMAGE;
509
- if (aztecDockerImage && aztecDockerImage.includes(':')) {
510
- const lastColon = aztecDockerImage.lastIndexOf(':');
511
- repositoryFromEnv = aztecDockerImage.slice(0, lastColon);
512
- tagFromEnv = aztecDockerImage.slice(lastColon + 1);
513
- }
514
- let repository = repositoryFromEnv;
515
- let tag = tagFromEnv;
516
- if (!repository || !tag) {
517
- try {
518
- const { stdout } = await execAsync(`kubectl get pods -l app.kubernetes.io/name=validator -n ${namespace} -o jsonpath='{.items[0].spec.containers[?(@.name=="aztec")].image}' | cat`);
519
- const image = stdout.trim().replace(/^'|'$/g, '');
520
- if (image && image.includes(':')) {
521
- const lastColon = image.lastIndexOf(':');
522
- repository = image.slice(0, lastColon);
523
- tag = image.slice(lastColon + 1);
524
- }
525
- } catch (err) {
526
- logger.warn(`Could not detect aztec image from validator pod: ${String(err)}`);
527
- }
528
- }
529
- if (repository && tag) {
530
- values['global.aztecImage.repository'] = repository;
531
- values['global.aztecImage.tag'] = tag;
532
- }
533
- if (mnemonicStartIndex !== undefined) {
534
- values['bot.mnemonicStartIndex'] = typeof mnemonicStartIndex === 'string' ? mnemonicStartIndex : Number(mnemonicStartIndex);
535
- }
536
- // If a previous install attempt left the release in a non-deployed state (e.g. FAILED),
537
- // `helm upgrade --install` can error with "has no deployed releases".
538
- // In that case, clear the release record and do a clean install.
539
- const existingStatus = await getHelmReleaseStatus(instanceName, namespace);
540
- if (existingStatus && existingStatus.toLowerCase() !== 'deployed') {
541
- logger.warn(`Transfer bot release ${instanceName} is in status '${existingStatus}'. Reinstalling cleanly.`);
542
- await execAsync(`helm uninstall ${instanceName} --namespace ${namespace} --wait --ignore-not-found`).catch(()=>undefined);
543
- // If helm left the release in `uninstalling`, force-delete the record so we can reinstall.
544
- const afterUninstallStatus = await getHelmReleaseStatus(instanceName, namespace);
545
- if (afterUninstallStatus?.toLowerCase() === 'uninstalling') {
546
- await forceDeleteHelmReleaseRecord(instanceName, namespace, logger);
547
- }
548
- }
549
- // `--reuse-values` fails if the release has never successfully deployed (e.g. first install, or a previous failed install).
550
- // Only reuse values when we have a deployed release to reuse from.
551
- const effectiveReuseValues = reuseValues && await hasDeployedHelmRelease(instanceName, namespace);
552
- await execHelmCommand({
553
- instanceName,
554
- helmChartDir,
555
- namespace,
556
- valuesFile: undefined,
557
- timeout,
558
- values: values,
559
- reuseValues: effectiveReuseValues
560
- });
561
- if (replicas > 0) {
562
- await waitForResourceByLabel({
563
- resource: 'pods',
564
- namespace,
565
- label: 'app.kubernetes.io/name=bot',
566
- condition: 'PodReadyToStartContainers'
567
- });
568
- }
569
- }
570
- /**
571
- * Uninstalls the transfer bot Helm release from the given namespace.
572
- * Intended for test teardown to clean up bot resources.
573
- */ export async function uninstallTransferBot(namespace, logger) {
574
- const instanceName = `${namespace}-bot-transfers`;
575
- logger.info(`Uninstalling transfer bot release ${instanceName}`);
576
- await execAsync(`helm uninstall ${instanceName} --namespace ${namespace} --wait --ignore-not-found`);
577
- // Ensure any leftover pods are removed
578
- await deleteResourceByLabel({
579
- resource: 'pods',
580
- namespace,
581
- label: 'app.kubernetes.io/name=bot'
582
- }).catch(()=>undefined);
583
- }
584
- /**
585
- * Enables or disables probabilistic transaction dropping on validators and waits for rollout.
586
- * Wired to env vars P2P_DROP_TX and P2P_DROP_TX_CHANCE via Helm values.
587
- */ export async function setValidatorTxDrop({ namespace, enabled, probability, logger }) {
588
- const drop = enabled ? 'true' : 'false';
589
- const prob = String(probability);
590
- const selectors = [
591
- 'app.kubernetes.io/name=validator',
592
- 'app.kubernetes.io/component=validator',
593
- 'app=validator'
594
- ];
595
- let updated = false;
596
- for (const selector of selectors){
597
- try {
598
- const list = await execAsync(`kubectl get statefulset -l ${selector} -n ${namespace} --no-headers -o name | cat`);
599
- const names = list.stdout.split('\n').map((s)=>s.trim()).filter(Boolean);
600
- if (names.length === 0) {
601
- continue;
602
- }
603
- const cmd = `kubectl set env statefulset -l ${selector} -n ${namespace} P2P_DROP_TX=${drop} P2P_DROP_TX_CHANCE=${prob}`;
604
- logger.info(`command: ${cmd}`);
605
- await execAsync(cmd);
606
- updated = true;
607
- } catch (e) {
608
- logger.warn(`Failed to update validators with selector ${selector}: ${String(e)}`);
609
- }
610
- }
611
- if (!updated) {
612
- logger.warn(`No validator StatefulSets found in ${namespace}. Skipping tx drop toggle.`);
613
- return;
614
- }
615
- // Restart validator pods to ensure env vars take effect and wait for readiness
616
- await restartValidators(namespace, logger);
617
- }
618
- export async function restartValidators(namespace, logger) {
619
- const selectors = [
620
- 'app.kubernetes.io/name=validator',
621
- 'app.kubernetes.io/component=validator',
622
- 'app=validator'
623
- ];
624
- let any = false;
625
- for (const selector of selectors){
626
- try {
627
- const { stdout } = await execAsync(`kubectl get pods -l ${selector} -n ${namespace} --no-headers -o name | cat`);
628
- if (!stdout || stdout.trim().length === 0) {
629
- continue;
630
- }
631
- any = true;
632
- await deleteResourceByLabel({
633
- resource: 'pods',
634
- namespace,
635
- label: selector
636
- });
637
- } catch (e) {
638
- logger.warn(`Error restarting validator pods with selector ${selector}: ${String(e)}`);
639
- }
640
- }
641
- if (!any) {
642
- logger.warn(`No validator pods found to restart in ${namespace}.`);
643
- return;
644
- }
645
- // Wait for either label to be Ready
646
- for (const selector of selectors){
647
- try {
648
- await waitForResourceByLabel({
649
- resource: 'pods',
650
- namespace,
651
- label: selector
652
- });
653
- return;
654
- } catch {
655
- // try next
656
- }
657
- }
658
- logger.warn(`Validator pods did not report Ready; continuing.`);
659
- }
660
- export async function enableValidatorDynamicBootNode(instanceName, namespace, spartanDir, logger) {
661
- logger.info(`Enabling validator dynamic boot node`);
662
- await execHelmCommand({
663
- instanceName,
664
- namespace,
665
- helmChartDir: getChartDir(spartanDir, 'aztec-network'),
666
- values: {
667
- 'validator.dynamicBootNode': 'true'
668
- },
669
- valuesFile: undefined,
670
- timeout: '15m',
671
- reuseValues: true
672
- });
673
- logger.info(`Validator dynamic boot node enabled`);
674
- }
675
- export async function getSequencers(namespace) {
676
- const selectors = [
677
- 'app.kubernetes.io/name=validator',
678
- 'app.kubernetes.io/component=validator',
679
- 'app.kubernetes.io/component=sequencer-node',
680
- 'app=validator'
681
- ];
682
- for (const selector of selectors){
683
- try {
684
- const command = `kubectl get pods -l ${selector} -n ${namespace} -o jsonpath='{.items[*].metadata.name}'`;
685
- const { stdout } = await execAsync(command);
686
- const sequencers = stdout.split(' ').map((s)=>s.trim()).filter(Boolean);
687
- if (sequencers.length > 0) {
688
- logger.verbose(`Found sequencer pods ${sequencers.join(', ')} (selector=${selector})`);
689
- return sequencers;
690
- }
691
- } catch {
692
- // try next selector
693
- }
694
- }
695
- // Fail fast instead of returning [''] which leads to attempts to port-forward `pod/`.
696
- throw new Error(`No sequencer/validator pods found in namespace ${namespace}. Tried selectors: ${selectors.join(', ')}`);
697
- }
698
- export function updateSequencersConfig(env, config) {
699
- return withSequencersAdmin(env, async (client)=>{
700
- await client.setConfig(config);
701
- return client.getConfig();
702
- });
703
- }
704
- export function getSequencersConfig(env) {
705
- return withSequencersAdmin(env, (client)=>client.getConfig());
706
- }
707
- export async function withSequencersAdmin(env, fn) {
708
- const adminContainerPort = 8880;
709
- const namespace = env.NAMESPACE;
710
- const sequencers = await getSequencers(namespace);
711
- const results = [];
712
- for (const sequencer of sequencers){
713
- const { process: process1, port } = await startPortForward({
714
- resource: `pod/${sequencer}`,
715
- namespace,
716
- containerPort: adminContainerPort
717
- });
718
- const url = `http://localhost:${port}`;
719
- await retry(()=>fetch(`${url}/status`).then((res)=>res.status === 200), 'forward node admin port', makeBackoff([
720
- 1,
721
- 1,
722
- 2,
723
- 6
724
- ]), logger, true);
725
- const client = createAztecNodeAdminClient(url);
726
- results.push(await fn(client));
727
- process1.kill();
728
- }
729
- return results;
730
- }
731
- /**
732
- * Returns a public viem client to the eth execution node. If it was part of a local eth devnet,
733
- * it first port-forwards the service and points to it. Otherwise, just uses the external RPC url.
734
- */ export async function getPublicViemClient(env, /** If set, will push the new process into it */ processes) {
735
- const { NAMESPACE, CREATE_ETH_DEVNET, L1_RPC_URLS_JSON } = env;
736
- if (CREATE_ETH_DEVNET) {
737
- logger.info(`Creating port forward to eth execution node`);
738
- const { process: process1, port } = await startPortForward({
739
- resource: `svc/${NAMESPACE}-eth-execution`,
740
- namespace: NAMESPACE,
741
- containerPort: 8545
742
- });
743
- const url = `http://127.0.0.1:${port}`;
744
- const client = createPublicClient({
745
- transport: fallback([
746
- http(url, {
747
- batch: false
748
- })
749
- ])
750
- });
751
- if (processes) {
752
- processes.push(process1);
753
- }
754
- return {
755
- url,
756
- client,
757
- process: process1
758
- };
759
- } else {
760
- logger.info(`Connecting to the eth execution node at ${L1_RPC_URLS_JSON}`);
761
- if (!L1_RPC_URLS_JSON) {
762
- throw new Error(`L1_RPC_URLS_JSON is not defined`);
763
- }
764
- const client = createPublicClient({
765
- transport: fallback([
766
- http(L1_RPC_URLS_JSON, {
767
- batch: false
768
- })
769
- ])
770
- });
771
- return {
772
- url: L1_RPC_URLS_JSON,
773
- client
774
- };
775
- }
776
- }
777
- /** Queries an Aztec node for the L1 deployment addresses */ export async function getL1DeploymentAddresses(env) {
778
- let forwardProcess;
779
- try {
780
- const [sequencer] = await getSequencers(env.NAMESPACE);
781
- const { process: process1, port } = await startPortForward({
782
- resource: `pod/${sequencer}`,
783
- namespace: env.NAMESPACE,
784
- containerPort: 8080
785
- });
786
- forwardProcess = process1;
787
- const url = `http://127.0.0.1:${port}`;
788
- const node = createAztecNodeClient(url);
789
- return await retry(()=>node.getNodeInfo().then((i)=>i.l1ContractAddresses), 'get node info', makeBackoff([
790
- 1,
791
- 3,
792
- 6
793
- ]), logger);
794
- } finally{
795
- forwardProcess?.kill();
796
- }
797
- }
798
- /**
799
- * Rolls the Aztec pods in the given namespace.
800
- * @param namespace - The namespace to roll the Aztec pods in.
801
- * @param clearState - If true, also deletes the underlying PVCs to clear persistent storage.
802
- * This is required for rollup upgrades where the old state is incompatible with the new rollup.
803
- * Defaults to false, which preserves the existing storage.
804
- */ export async function rollAztecPods(namespace, clearState = false) {
805
- // Pod components use 'validator', but StatefulSets and PVCs use 'sequencer-node' for validators
806
- const podComponents = [
807
- 'p2p-bootstrap',
808
- 'prover-node',
809
- 'prover-broker',
810
- 'prover-agent',
811
- 'sequencer-node',
812
- 'rpc'
813
- ];
814
- const pvcComponents = [
815
- 'p2p-bootstrap',
816
- 'prover-node',
817
- 'prover-broker',
818
- 'sequencer-node',
819
- 'rpc'
820
- ];
821
- // StatefulSet components that need to be scaled down before PVC deletion
822
- // Note: validators use 'sequencer-node' as component label, not 'validator'
823
- const statefulSetComponents = [
824
- 'p2p-bootstrap',
825
- 'prover-node',
826
- 'prover-broker',
827
- 'sequencer-node',
828
- 'rpc'
829
- ];
830
- if (clearState) {
831
- // To delete PVCs, we must first scale down StatefulSets so pods release the volumes
832
- // Otherwise PVC deletion will hang waiting for pods to terminate
833
- // First, save original replica counts
834
- const originalReplicas = new Map();
835
- for (const component of statefulSetComponents){
836
- try {
837
- const getCmd = `kubectl get statefulset -l app.kubernetes.io/component=${component} -n ${namespace} -o jsonpath='{.items[0].spec.replicas}'`;
838
- const { stdout } = await execAsync(getCmd);
839
- const replicas = parseInt(stdout.replace(/'/g, '').trim(), 10);
840
- if (!isNaN(replicas) && replicas > 0) {
841
- originalReplicas.set(component, replicas);
842
- }
843
- } catch {
844
- // Component might not exist, continue
845
- }
846
- }
847
- // Scale down to 0
848
- for (const component of statefulSetComponents){
849
- try {
850
- const scaleCmd = `kubectl scale statefulset -l app.kubernetes.io/component=${component} -n ${namespace} --replicas=0 --timeout=2m`;
851
- logger.info(`command: ${scaleCmd}`);
852
- await execAsync(scaleCmd);
853
- } catch (e) {
854
- // Component might not exist or might be a Deployment, continue
855
- logger.verbose(`Scale down ${component} skipped: ${e}`);
856
- }
857
- }
858
- // Wait for pods to terminate
859
- await sleep(15 * 1000);
860
- // Now delete PVCs (they should no longer be in use)
861
- for (const component of pvcComponents){
862
- await deleteResourceByLabel({
863
- resource: 'persistentvolumeclaims',
864
- namespace: namespace,
865
- label: `app.kubernetes.io/component=${component}`
866
- });
867
- }
868
- // Scale StatefulSets back up to original replica counts
869
- for (const component of statefulSetComponents){
870
- const replicas = originalReplicas.get(component) ?? 1;
871
- try {
872
- const scaleCmd = `kubectl scale statefulset -l app.kubernetes.io/component=${component} -n ${namespace} --replicas=${replicas} --timeout=2m`;
873
- logger.info(`command: ${scaleCmd}`);
874
- await execAsync(scaleCmd);
875
- } catch (e) {
876
- logger.verbose(`Scale up ${component} skipped: ${e}`);
877
- }
878
- }
879
- } else {
880
- // Just delete pods (no state clearing)
881
- for (const component of podComponents){
882
- await deleteResourceByLabel({
883
- resource: 'pods',
884
- namespace: namespace,
885
- label: `app.kubernetes.io/component=${component}`
886
- });
887
- }
888
- }
889
- await sleep(10 * 1000);
890
- // Wait for pods to come back
891
- for (const component of podComponents){
892
- await waitForResourceByLabel({
893
- resource: 'pods',
894
- namespace: namespace,
895
- label: `app.kubernetes.io/component=${component}`
896
- });
897
- }
898
- }
899
- /**
900
- * Returns the absolute path to the git repository root
901
- */ export function getGitProjectRoot() {
902
- try {
903
- const rootDir = execSync('git rev-parse --show-toplevel', {
904
- encoding: 'utf-8',
905
- stdio: [
906
- 'ignore',
907
- 'pipe',
908
- 'ignore'
909
- ]
910
- }).trim();
911
- return rootDir;
912
- } catch (error) {
913
- throw new Error(`Failed to determine git project root: ${error}`);
914
- }
915
- }
916
- /** Returns a client to the RPC of the given sequencer (defaults to first) */ export async function getNodeClient(env, index = 0) {
917
- const namespace = env.NAMESPACE;
918
- const containerPort = 8080;
919
- const sequencers = await getSequencers(namespace);
920
- const sequencer = sequencers[index];
921
- if (!sequencer) {
922
- throw new Error(`No sequencer found at index ${index} in namespace ${namespace}`);
923
- }
924
- const { process: process1, port } = await startPortForward({
925
- resource: `pod/${sequencer}`,
926
- namespace,
927
- containerPort
928
- });
929
- const url = `http://localhost:${port}`;
930
- await retry(()=>fetch(`${url}/status`).then((res)=>res.status === 200), 'forward port', makeBackoff([
931
- 1,
932
- 1,
933
- 2,
934
- 6
935
- ]), logger, true);
936
- const client = createAztecNodeClient(url);
937
- return {
938
- node: client,
939
- port,
940
- process: process1
941
- };
942
- }
1
+ export * from './utils/index.js';