@typesol/cli 0.44.0 → 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.
Files changed (47) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/NOTICE +14 -1
  3. package/README.md +52 -10
  4. package/SECURITY.md +1 -1
  5. package/dist/cli.js +194 -48
  6. package/dist/compiler/emit/alias.d.ts +16 -2
  7. package/dist/compiler/emit/alias.js +62 -4
  8. package/dist/compiler/emit/calls.js +15 -7
  9. package/dist/compiler/emit/cpi-core.d.ts +6 -0
  10. package/dist/compiler/emit/cpi-core.js +18 -5
  11. package/dist/compiler/emit/create.js +19 -11
  12. package/dist/compiler/emit/function.js +5 -5
  13. package/dist/compiler/emit/metaplex.js +17 -4
  14. package/dist/compiler/emit/token.js +64 -39
  15. package/dist/compiler/index.d.ts +51 -1
  16. package/dist/compiler/index.js +17 -2
  17. package/dist/compiler/toolchain.d.ts +23 -0
  18. package/dist/compiler/toolchain.js +128 -8
  19. package/dist/tools/docker.d.ts +183 -0
  20. package/dist/tools/docker.js +442 -0
  21. package/dist/tools/doctor.d.ts +3 -0
  22. package/dist/tools/doctor.js +12 -0
  23. package/dist/workspace.d.ts +2 -1
  24. package/dist/workspace.js +33 -6
  25. package/docker/Dockerfile +163 -0
  26. package/docker/deps/0.43.0.lock.json +1206 -0
  27. package/docker/deps/0.44.0.lock.json +1206 -0
  28. package/docker/deps/0.44.1.lock.json +1206 -0
  29. package/docker/deps/0.45.0.lock.json +1206 -0
  30. package/docs/architecture.md +13 -5
  31. package/docs/audit.md +54 -7
  32. package/docs/cli.md +31 -4
  33. package/docs/errors.md +1 -1
  34. package/docs/language.md +6 -4
  35. package/docs/mainnet.md +86 -6
  36. package/docs/security-model.md +47 -12
  37. package/docs/stability.md +62 -3
  38. package/docs/testing.md +49 -2
  39. package/docs/troubleshooting.md +46 -0
  40. package/llms-full.txt +283 -34
  41. package/package.json +3 -1
  42. package/releases/0.43.0.json +669 -0
  43. package/releases/0.44.0.json +672 -0
  44. package/releases/0.44.1.json +672 -0
  45. package/runtime/LICENSE-compiler-builtins.txt +275 -0
  46. package/runtime/typesol_builtins.c +484 -0
  47. package/runtime/typesol_rt.h +8 -5
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)
@@ -15,7 +15,9 @@ import { EmitterBase } from "./base.js";
15
15
  * assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
16
16
  *
17
17
  * Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
18
- * unless `Dup<…>` allows it for in-place accounts.
18
+ * unless `Dup<…>` allows it for in-place accounts. Where data moves (a Vec resized, an account given to a helper:
19
+ * `moves`), `assertNotAliased` also treats the names that may be one account (`maySharePlace`: a Dup pair, a
20
+ * read-only and a writable account of one type, a loaded struct) as one, since the data moves under each of them.
19
21
  */
20
22
  export declare abstract class AliasEmitter extends EmitterBase {
21
23
  /**
@@ -38,7 +40,19 @@ export declare abstract class AliasEmitter extends EmitterBase {
38
40
  * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
39
41
  * value. Refuse when a live reference into the replaced place is still used afterwards.
40
42
  */
41
- protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string, inPlace?: boolean): void;
43
+ protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string, inPlace?: boolean, moves?: boolean): void;
44
+ /**
45
+ * A reference path (`a.entries[]`) inside one of the `replaced` places named through another root that may be the
46
+ * same account (`b.entries` when `a` and `b` may be one account): the path, the two roots and why.
47
+ */
48
+ private sharedPlace;
49
+ /**
50
+ * Whether two reference roots may name one account's data, read in place: both structs of one type (a struct
51
+ * account parameter or group field not `@layout borsh`, or a struct loaded with loadAccount / loadAccountMut), and
52
+ * accounts the entry checks do not keep apart (`mayBeSameAccount`: a Dup<…> or read-only one, a helper's). Returns
53
+ * why, for the message.
54
+ */
55
+ protected maySharePlace(a: string, b: string): string | undefined;
42
56
  /**
43
57
  * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
44
58
  * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
@@ -17,7 +17,9 @@ const TREE_NODE_METHODS = new Set(["min", "max", "nodeAt", "remove", "removeAt"]
17
17
  * assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
18
18
  *
19
19
  * Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
20
- * unless `Dup<…>` allows it for in-place accounts.
20
+ * unless `Dup<…>` allows it for in-place accounts. Where data moves (a Vec resized, an account given to a helper:
21
+ * `moves`), `assertNotAliased` also treats the names that may be one account (`maySharePlace`: a Dup pair, a
22
+ * read-only and a writable account of one type, a loaded struct) as one, since the data moves under each of them.
21
23
  */
22
24
  export class AliasEmitter extends EmitterBase {
23
25
  /**
@@ -69,7 +71,7 @@ export class AliasEmitter extends EmitterBase {
69
71
  * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
70
72
  * value. Refuse when a live reference into the replaced place is still used afterwards.
71
73
  */
72
- assertNotAliased(replaced, at, helper, inPlace = false) {
74
+ assertNotAliased(replaced, at, helper, inPlace = false, moves = false) {
73
75
  if (!replaced)
74
76
  return;
75
77
  for (const scope of this.scopes)
@@ -78,14 +80,70 @@ export class AliasEmitter extends EmitterBase {
78
80
  continue;
79
81
  // A helper given an account changes it in place (`inPlace`): a local naming the whole account (a struct loaded
80
82
  // with loadAccountMut) then reads what JS's object would. Only references into it are stale.
81
- const hit = replaced.find((r) => l.paths.some((p) => (p === r && !inPlace) || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
82
- if (!hit || !this.usedAfter(l.decl, at))
83
+ const inside = (p, r) => (p === r && !inPlace) || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`);
84
+ const hit = replaced.find((r) => l.paths.some((p) => inside(p, r)));
85
+ // Data that moves (`moves`: a Vec resized, so the Vecs after it shift; an account a helper may resize) moves
86
+ // under every name of the account: a reference made through another parameter (or loaded struct) that may be
87
+ // this account is stale too.
88
+ const shared = !hit && moves ? this.sharedPlace(replaced, l.paths, inside) : undefined;
89
+ if ((!hit && !shared) || !this.usedAfter(l.decl, at))
83
90
  continue;
91
+ if (shared)
92
+ this.fail(at, `"${name}" still refers to ${this.showPath(shared.path)}, and ${this.showPath(shared.root)} may be the same account as ${this.showPath(shared.other)} (${shared.why}): ${helper ? `${helper}() may move` : "this moves"} that data, so "${name}" would then reach another record. Copy the fields you need into locals first`);
84
93
  this.fail(at, helper
85
94
  ? `"${name}" still refers to data in ${this.showPath(hit)}, and ${helper}() may replace it (then "${name}" would read the new value; in JS it keeps the old one). Copy the fields you need into locals first`
86
95
  : `"${name}" still refers to ${this.showPath(hit)}; replacing it here would change what "${name}" reads (in JS it keeps the old value). Copy the fields you need into locals first`);
87
96
  }
88
97
  }
98
+ /**
99
+ * A reference path (`a.entries[]`) inside one of the `replaced` places named through another root that may be the
100
+ * same account (`b.entries` when `a` and `b` may be one account): the path, the two roots and why.
101
+ */
102
+ sharedPlace(replaced, paths, inside) {
103
+ const rootOf = (p) => p.split(/[.[]/)[0];
104
+ for (const r of replaced)
105
+ for (const p of paths) {
106
+ const [R, P] = [rootOf(r), rootOf(p)];
107
+ if (R === P)
108
+ continue;
109
+ const why = this.maySharePlace(R, P);
110
+ if (why && inside(p, P + r.slice(R.length)))
111
+ return { path: p, root: P, other: R, why };
112
+ }
113
+ return undefined;
114
+ }
115
+ /**
116
+ * Whether two reference roots may name one account's data, read in place: both structs of one type (a struct
117
+ * account parameter or group field not `@layout borsh`, or a struct loaded with loadAccount / loadAccountMut), and
118
+ * accounts the entry checks do not keep apart (`mayBeSameAccount`: a Dup<…> or read-only one, a helper's). Returns
119
+ * why, for the message.
120
+ */
121
+ maySharePlace(a, b) {
122
+ const struct = (root) => {
123
+ if (root.startsWith("@")) {
124
+ for (const s of this.scopes)
125
+ for (const l of s.values())
126
+ if (`@${l.c}` === root && l.loaded)
127
+ return l.loaded.struct;
128
+ return undefined;
129
+ }
130
+ const k = this.accounts.get(root)?.kind;
131
+ return k?.kind === "account" && k.struct.layout !== "borsh" ? k.struct.name : undefined;
132
+ };
133
+ const s = struct(a);
134
+ if (!s || s !== struct(b))
135
+ return undefined;
136
+ if (a.startsWith("@") || b.startsWith("@"))
137
+ return "a struct loaded from an account";
138
+ if (!this.mayBeSameAccount(a, b))
139
+ return undefined;
140
+ const [x, y] = [this.accounts.get(a), this.accounts.get(b)];
141
+ if (x.constraints.dup || y.constraints.dup)
142
+ return "Dup<…>";
143
+ if (!isWritable(x.kind) || !isWritable(y.kind))
144
+ return "a read-only account may be a writable one";
145
+ return "the entry checks do not keep them apart";
146
+ }
89
147
  /**
90
148
  * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
91
149
  * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
@@ -717,8 +717,14 @@ export class CallEmitter extends ExpressionEmitter {
717
717
  if (sys.kind.kind !== "system")
718
718
  this.fail(args[3], "pass the SystemProgram parameter");
719
719
  const { name: entries, count } = args[4] ? this.extraAccountMetas(args[4]) : { name: "NULL", count: 0 };
720
- const fn = builtin === "initExtraAccountMetas" ? "ts_init_extra_metas" : "ts_update_extra_metas";
721
- this.line(`TS_TRY(${fn}(params, a_${payer.name}, a_${acct.name}, &a_${mint.name}->key, ${entries}, ${count}));`);
720
+ if (builtin === "initExtraAccountMetas")
721
+ this.line(`TS_TRY(ts_init_extra_metas(params, a_${payer.name}, a_${acct.name}, &a_${mint.name}->key, ${entries}, ${count}));`);
722
+ else {
723
+ // The growth limit counts from the account's length when the instruction started: entry_ in an instruction
724
+ // (function.ts), the length the entrypoint recorded in the record in a helper.
725
+ const entry = this.ix ? `entry_${acct.name}` : `ts_entry_len(a_${acct.name})`;
726
+ this.line(`TS_TRY(ts_update_extra_metas(params, a_${payer.name}, a_${acct.name}, &a_${mint.name}->key, ${entries}, ${count}, ${entry}));`);
727
+ }
722
728
  return undefined;
723
729
  }
724
730
  case "remainingAccounts":
@@ -1146,7 +1152,7 @@ export class CallEmitter extends ExpressionEmitter {
1146
1152
  const tailStart = () => {
1147
1153
  if (!tail)
1148
1154
  return undefined;
1149
- this.assertNotAliased(tail.paths, node);
1155
+ this.assertNotAliased(tail.paths, node, undefined, false, true);
1150
1156
  const at = this.tmp("tail");
1151
1157
  const n = this.tmp("tail_n");
1152
1158
  this.line(`uint8_t *${at} = ${tail.end};`);
@@ -1233,7 +1239,9 @@ export class CallEmitter extends ExpressionEmitter {
1233
1239
  if (args.length !== 0)
1234
1240
  this.fail(node, "pop() takes no arguments");
1235
1241
  needWritable();
1236
- this.assertNotAliased(elemPaths(), node);
1242
+ // A Vec of an account shrinks: the popped element is cut off under every name of the account.
1243
+ const growable = info.cap === undefined && !info.heap;
1244
+ this.assertNotAliased(elemPaths(), node, undefined, false, growable);
1237
1245
  const st = this.storageValueType(vt.elem);
1238
1246
  const n = this.tmp("n");
1239
1247
  this.line(`uint64_t ${n} = ${count};`);
@@ -1254,7 +1262,7 @@ export class CallEmitter extends ExpressionEmitter {
1254
1262
  this.line(`${valueC(st)} ${out} = ${val.c};`);
1255
1263
  result = st.kind === "pubkey" ? { c: `(&${out})`, type: st } : { c: out, type: st };
1256
1264
  }
1257
- const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
1265
+ const t = growable ? tailStart() : undefined;
1258
1266
  if (t)
1259
1267
  this.line(`ts_memmove(${t.at} - ${info.elemSize}, ${t.at}, ${t.n});`);
1260
1268
  this.line(`${info.len} = (uint32_t)(${n} - 1);`);
@@ -1265,7 +1273,7 @@ export class CallEmitter extends ExpressionEmitter {
1265
1273
  if (args.length !== 0)
1266
1274
  this.fail(node, "clear() takes no arguments");
1267
1275
  needWritable();
1268
- this.assertNotAliased(elemPaths(), node);
1276
+ this.assertNotAliased(elemPaths(), node, undefined, false, info.cap === undefined && !info.heap);
1269
1277
  const t = info.cap === undefined && !info.heap ? tailStart() : undefined;
1270
1278
  if (t)
1271
1279
  this.line(`ts_memmove((uint8_t *)${info.items}, ${t.at}, ${t.n});`);
@@ -2582,7 +2590,7 @@ export class CallEmitter extends ExpressionEmitter {
2582
2590
  // account however it is named here (a parameter, an account group's field, a struct loaded with loadAccountMut).
2583
2591
  for (const [i, p] of h.params.entries())
2584
2592
  if (p.account && p.account.kind === "account" && p.account.mut)
2585
- this.assertNotAliased(this.pathsOf(argNodes[i]), node, h.display, true);
2593
+ this.assertNotAliased(this.pathsOf(argNodes[i]), node, h.display, true, true);
2586
2594
  const args = [
2587
2595
  "params",
2588
2596
  ...pieces.map((x) => (typeof x === "number" ? (passedByPointer(values[x].type) ? this.pointerArg(values[x], mayWrite) : values[x].c) : x)),
@@ -13,6 +13,12 @@ export declare abstract class CpiCoreEmitter extends ViewEmitter {
13
13
  count: number;
14
14
  idl: IdlSeed[] | undefined;
15
15
  };
16
+ /**
17
+ * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
18
+ * also count as pure the byte readers (`data.readU64(i)`) and a stake sysvar slot's `named(account, address)`
19
+ * marker, which only read (their arguments still count).
20
+ */
21
+ protected runsCode(n: ts.Node, readers?: boolean): boolean;
16
22
  /** A call that runs none of the program's code and writes nothing: an integer cast, min / max, a list's get(i). */
17
23
  protected pureCall(n: ts.CallExpression): boolean;
18
24
  protected describeSeed(el: ts.Expression): IdlSeed | undefined;
@@ -21,11 +21,7 @@ export class CpiCoreEmitter extends ViewEmitter {
21
21
  // the list is written, as JS reads them then, unless nothing can run between the list and the CPI that reads it:
22
22
  // no calls or writes among the seeds, nor in the other arguments of the call consuming the list (evaluated before
23
23
  // or after it). A list bound to a name or passed to a helper (`bound`) outlives its expression: always copied.
24
- const mutates = (n) => (ts.isCallExpression(n) && !this.pureCall(n)) ||
25
- (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
26
- (ts.isPrefixUnaryExpression(n) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) ||
27
- ts.isPostfixUnaryExpression(n) ||
28
- ts.forEachChild(n, mutates) === true;
24
+ const mutates = (n) => this.runsCode(n);
29
25
  // The argument holding the list (`signer([…])`, a list of signer lists, an object of CPI options) and the call it
30
26
  // is an argument of.
31
27
  let consumer = node.parent;
@@ -121,6 +117,23 @@ export class CpiCoreEmitter extends ViewEmitter {
121
117
  this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
122
118
  return { name, count: parts.length, idl };
123
119
  }
120
+ /**
121
+ * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
122
+ * also count as pure the byte readers (`data.readU64(i)`) and a stake sysvar slot's `named(account, address)`
123
+ * marker, which only read (their arguments still count).
124
+ */
125
+ runsCode(n, readers = false) {
126
+ if (readers &&
127
+ ts.isCallExpression(n) &&
128
+ ((ts.isPropertyAccessExpression(n.expression) && /^read(?:U8|U16|U32|U64|U128|Pubkey)$/.test(n.expression.name.text)) ||
129
+ this.exportName(n.expression) === "named"))
130
+ return ts.forEachChild(n, (c) => this.runsCode(c, true)) === true;
131
+ return ((ts.isCallExpression(n) && !this.pureCall(n)) ||
132
+ (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
133
+ (ts.isPrefixUnaryExpression(n) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) ||
134
+ ts.isPostfixUnaryExpression(n) ||
135
+ ts.forEachChild(n, (c) => this.runsCode(c, readers)) === true);
136
+ }
124
137
  /** A call that runs none of the program's code and writes nothing: an integer cast, min / max, a list's get(i). */
125
138
  pureCall(n) {
126
139
  const fn = this.exportName(n.expression);