-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbootstrap.command.ts
More file actions
681 lines (626 loc) · 20.6 KB
/
bootstrap.command.ts
File metadata and controls
681 lines (626 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
import { Command, InvalidArgumentError } from "commander";
import { ARTIFACT_DEFAULTS } from "../../../constants/artifact-defaults.ts";
import {
ALGORITHM,
type Algorithm,
BesuGenesisService,
} from "../../../genesis/besu-genesis.service.ts";
import { NodeKeyFactory } from "../../../keys/node-key-factory.ts";
import { createCompileGenesisCommand } from "../compile-genesis/compile-genesis.command.ts";
import { createDownloadAbiCommand } from "../download-abi/download-abi.command.ts";
import { loadAbis } from "./bootstrap.abis.ts";
import { loadAllocations } from "./bootstrap.allocations.ts";
import {
type HexAddress,
promptForGenesisConfig,
} from "./bootstrap.genesis-prompts.ts";
import {
outputResult as defaultOutputResult,
type IndexedNode,
type OutputPayload,
type OutputType,
} from "./bootstrap.output.ts";
import {
createCountParser,
promptForCount,
promptForText,
} from "./bootstrap.prompt-helpers.ts";
import { loadSubgraphHash } from "./bootstrap.subgraph.ts";
type CliOptions = {
allocations?: string;
abiDirectory?: string;
acceptDefaults?: boolean;
chainId?: number;
consensus?: Algorithm;
contractSizeLimit?: number;
evmStackSize?: number;
gasLimit?: string;
gasPrice?: number;
validators?: number;
outputType?: OutputType;
secondsPerBlock?: number;
staticNodeDomain?: string;
staticNodeNamespace?: string;
staticNodePort?: number;
staticNodeDiscoveryPort?: number;
staticNodeServiceName?: string;
staticNodePodPrefix?: string;
genesisConfigmapName?: string;
staticNodesConfigmapName?: string;
faucetArtifactPrefix?: string;
subgraphHashFile?: string;
};
type BootstrapDependencies = {
factory: NodeKeyFactory;
promptForCount: typeof promptForCount;
promptForGenesis: typeof promptForGenesisConfig;
promptForText: typeof promptForText;
service: BesuGenesisService;
loadAllocations: typeof loadAllocations;
loadAbis: typeof loadAbis;
loadSubgraphHash: typeof loadSubgraphHash;
outputResult: (type: OutputType, payload: OutputPayload) => Promise<void>;
};
const DEFAULT_VALIDATOR_COUNT = 4;
const DEFAULT_STATIC_NODE_PORT = 30_303;
const {
staticNodeServiceName: DEFAULT_STATIC_NODE_SERVICE_NAME,
staticNodePodPrefix: DEFAULT_STATIC_NODE_POD_PREFIX,
genesisConfigMapName: DEFAULT_GENESIS_CONFIGMAP_NAME,
staticNodesConfigMapName: DEFAULT_STATIC_NODES_CONFIGMAP_NAME,
faucetArtifactPrefix: DEFAULT_FAUCET_ARTIFACT_PREFIX,
subgraphConfigMapName: DEFAULT_SUBGRAPH_CONFIGMAP_NAME,
} = ARTIFACT_DEFAULTS;
const OUTPUT_CHOICES: OutputType[] = ["screen", "file", "kubernetes"];
const LEADING_DOT_REGEX = /^\./u;
const UNCOMPRESSED_PUBLIC_KEY_PREFIX = "04";
const UNCOMPRESSED_PUBLIC_KEY_LENGTH = 130;
// Normalizes CLI inputs wrapped by orchestrators that keep literal quotes.
const stripSurroundingQuotes = (value: string): string => {
const trimmed = value.trim();
if (trimmed.length < 2) {
return trimmed;
}
const startsWithQuote = trimmed[0];
const endsWithQuote = trimmed.at(-1);
if (
(startsWithQuote === '"' || startsWithQuote === "'") &&
startsWithQuote === endsWithQuote
) {
return trimmed.slice(1, -1);
}
return trimmed;
};
const parsePositiveInteger = (value: string, label: string): number => {
const parsed = Number.parseInt(stripSurroundingQuotes(value), 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new InvalidArgumentError(`${label} must be a positive integer.`);
}
return parsed;
};
const parseNonNegativeInteger = (value: string, label: string): number => {
const parsed = Number.parseInt(stripSurroundingQuotes(value), 10);
if (!Number.isInteger(parsed) || parsed < 0) {
throw new InvalidArgumentError(`${label} must be a non-negative integer.`);
}
return parsed;
};
const parsePositiveBigInt = (value: string, label: string): string => {
const trimmed = stripSurroundingQuotes(value);
try {
const parsed = BigInt(trimmed);
if (parsed <= 0n) {
throw new InvalidArgumentError(`${label} must be a positive integer.`);
}
} catch (_error) {
throw new InvalidArgumentError(`${label} must be a positive integer.`);
}
return trimmed;
};
const generateGroup = (factory: NodeKeyFactory, count: number): IndexedNode[] =>
Array.from({ length: count }, (_, index) => ({
index: index + 1,
...factory.generate(),
}));
const normalizeStaticNodeDomain = (
domain: string | undefined
): string | undefined => {
if (!domain) {
return;
}
const trimmed = domain.trim().replace(LEADING_DOT_REGEX, "");
return trimmed.length === 0 ? undefined : trimmed;
};
const normalizeStaticNodeNamespace = (
namespace: string | undefined
): string | undefined => {
if (!namespace) {
return;
}
const trimmed = namespace.trim();
return trimmed.length === 0 ? undefined : trimmed;
};
type TextOptionKey =
| "staticNodeDomain"
| "staticNodeNamespace"
| "staticNodeServiceName"
| "staticNodePodPrefix"
| "genesisConfigmapName"
| "staticNodesConfigmapName"
| "faucetArtifactPrefix";
type TextOptionDescriptor<T extends TextOptionKey> = {
key: T;
flag: string;
description: string;
parser?: (value: string) => CliOptions[T];
sanitize?: (value: NonNullable<CliOptions[T]>) => CliOptions[T] | undefined;
};
const TEXT_OPTION_DESCRIPTORS: TextOptionDescriptor<TextOptionKey>[] = [
{
key: "staticNodeDomain",
flag: "--static-node-domain <domain>",
description:
"DNS suffix appended to validator peer hostnames for static-nodes entries.",
parser: stripSurroundingQuotes,
sanitize: (value) => normalizeStaticNodeDomain(value) ?? undefined,
},
{
key: "staticNodeNamespace",
flag: "--static-node-namespace <name>",
description:
"Namespace segment inserted between service name and domain for static-nodes entries.",
parser: stripSurroundingQuotes,
sanitize: (value) => normalizeStaticNodeNamespace(value) ?? undefined,
},
{
key: "staticNodeServiceName",
flag: "--static-node-service-name <name>",
description:
"Headless Service name used when constructing static-nodes hostnames.",
parser: stripSurroundingQuotes,
sanitize: (value) => stripSurroundingQuotes(value),
},
{
key: "staticNodePodPrefix",
flag: "--static-node-pod-prefix <prefix>",
description:
"StatefulSet prefix used when constructing validator pod hostnames.",
parser: stripSurroundingQuotes,
sanitize: (value) => stripSurroundingQuotes(value),
},
{
key: "genesisConfigmapName",
flag: "--genesis-configmap-name <name>",
description:
"ConfigMap name that stores the generated genesis.json payload.",
parser: stripSurroundingQuotes,
sanitize: (value) => stripSurroundingQuotes(value),
},
{
key: "staticNodesConfigmapName",
flag: "--static-nodes-configmap-name <name>",
description:
"ConfigMap name that stores the generated static-nodes.json payload.",
parser: stripSurroundingQuotes,
sanitize: (value) => stripSurroundingQuotes(value),
},
{
key: "faucetArtifactPrefix",
flag: "--faucet-artifact-prefix <prefix>",
description: "Prefix applied to faucet ConfigMaps and Secrets.",
parser: stripSurroundingQuotes,
sanitize: (value) => stripSurroundingQuotes(value),
},
];
const deriveNodeId = (publicKey: string): string => {
const trimmed = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
if (
trimmed.startsWith(UNCOMPRESSED_PUBLIC_KEY_PREFIX) &&
trimmed.length === UNCOMPRESSED_PUBLIC_KEY_LENGTH
) {
return trimmed.slice(2);
}
return trimmed;
};
const createStaticNodeEntries = (
nodes: readonly IndexedNode[],
{
namespace,
domain,
serviceName,
podPrefix,
port,
discoveryPort,
}: {
namespace?: string;
domain?: string;
serviceName: string;
podPrefix: string;
port: number;
discoveryPort: number;
}
): string[] => {
const normalizedDomain = normalizeStaticNodeDomain(domain);
const normalizedNamespace = normalizeStaticNodeNamespace(namespace);
const hostServiceName =
normalizeStaticNodeNamespace(serviceName) ?? serviceName;
const podNamePrefix = normalizeStaticNodeNamespace(podPrefix) ?? podPrefix;
return nodes.map((node) => {
// StatefulSet pod ordinals start at 0 even though our generator indexes start at 1.
const ordinal = node.index - 1;
const podName = `${podNamePrefix}-${ordinal}`;
const segments = [podName, hostServiceName];
if (normalizedNamespace) {
segments.push(normalizedNamespace);
}
if (normalizedDomain) {
segments.push(normalizedDomain);
}
const host = segments.join(".");
const nodeId = deriveNodeId(node.publicKey);
return `enode://${nodeId}@${host}:${port}?discport=${discoveryPort}`;
});
};
const runBootstrap = async (
options: CliOptions,
deps: BootstrapDependencies
): Promise<void> => {
const {
acceptDefaults = false,
allocations,
abiDirectory,
chainId,
consensus,
contractSizeLimit,
evmStackSize,
gasLimit,
gasPrice,
outputType,
secondsPerBlock,
validators: validatorOption,
staticNodeDomain: staticNodeDomainOption,
staticNodeNamespace: staticNodeNamespaceOption,
staticNodePort: staticNodePortOption,
staticNodeDiscoveryPort: staticNodeDiscoveryPortOption,
staticNodeServiceName: staticNodeServiceNameOption,
staticNodePodPrefix: staticNodePodPrefixOption,
genesisConfigmapName: genesisConfigmapNameOption,
staticNodesConfigmapName: staticNodesConfigmapNameOption,
faucetArtifactPrefix: faucetArtifactPrefixOption,
subgraphHashFile: subgraphHashFileOption,
} = options;
const resolveCount = (
label: string,
provided: number | undefined,
defaultValue: number
): Promise<number> => {
if (provided !== undefined) {
return Promise.resolve(provided);
}
if (acceptDefaults) {
return Promise.resolve(defaultValue);
}
return deps.promptForCount(label, undefined, defaultValue);
};
const resolveText = async (
label: string,
provided: string | undefined,
defaultValue: string
): Promise<string> => {
if (provided && provided.trim().length > 0) {
return provided.trim();
}
if (acceptDefaults) {
return defaultValue;
}
const response = await deps.promptForText({
defaultValue,
labelText: label,
message: label,
});
const trimmed = response.trim();
return trimmed.length === 0 ? defaultValue : trimmed;
};
const validatorsCount = await resolveCount(
"validator nodes",
validatorOption,
DEFAULT_VALIDATOR_COUNT
);
const staticNodeServiceName = await resolveText(
"Static node service name",
staticNodeServiceNameOption,
DEFAULT_STATIC_NODE_SERVICE_NAME
);
const staticNodePodPrefix = await resolveText(
"Static node pod prefix",
staticNodePodPrefixOption,
DEFAULT_STATIC_NODE_POD_PREFIX
);
const genesisConfigMapName = await resolveText(
"Genesis ConfigMap name",
genesisConfigmapNameOption,
DEFAULT_GENESIS_CONFIGMAP_NAME
);
const staticNodesConfigMapName = await resolveText(
"Static nodes ConfigMap name",
staticNodesConfigmapNameOption,
DEFAULT_STATIC_NODES_CONFIGMAP_NAME
);
const faucetArtifactPrefix = await resolveText(
"Faucet artifact prefix",
faucetArtifactPrefixOption,
DEFAULT_FAUCET_ARTIFACT_PREFIX
);
const validators = generateGroup(deps.factory, validatorsCount);
const faucet = deps.factory.generate();
const staticNodes = createStaticNodeEntries(validators, {
namespace: staticNodeNamespaceOption,
domain: staticNodeDomainOption,
serviceName: staticNodeServiceName,
podPrefix: staticNodePodPrefix,
port: staticNodePortOption ?? DEFAULT_STATIC_NODE_PORT,
discoveryPort: staticNodeDiscoveryPortOption ?? DEFAULT_STATIC_NODE_PORT,
});
const validatorAddresses = validators.map<HexAddress>((node) => node.address);
const faucetAddress: HexAddress = faucet.address;
const trimmedAbiDirectory = abiDirectory?.trim();
const allocationOverrides = allocations
? await deps.loadAllocations(allocations)
: {};
const abiArtifacts = trimmedAbiDirectory
? await deps.loadAbis(trimmedAbiDirectory)
: [];
const envSubgraphHashFile = Bun.env.SUBGRAPH_HASH_FILE?.trim();
const providedSubgraphHashFile =
subgraphHashFileOption === undefined
? undefined
: subgraphHashFileOption.trim();
let subgraphHashPath: string | undefined;
if (providedSubgraphHashFile && providedSubgraphHashFile.length > 0) {
subgraphHashPath = providedSubgraphHashFile;
} else if (envSubgraphHashFile && envSubgraphHashFile.length > 0) {
subgraphHashPath = envSubgraphHashFile;
}
const subgraphHash = subgraphHashPath
? await deps.loadSubgraphHash(subgraphHashPath)
: undefined;
const { genesis } = await deps.promptForGenesis(deps.service, {
faucetAddress,
allocations: allocationOverrides,
preset: {
algorithm: consensus,
chainId,
secondsPerBlock,
gasLimit,
gasPrice,
evmStackSize,
contractSizeLimit,
},
autoAcceptDefaults: acceptDefaults,
validatorAddresses,
});
const payload: OutputPayload = {
faucet,
genesis,
validators,
staticNodes,
artifactNames: {
faucetPrefix: faucetArtifactPrefix,
validatorPrefix: staticNodePodPrefix,
genesisConfigMapName,
staticNodesConfigMapName,
subgraphConfigMapName: DEFAULT_SUBGRAPH_CONFIGMAP_NAME,
},
abiArtifacts,
subgraphHash,
};
await deps.outputResult(outputType ?? "screen", payload);
};
/* c8 ignore start */
const defaultDependencies: BootstrapDependencies = {
factory: new NodeKeyFactory(),
promptForCount,
promptForText,
promptForGenesis: promptForGenesisConfig,
service: new BesuGenesisService(),
loadAllocations,
loadAbis,
loadSubgraphHash,
outputResult: defaultOutputResult,
};
/* c8 ignore end */
const createCliCommand = (
deps: BootstrapDependencies = defaultDependencies
): Command => {
const command = new Command();
command
.name("network-bootstrapper")
.description("Utilities for configuring Besu-based networks.");
// Keep the root command free of options so future subcommands can compose alongside generate.
const generate = command
.command("generate")
.description(
"Generate node identities, configure consensus, and emit a Besu genesis."
);
const identityParser = <T>(value: T): T => value;
for (const descriptor of TEXT_OPTION_DESCRIPTORS) {
const parser = descriptor.parser ?? identityParser;
generate.option(
descriptor.flag,
descriptor.description,
parser as (value: string) => unknown
);
}
generate
.option(
"-v, --validators <count>",
"Number of validator nodes to generate.",
createCountParser("Validators"),
DEFAULT_VALIDATOR_COUNT
)
.option(
"-a, --allocations <file>",
"Path to a genesis allocations JSON file. (default: none)"
)
.option(
"--abi-directory <path>",
"Directory containing ABI JSON files to publish as ConfigMaps.",
(value: string) => stripSurroundingQuotes(value)
)
.option(
"--subgraph-hash-file <path>",
"Path to a file containing the subgraph IPFS hash.",
(value: string) => stripSurroundingQuotes(value)
)
.option(
"-o, --outputType <type>",
`Output target (${OUTPUT_CHOICES.join(", ")}).`,
(value: string): OutputType => {
const normalized = stripSurroundingQuotes(value).toLowerCase();
if (OUTPUT_CHOICES.includes(normalized as OutputType)) {
return normalized as OutputType;
}
throw new InvalidArgumentError(
`Output type must be one of: ${OUTPUT_CHOICES.join(", ")}.`
);
},
"screen"
)
.option(
"--static-node-port <number>",
"P2P port used for static-nodes enode URIs.",
(value: string) => parsePositiveInteger(value, "Static node port"),
DEFAULT_STATIC_NODE_PORT
)
.option(
"--static-node-discovery-port <number>",
"Discovery port used for static-nodes enode URIs.",
(value: string) =>
parseNonNegativeInteger(value, "Static node discovery port"),
DEFAULT_STATIC_NODE_PORT
)
.option(
"--consensus <algorithm>",
`Consensus algorithm (${Object.values(ALGORITHM).join(", ")}). (default: ${
ALGORITHM.QBFT
})`,
(value: string): Algorithm => {
const normalized = stripSurroundingQuotes(value).toLowerCase();
const match = Object.values(ALGORITHM).find(
(candidate) => candidate.toLowerCase() === normalized
);
if (!match) {
throw new InvalidArgumentError(
`Consensus must be one of: ${Object.values(ALGORITHM).join(", ")}.`
);
}
return match;
}
)
.option(
"--chain-id <number>",
"Chain ID for the genesis config. (default: random between 40000 and 50000)",
(value: string): number => parsePositiveInteger(value, "Chain ID")
)
.option(
"--seconds-per-block <number>",
"Block time in seconds. (default: 2)",
(value: string): number =>
parsePositiveInteger(value, "Seconds per block")
)
.option(
"--gas-limit <decimal>",
"Block gas limit in decimal form. (default: 9007199254740991)",
(value: string): string => parsePositiveBigInt(value, "Gas limit")
)
.option(
"--gas-price <number>",
"Base gas price (wei). (default: 0)",
(value: string): number => parseNonNegativeInteger(value, "Gas price")
)
.option(
"--evm-stack-size <number>",
"EVM stack size limit. (default: 2048)",
(value: string): number => parsePositiveInteger(value, "EVM stack size")
)
.option(
"--contract-size-limit <number>",
"Contract size limit in bytes. (default: 2147483647)",
(value: string): number =>
parsePositiveInteger(value, "Contract size limit")
)
.option(
"--accept-defaults",
"Accept default values for all prompts when CLI flags are omitted. (default: disabled)"
)
.action(async (options: CliOptions, cmd: Command) => {
const normalizedOptions: CliOptions = {
...options,
validators:
cmd.getOptionValueSource("validators") === "default"
? undefined
: options.validators,
staticNodePort:
cmd.getOptionValueSource("staticNodePort") === "default"
? undefined
: options.staticNodePort,
staticNodeDiscoveryPort:
cmd.getOptionValueSource("staticNodeDiscoveryPort") === "default"
? undefined
: options.staticNodeDiscoveryPort,
};
for (const { key } of TEXT_OPTION_DESCRIPTORS) {
if (cmd.getOptionValueSource(key) === "default") {
normalizedOptions[key] = undefined;
}
}
const sanitizedOptions: CliOptions = {
...normalizedOptions,
allocations:
normalizedOptions.allocations === undefined
? undefined
: stripSurroundingQuotes(normalizedOptions.allocations),
abiDirectory:
normalizedOptions.abiDirectory === undefined
? undefined
: stripSurroundingQuotes(normalizedOptions.abiDirectory),
subgraphHashFile:
normalizedOptions.subgraphHashFile === undefined
? undefined
: stripSurroundingQuotes(normalizedOptions.subgraphHashFile),
};
for (const { key, sanitize } of TEXT_OPTION_DESCRIPTORS) {
const currentValue = normalizedOptions[key];
if (currentValue === undefined) {
sanitizedOptions[key] = undefined;
continue;
}
if (!sanitize) {
sanitizedOptions[key] = currentValue;
continue;
}
const sanitizedValue = sanitize(
currentValue as NonNullable<CliOptions[typeof key]>
);
sanitizedOptions[key] = (sanitizedValue ??
undefined) as CliOptions[typeof key];
}
if (sanitizedOptions.abiDirectory) {
const trimmed = sanitizedOptions.abiDirectory.trim();
sanitizedOptions.abiDirectory =
trimmed.length === 0 ? undefined : trimmed;
}
if (sanitizedOptions.subgraphHashFile) {
const trimmed = sanitizedOptions.subgraphHashFile.trim();
sanitizedOptions.subgraphHashFile =
trimmed.length === 0 ? undefined : trimmed;
}
await runBootstrap(sanitizedOptions, deps);
});
// Register subcommands from their own modules to keep the bootstrap surface composable.
command.addCommand(createCompileGenesisCommand());
command.addCommand(createDownloadAbiCommand());
return command;
};
export type { BootstrapDependencies, CliOptions };
export { createCliCommand, runBootstrap };