@typesol/cli 0.44.1 → 0.45.0

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.
package/dist/cli.js CHANGED
@@ -6,8 +6,8 @@ import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { parseArgs } from "node:util";
8
8
  import { createHash } from "node:crypto";
9
- import { build, CompileError, COMPILER_VERSION, describeToolchain, elfLength, generate, SBPF_VERSIONS, toolchainDifferences, verifyBinary, } from "./compiler/index.js";
10
- import { setToolchainStrict } from "./compiler/toolchain.js";
9
+ import { build, CompileError, COMPILER_VERSION, describeToolchain, elfLength, generate, MEASURED_HOSTS, SBPF_VERSIONS, toolchainDifferences, verifyBinary, } from "./compiler/index.js";
10
+ import { setToolchainStrict, shortClang } from "./compiler/toolchain.js";
11
11
  import { generateCpi } from "./tools/cpigen.js";
12
12
  import { generatePort } from "./tools/portgen.js";
13
13
  import { generateClient, writeClient } from "./tools/clientgen.js";
@@ -15,7 +15,8 @@ import { buildIdl } from "./compiler/idl.js";
15
15
  import { base58, decodeAddress, loadOrCreateKeypair, readKeypair } from "./keys.js";
16
16
  import { formatProfile, profileLogs } from "./tools/profile.js";
17
17
  import { TEMPLATE_NAMES } from "./templates.js";
18
- import { addProgram, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, } from "./workspace.js";
18
+ import { addProgram, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, withBuildLock, } from "./workspace.js";
19
+ import { chooseTypesolVersion, containerBuild, ensureImage, findReleaseRecord, needDocker, repeatCommand, shellQuote, sourceRevision, } from "./tools/docker.js";
19
20
  import { cliRpc, clusterUrl, deployPreflight, doctorChecks, formatChecks, INSTALL_AGAVE, rpcHost, solanaConfig as readSolanaConfig, toolchainCheck, } from "./tools/doctor.js";
20
21
  const ASSETS = fileURLToPath(new URL("../assets/", import.meta.url));
21
22
  /** A usage problem: printed with the command's help, exit code 2. */
@@ -42,6 +43,13 @@ function banner() {
42
43
  }
43
44
  const SBPF = `--sbpf v0|v1|v2 SBPF version (default v0, or "sbpf" in ${CONFIG}); v1/v2 need clusters that enabled them`;
44
45
  const TOOLCHAIN_STRICT = "--toolchain-strict refuse to build with platform-tools other than the tested ones (default: one warning); also TYPESOL_TOOLCHAIN=strict";
46
+ const DOCKER_HELP = [
47
+ "--docker build in the pinned container (docker/Dockerfile: linux/amd64, Agave 3.1.10 platform-tools v1.52,",
48
+ " the TypeSOL tarball checked against releases/<version>.json); the image is built locally the first time",
49
+ "--typesol-version <v> the TypeSOL version inside the container (default: this one; for verify, the deployed build's manifest's)",
50
+ "--release-record <file> the releases/<v>.json to check that version's tarball against (default: this package's, else the repository's)",
51
+ ].join("\n ");
52
+ const DOCKER_OPTIONS = { docker: { type: "boolean" }, "typesol-version": { type: "string" }, "release-record": { type: "string" } };
45
53
  const COMMANDS = {
46
54
  new: {
47
55
  usage: "typesol new <program> [--template counter|vault|escrow]",
@@ -108,13 +116,14 @@ const COMMANDS = {
108
116
  },
109
117
  },
110
118
  build: {
111
- usage: "typesol build [<program>…] [--sbpf v0|v1|v2] [--profile] [--toolchain-strict]\n typesol build <program.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict]",
119
+ usage: "typesol build [<program>…] [--sbpf v0|v1|v2] [--profile] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]]\n typesol build <program.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--docker …]",
112
120
  help: [
113
121
  `In a project (${CONFIG}): build every program, or the ones named, into <out>/<name>/ (.so, IDL .json, .client.ts, .c, .build.json).`,
114
122
  "Outside a project, or with a .ts file: build that file (its keypair is created next to the output if needed).",
115
123
  SBPF,
116
124
  "--profile log a marker and the remaining compute units before every statement (for `typesol profile`; not for release)",
117
125
  TOOLCHAIN_STRICT,
126
+ DOCKER_HELP,
118
127
  "--quiet no banner",
119
128
  ].join("\n "),
120
129
  options: {
@@ -124,8 +133,9 @@ const COMMANDS = {
124
133
  "program-id": { type: "string" },
125
134
  quiet: { type: "boolean" },
126
135
  "toolchain-strict": { type: "boolean" },
136
+ ...DOCKER_OPTIONS,
127
137
  },
128
- run(v, args) {
138
+ async run(v, args) {
129
139
  if (v["toolchain-strict"])
130
140
  setToolchainStrict();
131
141
  const sbpf = sbpfOf(v);
@@ -134,11 +144,28 @@ const COMMANDS = {
134
144
  const file = args.length === 1 && args[0].endsWith(".ts") ? args[0] : undefined;
135
145
  // A .ts that is one of the project's programs builds as that program (same keypair, output and settings).
136
146
  const inProject = ws && (file ? programForEntry(ws, file) : undefined);
147
+ dockerOptions(v);
137
148
  if (ws && (!file || inProject)) {
138
149
  if (v.out || v["program-id"])
139
150
  throw new UsageError(`--out and --program-id do not apply to programs of ${CONFIG} (use "out" there; keypairs live in <out>/deploy/)`);
140
151
  if (!v.quiet && process.stdout.isTTY)
141
152
  log(banner());
153
+ if (v.docker) {
154
+ const image = await buildImage(v, ws.root);
155
+ const progs = (inProject ? [inProject] : names(ws, args)).map((name) => programPaths(ws, name));
156
+ // The same locks as a local build: another process building one of these programs would write the same files.
157
+ const { jobs, built } = withBuildLocks(progs.map((p) => p.outDir), () => {
158
+ const jobs = progs.map((paths) => ({ paths, ...programAddress(ws, paths.name) }));
159
+ const built = containerBuild(image, ws.root, jobs.map((j) => ({ entry: j.paths.entry, outDir: j.paths.outDir, address: j.address, sbpf: sbpf ?? ws.sbpf, profile })));
160
+ return { jobs, built };
161
+ });
162
+ built.forEach((r, i) => {
163
+ const j = jobs[i];
164
+ log(` ${j.paths.name.padEnd(12)} ${j.address}${j.created ? " (new keypair)" : j.keyless ? " (no keypair here: deploying needs it)" : ""} ${path.relative(process.cwd(), r.soPath)}`);
165
+ });
166
+ log(containerLine(image));
167
+ return 0;
168
+ }
142
169
  for (const b of buildWorkspace(ws, inProject ? [inProject] : names(ws, args), { sbpf, profile }))
143
170
  log(` ${b.paths.name.padEnd(12)} ${b.address}${b.created ? " (new keypair)" : b.keyless ? " (no keypair here: deploying needs it)" : ""} ${path.relative(process.cwd(), b.result.soPath)}`);
144
171
  return 0;
@@ -151,23 +178,36 @@ const COMMANDS = {
151
178
  if (!v.quiet && process.stdout.isTTY)
152
179
  log(banner());
153
180
  const outDir = v.out ?? path.join(path.dirname(file), "target");
154
- const { model } = generate(file);
181
+ // The program is named after its entry file. With --docker the container's TypeSOL compiles it, not this one.
182
+ const name = v.docker ? path.basename(file).replace(/\.ts$/, "") : generate(file).model.name;
155
183
  const given = v["program-id"];
156
184
  // A keypair given by name must be there: creating one in its place would give the program a new address.
157
185
  if (given !== undefined && !existsSync(given))
158
186
  throw new UsageError(`--program-id ${given} does not exist (leave --program-id out to create a keypair next to the output)`);
159
- const keyFile = given ?? path.join(outDir, `${model.name}-keypair.json`);
187
+ const keyFile = given ?? path.join(outDir, `${name}-keypair.json`);
188
+ const image = v.docker ? await buildImage(v, ws?.root) : undefined;
160
189
  mkdirSync(path.dirname(keyFile), { recursive: true });
161
190
  const { address, created } = loadOrCreateKeypair(keyFile);
162
- const res = build(file, outDir, address, { sbpf: sbpf ?? "v0", profile });
163
- const client = writeClient(res.idl, path.join(outDir, `${model.name}.client.ts`));
164
- log(` program ${model.name}`);
191
+ let res;
192
+ if (image) {
193
+ // The container sees the entry's directory: the program and the files it imports from there.
194
+ const [r] = containerBuild(image, path.dirname(path.resolve(file)), [{ entry: file, outDir, address, sbpf: sbpf ?? "v0", profile }]);
195
+ res = { soPath: r.soPath, idlPath: path.join(outDir, `${name}.json`), manifestPath: r.manifestPath };
196
+ }
197
+ else {
198
+ const local = build(file, outDir, address, { sbpf: sbpf ?? "v0", profile });
199
+ writeClient(local.idl, path.join(outDir, `${name}.client.ts`));
200
+ res = local;
201
+ }
202
+ log(` program ${name}`);
165
203
  log(` address ${address}${created ? " (new keypair: keep it, it is the program's address)" : ""}`);
166
204
  log(` binary ${res.soPath}`);
167
205
  log(` idl ${res.idlPath}`);
168
- log(` client ${client.path}`);
206
+ log(` client ${path.join(outDir, `${name}.client.ts`)}`);
169
207
  log(` manifest ${res.manifestPath}`);
170
208
  log(`\n deploy: solana program deploy ${shellQuote(res.soPath)} --program-id ${shellQuote(keyFile)}`);
209
+ if (image)
210
+ log(containerLine(image));
171
211
  return 0;
172
212
  },
173
213
  },
@@ -449,7 +489,7 @@ const COMMANDS = {
449
489
  },
450
490
  },
451
491
  verify: {
452
- usage: "typesol verify <program.ts | program> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <solana cli config>] [--sbpf v0|v1|v2] [--manifest <name.build.json>]",
492
+ usage: "typesol verify <program.ts | program> [<deployed.so>] [--address <program id>] [--url <rpc>] [--config <solana cli config>] [--sbpf v0|v1|v2] [--manifest <name.build.json>] [--docker [--typesol-version <v>] [--release-record <file>]]",
453
493
  help: [
454
494
  "Rebuild and compare with what is deployed. Exit 0 on a match, 3 on a mismatch.",
455
495
  "With a .so (e.g. from `solana program dump`): compare with that file.",
@@ -462,9 +502,20 @@ const COMMANDS = {
462
502
  "manifest whose binary hash is the deployed one's (--manifest, <deployed>.build.json next to a given .so, or the",
463
503
  "local build's). A program on chain carries no record of what built it: keep the .build.json with the deployment.",
464
504
  "--manifest <file> the <name>.build.json of the build that was deployed",
505
+ "With --docker the rebuild runs in the pinned container, with the TypeSOL version of the deployed build's manifest",
506
+ "(when one is known) unless --typesol-version is given; on a match it prints what was verified, for anyone to repeat.",
507
+ DOCKER_HELP,
465
508
  ].join("\n "),
466
- options: { sbpf: { type: "string" }, address: { type: "string" }, url: { type: "string" }, config: { type: "string" }, manifest: { type: "string" } },
509
+ options: {
510
+ sbpf: { type: "string" },
511
+ address: { type: "string" },
512
+ url: { type: "string" },
513
+ config: { type: "string" },
514
+ manifest: { type: "string" },
515
+ ...DOCKER_OPTIONS,
516
+ },
467
517
  async run(v, args) {
518
+ dockerOptions(v);
468
519
  if (args.length < 1 || args.length > 2)
469
520
  throw new UsageError("verify takes the program and, optionally, the deployed .so");
470
521
  const [target, deployedPath] = args;
@@ -503,31 +554,48 @@ const COMMANDS = {
503
554
  // ELF e_flags (offset 0x30) hold the SBPF version: 0 for v0, 1 for v1, 2 for v2.
504
555
  const flags = deployed.length > 0x34 && deployed.readUInt32BE(0) === 0x7f454c46 ? deployed.readUInt32LE(0x30) : 0;
505
556
  const sbpf = sbpfOf(v) ?? SBPF_VERSIONS[flags] ?? "v0";
557
+ const programName = path.basename(entry).replace(/\.ts$/, "");
558
+ // The rebuild's own output directory is temporary; the local build's manifest sits in the usual place.
559
+ const local = ws && name ? programPaths(ws, name).outDir : path.join(path.dirname(entry), "target");
560
+ const candidates = [
561
+ v.manifest,
562
+ deployedPath ? deployedPath.replace(/\.so$/, "") + ".build.json" : undefined,
563
+ path.join(local, `${programName}.build.json`),
564
+ ].filter((f) => !!f);
565
+ const known = buildManifests(deployed, candidates);
566
+ const address = onChain?.address ?? "11111111111111111111111111111111";
506
567
  const dir = mkdtempSync(path.join(os.tmpdir(), "typesol-verify-"));
507
- let res, same;
568
+ let rebuilt, idl, same;
569
+ let image;
570
+ let root;
508
571
  try {
509
- res = build(entry, dir, onChain?.address ?? "11111111111111111111111111111111", { sbpf });
510
- same = verifyBinary(deployed, readFileSync(res.soPath));
572
+ if (v.docker) {
573
+ image = await buildImage(v, ws?.root, known.deployed ? { version: known.deployed.manifest.compiler, from: relPath(known.deployed.file) } : undefined);
574
+ root = ws && name ? ws.root : path.dirname(path.resolve(entry));
575
+ const [r] = containerBuild(image, root, [{ entry, outDir: dir, address, sbpf }]);
576
+ rebuilt = r.manifest;
577
+ idl = JSON.parse(readFileSync(path.join(dir, `${r.name}.json`), "utf8"));
578
+ same = verifyBinary(deployed, readFileSync(r.soPath));
579
+ }
580
+ else {
581
+ const res = build(entry, dir, address, { sbpf });
582
+ rebuilt = res.manifest;
583
+ idl = res.idl;
584
+ same = verifyBinary(deployed, readFileSync(res.soPath));
585
+ }
511
586
  }
512
587
  finally {
513
588
  rmSync(dir, { recursive: true, force: true });
514
589
  }
515
590
  const what = deployedPath ??
516
591
  `${onChain.address} (${onChain.info.dataAccount === onChain.address ? "" : `data ${onChain.info.dataAccount}, `}loader ${onChain.info.loader})`;
517
- log(same
518
- ? ` match ${res.manifest.binary} (sbpf ${sbpf})`
519
- : ` MISMATCH ${what} is not what ${entry} builds to (${res.manifest.binary}, sbpf ${sbpf})`);
520
- if (!same) {
521
- // The rebuild's own output directory was temporary; the local build's manifest sits in the usual place.
522
- const local = ws && name ? programPaths(ws, name).outDir : path.join(path.dirname(entry), "target");
523
- const candidates = [
524
- v.manifest,
525
- deployedPath ? deployedPath.replace(/\.so$/, "") + ".build.json" : undefined,
526
- path.join(local, `${res.manifest.program}.build.json`),
527
- ].filter((f) => !!f);
528
- for (const line of toolchainHint(res.manifest, deployed, candidates, !!v.manifest))
592
+ log(same ? ` match ${rebuilt.binary} (sbpf ${sbpf})` : ` MISMATCH ${what} is not what ${entry} builds to (${rebuilt.binary}, sbpf ${sbpf})`);
593
+ if (same && image && root)
594
+ for (const line of verifiedLines({ what, entry, root, rebuilt, image, args, v }))
595
+ log(line);
596
+ if (!same)
597
+ for (const line of toolchainHint(rebuilt, known, !!v.manifest))
529
598
  log(line);
530
- }
531
599
  if (!onChain)
532
600
  return same ? 0 : 3;
533
601
  const { info } = onChain;
@@ -549,7 +617,7 @@ const COMMANDS = {
549
617
  log(` IDL ERROR the IDL at ${at} could not be read: ${e.message}`);
550
618
  return 3;
551
619
  }
552
- const idlSame = canonicalJson(published) === canonicalJson(res.idl);
620
+ const idlSame = canonicalJson(published) === canonicalJson(idl);
553
621
  log(idlSame
554
622
  ? " idl match: the published IDL is the one the source builds"
555
623
  : " IDL MISMATCH the published IDL differs from the one the source builds");
@@ -672,16 +740,13 @@ function mustExist(file) {
672
740
  return file;
673
741
  }
674
742
  /**
675
- * After a verify mismatch: the toolchain of the rebuild and, when a build manifest describes the deployed bytes (its
676
- * binary hash is theirs), of the deployed build, and what differs. A manifest that describes other bytes (an older
677
- * local build) is only mentioned: its toolchain says nothing about the deployed binary.
743
+ * The build manifests among `candidates` (files that may not exist): the one whose binary hash is the deployed bytes'
744
+ * (it describes the deployed build), and the others, which describe other binaries (an older local build).
678
745
  */
679
- function toolchainHint(rebuilt, deployed, candidates, explicit) {
680
- const lines = [` rebuilt ${describeToolchain(rebuilt)}`];
746
+ function buildManifests(deployed, candidates) {
681
747
  const deployedHash = createHash("sha256")
682
748
  .update(deployed.subarray(0, elfLength(deployed)))
683
749
  .digest("hex");
684
- let other;
685
750
  const unrelated = [];
686
751
  for (const file of [...new Set(candidates.map((c) => path.resolve(c)))]) {
687
752
  if (!existsSync(file))
@@ -695,33 +760,114 @@ function toolchainHint(rebuilt, deployed, candidates, explicit) {
695
760
  }
696
761
  if (typeof manifest?.clang !== "string" || typeof manifest.binary !== "string")
697
762
  continue;
698
- if (manifest.binary === deployedHash) {
699
- other = { file, manifest };
700
- break;
701
- }
763
+ if (manifest.binary === deployedHash)
764
+ return { deployed: { file, manifest }, unrelated };
702
765
  unrelated.push({ file, manifest });
703
766
  }
704
- const rel = (f) => path.relative(process.cwd(), f) || f;
767
+ return { unrelated };
768
+ }
769
+ /** A path as the user would type it here: relative below the working directory, absolute elsewhere. */
770
+ const relPath = (f) => {
771
+ const rel = path.relative(process.cwd(), f);
772
+ return !rel ? f : rel.startsWith("..") || path.isAbsolute(rel) ? path.resolve(f) : rel;
773
+ };
774
+ /**
775
+ * After a verify mismatch: the toolchain of the rebuild and, when a build manifest describes the deployed bytes (its
776
+ * binary hash is theirs), of the deployed build, and what differs. A manifest that describes other bytes (an older
777
+ * local build) is only mentioned: its toolchain says nothing about the deployed binary.
778
+ */
779
+ function toolchainHint(rebuilt, known, explicit) {
780
+ const lines = [` rebuilt ${describeToolchain(rebuilt)}`];
781
+ const other = known.deployed;
705
782
  if (other) {
706
- lines.push(` deployed ${describeToolchain(other.manifest)} (${rel(other.file)}, whose binary hash is the deployed one's)`);
783
+ lines.push(` deployed ${describeToolchain(other.manifest)} (${relPath(other.file)}, whose binary hash is the deployed one's)`);
707
784
  const diff = toolchainDifferences(rebuilt, other.manifest);
785
+ const why = diff.includes("clang")
786
+ ? "another clang can compile the same C to other bytes; "
787
+ : diff.includes("host")
788
+ ? "the host may be the cause if the program uses 128-bit or signed division: before 0.45.0 those linked platform-tools' compiler-builtins, laid out differently by each host package; "
789
+ : diff.includes("host (not measured)")
790
+ ? `the same bytes on another host were measured only on ${MEASURED_HOSTS.join(", ")}; `
791
+ : "";
792
+ const fix = diff.length === 1 && diff[0].startsWith("host")
793
+ ? other.manifest.container
794
+ ? "rebuild with --docker, as the deployed build was"
795
+ : `rebuild on a ${other.manifest.host.os}-${other.manifest.host.arch} host, or deploy a --docker build so that anyone can rebuild it`
796
+ : `rebuild with the deployed side's ${diff.join(" and ")} to compare like with like`;
708
797
  lines.push(diff.length
709
- ? ` differs ${diff.join(", ")}: ${diff.includes("clang") ? "another clang can compile the same C to other bytes; " : ""}rebuild with the deployed side's ${diff.join(" and ")} to compare like with like`
798
+ ? ` differs ${diff.join(", ")}: ${why}${fix}`
710
799
  : " same toolchain and compiler versions on both sides: the sources (or an import, or the runtime header) differ");
711
800
  return lines;
712
801
  }
713
802
  lines.push(" deployed toolchain unknown: a deployed program records nothing about what built it" +
714
803
  (explicit ? "" : "; pass --manifest <name>.build.json, kept from the build that was deployed"));
715
- for (const u of unrelated) {
804
+ for (const u of known.unrelated) {
716
805
  const diff = toolchainDifferences(rebuilt, u.manifest);
717
- lines.push(` note ${rel(u.file)} describes another binary (${u.manifest.binary.slice(0, 12)}…, ${describeToolchain(u.manifest)})` +
806
+ lines.push(` note ${relPath(u.file)} describes another binary (${u.manifest.binary.slice(0, 12)}…, ${describeToolchain(u.manifest)})` +
718
807
  (diff.length ? `; it differs from the rebuild in ${diff.join(", ")}` : ""));
719
808
  }
720
809
  return lines;
721
810
  }
722
- /** Quote a command-line word for a POSIX shell when it needs it. */
723
- function shellQuote(s) {
724
- return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
811
+ /** After a container verify matched: what was verified, in terms a third party can repeat. */
812
+ function verifiedLines(o) {
813
+ const id = o.image.identity;
814
+ const rev = sourceRevision(o.root);
815
+ return [
816
+ ` verified ${o.what} is what ${relPath(path.resolve(o.entry))} builds to in the pinned build container:`,
817
+ ` source ${o.root}${rev ? ` (git ${rev.commit}${rev.clean ? "" : ", with uncommitted changes"})` : " (not a git checkout)"}`,
818
+ ` TypeSOL ${id.typesol.version}, npm tarball shasum ${id.typesol.shasum}, as releases/${id.typesol.version}.json records it (the record names commit ${id.typesol.commit})`,
819
+ ` record ${recordLine(id.typesol.record) ?? `releases/${id.typesol.version}.json`}`,
820
+ ...(id.deps
821
+ ? [
822
+ ` deps ${id.deps.path} sha256 ${id.deps.sha256} (${id.deps.source === "package" ? "this package's" : "the checked tarball's"}), installed with npm ci`,
823
+ ]
824
+ : []),
825
+ ` toolchain ${shortClang(o.rebuilt.clang)}, platform-tools ${o.rebuilt.platformTools ?? "unknown"}, TypeScript ${o.rebuilt.typescript}`,
826
+ ` container ${id.platform}, Dockerfile sha256 ${id.dockerfile}, local image ${id.image}`,
827
+ ...id.base.map((b) => ` base ${b}`),
828
+ ...id.downloads.map((d) => ` download ${d.url.split("/").pop()} sha256 ${d.sha256}`),
829
+ ` repeat ${repeatCommand(o.args, o.v, id.typesol.version)}`,
830
+ ];
831
+ }
832
+ /** Where a container build's release record came from, in one line. */
833
+ function recordLine(r) {
834
+ if (!r)
835
+ return undefined;
836
+ const where = r.kind === "package"
837
+ ? `${r.location} in this package`
838
+ : r.kind === "file"
839
+ ? `${r.location} (--release-record)`
840
+ : `${r.location} (the repository's main branch)`;
841
+ return `${where}, sha256 ${r.sha256}`;
842
+ }
843
+ /** --typesol-version and --release-record only mean something with --docker. */
844
+ function dockerOptions(v) {
845
+ for (const o of ["typesol-version", "release-record"])
846
+ if (v[o] !== undefined && !v.docker)
847
+ throw new UsageError(`--${o} applies to container builds: add --docker`);
848
+ }
849
+ /**
850
+ * The build image for --docker, built first if needed, with the TypeSOL version chosen for it (said on stderr). The
851
+ * version's release record is this package's, the --release-record file, or (a release newer than this package) the
852
+ * repository's.
853
+ */
854
+ async function buildImage(v, projectRoot, deployed) {
855
+ const { version, why } = chooseTypesolVersion({ given: v["typesol-version"], deployed, projectRoot, cliVersion: COMPILER_VERSION });
856
+ needDocker(); // before any download: without Docker there is nothing to check a record for
857
+ const found = await findReleaseRecord(version, { file: v["release-record"] });
858
+ const image = ensureImage(version, found);
859
+ console.error(` container ${image.tag}: TypeSOL ${version} (${why}), ${image.identity.platform}`);
860
+ return image;
861
+ }
862
+ /** The container build's environment in one line, for the build's report. */
863
+ function containerLine(image) {
864
+ const id = image.identity;
865
+ return ` built in ${id.platform} container ${image.tag} (Dockerfile sha256 ${id.dockerfile.slice(0, 16)}…, TypeSOL ${id.typesol.version} tarball ${id.typesol.shasum}${id.deps ? `, dependency lock ${id.deps.sha256.slice(0, 16)}…` : ""}); recorded in each .build.json`;
866
+ }
867
+ /** Hold the build lock of every directory while `fn` runs (one container builds them all). */
868
+ function withBuildLocks(dirs, fn) {
869
+ const [first, ...rest] = [...new Set(dirs)].sort();
870
+ return first === undefined ? fn() : withBuildLock(first, () => withBuildLocks(rest, fn));
725
871
  }
726
872
  function one(args, what) {
727
873
  if (args.length !== 1)
@@ -37,6 +37,54 @@ export interface BuildManifest {
37
37
  sources: Record<string, string>;
38
38
  /** sha256 of the .so. */
39
39
  binary: string;
40
+ /** Set when the build ran in the pinned container (`typesol build --docker`, after 0.44.0): what that environment is. */
41
+ container?: ContainerIdentity;
42
+ }
43
+ /**
44
+ * The build container of `--docker` (docker/Dockerfile): everything that decides what is inside it, so that another
45
+ * machine can build the same environment and compare. `image` is this machine's local image id; it can differ between
46
+ * machines that built the same Dockerfile (layer dates), so it identifies the image used, not the environment.
47
+ */
48
+ export interface ContainerIdentity {
49
+ /** The container platform: `linux/amd64` (before 0.45.0 some programs' binaries depended on the platform-tools host package). */
50
+ platform: string;
51
+ /** sha256 of docker/Dockerfile. */
52
+ dockerfile: string;
53
+ /** The local image id (`sha256:…`). */
54
+ image: string;
55
+ /** The base images, each pinned by digest (`node:24.22.2-bookworm-slim@sha256:…`). */
56
+ base: string[];
57
+ /** The Agave and platform-tools release files, with the sha256 the Dockerfile requires of them. */
58
+ downloads: {
59
+ url: string;
60
+ sha256: string;
61
+ }[];
62
+ /**
63
+ * The TypeSOL package installed in the image, as its release record (releases/<version>.json) describes it, and where
64
+ * that record came from (this package, a --release-record file, or the repository's main branch) with its sha256
65
+ * (recorded from 0.45.0 on).
66
+ */
67
+ typesol: {
68
+ version: string;
69
+ shasum: string;
70
+ integrity: string;
71
+ commit: string;
72
+ record?: {
73
+ kind: "package" | "file" | "repository";
74
+ location: string;
75
+ sha256: string;
76
+ };
77
+ };
78
+ /**
79
+ * The TypeSOL package's npm dependencies, installed by `npm ci` from this lock (every package checked against the
80
+ * integrity it records): `docker/deps/<version>.lock.json`, its sha256, and whether it came from the running
81
+ * package or from the version's own (checked) tarball (recorded from 0.45.0 on).
82
+ */
83
+ deps?: {
84
+ path: string;
85
+ sha256: string;
86
+ source: "package" | "tarball";
87
+ };
40
88
  }
41
89
  export interface BuildResult extends Generated {
42
90
  manifest: BuildManifest;
@@ -54,9 +102,11 @@ export declare function build(entry: string, outDir: string, programAddress: str
54
102
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
55
103
  export declare const COMPILER_VERSION: string;
56
104
  /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
57
- export declare function describeToolchain(m: Pick<BuildManifest, "clang" | "platformTools" | "host" | "compiler">): string;
105
+ export declare function describeToolchain(m: Pick<BuildManifest, "clang" | "platformTools" | "host" | "compiler" | "container">): string;
58
106
  /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
59
107
  export declare function toolchainDifferences(a: Partial<BuildManifest>, b: Partial<BuildManifest>): string[];
108
+ /** The hosts (`<os>-<arch>`) on which programs were measured to build to the same bytes (docs/stability.md). */
109
+ export declare const MEASURED_HOSTS: readonly string[];
60
110
  /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
61
111
  export declare function elfLength(elf: Buffer): number;
62
112
  /**
@@ -8,7 +8,7 @@ import { hintForTypeScript } from "./hints.js";
8
8
  import { emitProgram } from "./emit/index.js";
9
9
  import { buildIdl } from "./idl.js";
10
10
  import { buildSharedObject, checkToolchain, shortClang, TESTED_TOOLCHAIN } from "./toolchain.js";
11
- import { RUNTIME_DIR } from "./toolchain.js";
11
+ import { BUILTINS_SOURCE, RUNTIME_DIR } from "./toolchain.js";
12
12
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
13
13
  export { SBPF_VERSIONS, TESTED_TOOLCHAIN } from "./toolchain.js";
14
14
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
@@ -43,6 +43,7 @@ export function build(entry, outDir, programAddress, opts = {}) {
43
43
  for (const f of gen.files)
44
44
  sources[path.relative(root, f)] = sha256(readFileSync(f));
45
45
  sources["<runtime>/typesol_rt.h"] = sha256(readFileSync(path.join(RUNTIME_DIR, "typesol_rt.h")));
46
+ sources["<runtime>/typesol_builtins.c"] = sha256(readFileSync(BUILTINS_SOURCE));
46
47
  const manifest = {
47
48
  program: gen.model.name,
48
49
  compiler: COMPILER_VERSION,
@@ -69,6 +70,7 @@ export function describeToolchain(m) {
69
70
  m.host ? `${m.host.os}-${m.host.arch}` : "host unknown",
70
71
  `TypeSOL ${m.compiler}`,
71
72
  ...(m.clang === TESTED_TOOLCHAIN.clang ? ["the tested toolchain"] : []),
73
+ ...(m.container ? [`in the build container (Dockerfile ${m.container.dockerfile.slice(0, 12)}…)`] : []),
72
74
  ].join(", ");
73
75
  }
74
76
  /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
@@ -84,9 +86,22 @@ export function toolchainDifferences(a, b) {
84
86
  out.push("TypeScript");
85
87
  if (a.sbpf !== b.sbpf)
86
88
  out.push("SBPF version");
87
- // The host is recorded, not compared: one clang version is meant to give the same bytes on every host.
89
+ // The same clang gives the same object code on each host measured. Before 0.45.0 programs linked platform-tools'
90
+ // compiler-builtins, which each host package splits into archive members differently, so one with 128-bit or signed
91
+ // division linked to another layout on another host; a build that links the runtime's builtins (its manifest lists
92
+ // them among the sources) gives the same bytes on each host measured (docs/stability.md). Between two such builds
93
+ // the host is not a difference when both hosts were measured, and "host (not measured)" when one was not.
94
+ const linksRuntimeBuiltins = (m) => !!m.sources?.["<runtime>/typesol_builtins.c"];
95
+ if (a.host && b.host && (a.host.os !== b.host.os || a.host.arch !== b.host.arch)) {
96
+ if (!(linksRuntimeBuiltins(a) && linksRuntimeBuiltins(b)))
97
+ out.push("host");
98
+ else if (!MEASURED_HOSTS.includes(`${a.host.os}-${a.host.arch}`) || !MEASURED_HOSTS.includes(`${b.host.os}-${b.host.arch}`))
99
+ out.push("host (not measured)");
100
+ }
88
101
  return out;
89
102
  }
103
+ /** The hosts (`<os>-<arch>`) on which programs were measured to build to the same bytes (docs/stability.md). */
104
+ export const MEASURED_HOSTS = ["darwin-arm64", "linux-arm64", "linux-x64"];
90
105
  /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
91
106
  export function elfLength(elf) {
92
107
  if (elf.length < 0x40 || elf.readUInt32BE(0) !== 0x7f454c46)
@@ -9,14 +9,37 @@ export interface Toolchain {
9
9
  linkerScript: string;
10
10
  includes: string[];
11
11
  libDir: string;
12
+ /**
13
+ * platform-tools' compiler-builtins Rust library for this SBPF version. Not linked (programs link the runtime's own
14
+ * builtins, runtime/typesol_builtins.c, which build the same on each host measured); its presence tells that the
15
+ * platform-tools have this SBPF version's libraries, and the builtins tests compare against it.
16
+ */
12
17
  compilerBuiltins: string;
13
18
  }
19
+ /** The runtime's compiler builtins, compiled with each program and linked in place of compiler-builtins. */
20
+ export declare const BUILTINS_SOURCE: string;
14
21
  /** Locate the Solana C SDK that ships with the Agave CLI's platform-tools. */
15
22
  export declare function findToolchain(sbpf?: Sbpf): Toolchain;
16
23
  /** Compile generated C to an SBF shared object (same flags as the SDK's sbf.mk for the chosen SBPF version). */
17
24
  /** The SBF stack frame of one function. */
18
25
  export declare const STACK_FRAME = 4096;
26
+ /** clang's flags for SBF objects (the SDK's sbf.mk for the chosen SBPF version, plus TypeSOL's warnings). */
27
+ export declare function sbfCflags(sbpf?: Sbpf): string[];
28
+ /** The flags runtime/typesol_builtins.c is compiled with: the program's, and the SBPF version (its assembly differs). */
29
+ export declare function builtinsCflags(sbpf?: Sbpf): string[];
19
30
  export declare function buildSharedObject(cFile: string, outSo: string, sbpf?: Sbpf, tc?: Toolchain): void;
31
+ /** Link SBF objects into a program: libc from platform-tools, nothing from its Rust libraries. */
32
+ export declare function linkSharedObject(objects: string[], outSo: string, tc: Toolchain, extra?: string[]): void;
33
+ /**
34
+ * The syscalls a TypeSOL program may leave to the SBF loader: every one the SDK's headers declare (`@SYSCALL` in
35
+ * platform-tools-sdk/sbf/c/inc/sol/inc/*.inc) and every one runtime/typesol_rt.h declares itself, with `abort`.
36
+ * test/cli/toolchain.test.ts checks that this is exactly that set.
37
+ */
38
+ export declare const SYSCALLS: readonly string[];
39
+ /** Whether the SBF loader resolves `name` as a syscall for a TypeSOL program (one of SYSCALLS). */
40
+ export declare function isSyscall(name: string): boolean;
41
+ /** The undefined symbols of an SBF shared object's dynamic symbol table (what the loader resolves as syscalls). */
42
+ export declare function unresolvedSymbols(elf: Buffer): string[];
20
43
  /**
21
44
  * The toolchain this release is tested with: CI installs exactly this Agave CLI and platform-tools, and every
22
45
  * execution, differential and fuzz test runs on binaries this clang built. The C TypeSOL emits is only checked