@givelotus/compiler 0.0.0-stage → 0.1.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/README.md +331 -2
- package/artifact-v2.schema.json +58 -0
- package/artifact.schema.json +19 -0
- package/dist/ast.d.ts +292 -0
- package/dist/ast.js +150 -0
- package/dist/bindings.d.ts +6 -0
- package/dist/bindings.js +134 -0
- package/dist/call-runtime.d.ts +84 -0
- package/dist/call-runtime.js +249 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +22 -0
- package/dist/compiler.d.ts +79 -0
- package/dist/compiler.js +125 -0
- package/dist/diagnostics.d.ts +163 -0
- package/dist/diagnostics.js +498 -0
- package/dist/ecash.d.ts +41 -0
- package/dist/ecash.js +190 -0
- package/dist/fees.d.ts +164 -0
- package/dist/fees.js +208 -0
- package/dist/fixture-cli.d.ts +2 -0
- package/dist/fixture-cli.js +41 -0
- package/dist/fixtures.d.ts +68 -0
- package/dist/fixtures.js +46 -0
- package/dist/forth-ir.d.ts +73 -0
- package/dist/forth-ir.js +147 -0
- package/dist/generic-cli.d.ts +2 -0
- package/dist/generic-cli.js +140 -0
- package/dist/generic.d.ts +48 -0
- package/dist/generic.js +2566 -0
- package/dist/lints.d.ts +8 -0
- package/dist/lints.js +204 -0
- package/dist/names.d.ts +1 -0
- package/dist/names.js +7 -0
- package/dist/opcodes.d.ts +154 -0
- package/dist/opcodes.js +162 -0
- package/dist/optimizer.d.ts +58 -0
- package/dist/optimizer.js +786 -0
- package/dist/package-fetch-cli.d.ts +2 -0
- package/dist/package-fetch-cli.js +17 -0
- package/dist/package-lock-cli.d.ts +2 -0
- package/dist/package-lock-cli.js +28 -0
- package/dist/package-sources.d.ts +82 -0
- package/dist/package-sources.js +785 -0
- package/dist/package-update-cli.d.ts +2 -0
- package/dist/package-update-cli.js +20 -0
- package/dist/packages.d.ts +231 -0
- package/dist/packages.js +1307 -0
- package/dist/parser.d.ts +32 -0
- package/dist/parser.js +575 -0
- package/dist/policy.d.ts +83 -0
- package/dist/policy.js +207 -0
- package/dist/runtime.d.ts +58 -0
- package/dist/runtime.js +126 -0
- package/dist/scheduler.d.ts +38 -0
- package/dist/scheduler.js +76 -0
- package/dist/semantic-ir.d.ts +76 -0
- package/dist/semantic-ir.js +231 -0
- package/dist/std.d.ts +27 -0
- package/dist/std.js +225 -0
- package/dist/target-compiler.d.ts +9 -0
- package/dist/target-compiler.js +139 -0
- package/dist/targets.d.ts +53 -0
- package/dist/targets.js +67 -0
- package/dist/toml-subset.d.ts +19 -0
- package/dist/toml-subset.js +81 -0
- package/dist/transaction-runtime.d.ts +182 -0
- package/dist/transaction-runtime.js +646 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +3 -0
- package/dist/vm-cost.d.ts +11 -0
- package/dist/vm-cost.js +541 -0
- package/package.json +71 -4
- package/policy-artifact.schema.json +20 -0
- package/std/custody/arbiter-escrow.lotus +20 -0
- package/std/custody/htlc.lotus +15 -0
- package/std/custody/multisig-2of3.lotus +13 -0
- package/std/custody/single-owner-wallet.lotus +9 -0
- package/std/custody/vault-with-recovery.lotus +14 -0
- package/std/defi/amm-pool-v2.lotus +97 -0
- package/std/defi/indexed-limit-order.lotus +37 -0
- package/std/nft/nft-collection.lotus +51 -0
- package/std/nft/royalty-transfer-rules.lotus +38 -0
- package/std/nft/unique-nft.lotus +30 -0
- package/std/tokens/capped-supply-token.lotus +76 -0
- package/std/tokens/fixed-supply-token.lotus +29 -0
- package/std/tokens/standard-transfer-rules.lotus +15 -0
- package/std/tokens/voucher-mint-token.lotus +31 -0
package/dist/packages.js
ADDED
|
@@ -0,0 +1,1307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CABI-07: deterministic package/module resolution for the contract compiler.
|
|
3
|
+
*
|
|
4
|
+
* Build-time only. Nothing here is consensus, VM, runtime or transaction code.
|
|
5
|
+
* Local path packages and `compilePackage` read declared files, `lotus.lock` and
|
|
6
|
+
* (for module paths) the project cache or `vendor/` tree. They do not spawn git
|
|
7
|
+
* or use the network. `lotus-package-fetch` is the networked entry. The resolver
|
|
8
|
+
* parses each immutable module identity once, links explicit imports into one helper
|
|
9
|
+
* namespace and hands the linked program to the existing scheduler/compiler. Library
|
|
10
|
+
* contracts are compiled into the same program so `contract_root` / `leaf_hash` /
|
|
11
|
+
* `merkle_root` pin their bytecode roots; helpers stay inlined. There is no registry,
|
|
12
|
+
* clock, VM call (`OP_DEFINE` / `OP_INVOKE`) or environment input.
|
|
13
|
+
*/
|
|
14
|
+
import { lstatSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { join, relative, sep } from 'node:path';
|
|
16
|
+
import { bytes, concat, cs, hex, tagged } from './compiler.js';
|
|
17
|
+
import { CompileError, SourceManager, diagnostic } from './diagnostics.js';
|
|
18
|
+
import { DEFAULT_COMPILER_EDITION, DEFAULT_OPTIMIZER_VERSION, SUPPORTED_COMPILER_EDITIONS, SUPPORTED_OPTIMIZER_VERSIONS, compileContract, compileLinkedProgramAsync, linkedProgramSource, sourceBindings, isSupportedCompilerEdition, isSupportedOptimizerVersion, parseModuleSource, resolveCompilerEdition, resolveOptimizerVersion, } from './generic.js';
|
|
19
|
+
import { assertPortableName } from './names.js';
|
|
20
|
+
import { assertGitLocator, classifyRequirement, isGitLocator, isModulePath, resolveDistributedSources } from './package-sources.js';
|
|
21
|
+
import { PromiseScheduler } from './scheduler.js';
|
|
22
|
+
import { parseTomlSubset } from './toml-subset.js';
|
|
23
|
+
export { COMPILER_NAME, COMPILER_VERSION } from './version.js';
|
|
24
|
+
import { COMPILER_NAME, COMPILER_VERSION } from './version.js';
|
|
25
|
+
export const MANIFEST_FILE = 'lotus.toml';
|
|
26
|
+
export const LOCK_FILE = 'lotus.lock';
|
|
27
|
+
export const LOCK_SCHEMA = 'lotus/package-lock/1';
|
|
28
|
+
export const BUILD_GRAPH_SCHEMA = 'lotus/build-graph/1';
|
|
29
|
+
const TARGET = 'P01-P02-P03-candidate-2026-10-14';
|
|
30
|
+
const BUILTINS = new Set([
|
|
31
|
+
'leaf_hash', 'contract_root', 'merkle_root', 'checksig', 'sha256', 'hash256', 'blake3', 'num_bytes', 'check_lock', 'check_sequence',
|
|
32
|
+
'abs', 'sqrt', 'log', 'min', 'max', 'mulpow2', 'within', 'cat', 'size', 'num2bin', 'bin2num',
|
|
33
|
+
'leaf_hash_bytes', 'node_hash', 'checkdatasig', 'sighash', 'state_hash', 'state_verify', 'enforce_output', 'tx_token_in', 'tx_token_out',
|
|
34
|
+
'mul128_wide', 'add_carry', 'sub_carry', 'split', 'less_swap', 'tx_token_balance',
|
|
35
|
+
'bit_not', 'bit_and', 'bit_or', 'bit_xor', 'bit_shl', 'merkle_root_sorted', 'merkle_root_indexed',
|
|
36
|
+
'bytes32', 'TxId', 'StateRoot', 'ChainId', 'SigHash', 'TokenId', 'BranchRoot',
|
|
37
|
+
]);
|
|
38
|
+
const COMMITMENT_BUILTINS = new Set(['leaf_hash', 'contract_root', 'merkle_root']);
|
|
39
|
+
const MAX_WALK_ENTRIES = 4096;
|
|
40
|
+
export const DEFAULT_PACKAGE_LIMITS = { maxPackages: 64, maxModules: 256, maxImportDepth: 32, maxImportBindings: 4096, maxSourceBytes: 4 * 1024 * 1024 };
|
|
41
|
+
/** Diagnostic with a project-relative file and an optional UTF-8 byte span (`file:start..end: message [code]`). */
|
|
42
|
+
export class PackageError extends Error {
|
|
43
|
+
code;
|
|
44
|
+
detail;
|
|
45
|
+
file;
|
|
46
|
+
span;
|
|
47
|
+
constructor(code, detail, file, span) {
|
|
48
|
+
super(`${file ? `${file}${span ? `:${span.start}..${span.end}` : ''}: ` : ''}${detail} [${code}]`);
|
|
49
|
+
this.code = code;
|
|
50
|
+
this.detail = detail;
|
|
51
|
+
this.file = file;
|
|
52
|
+
this.span = span;
|
|
53
|
+
this.name = 'PackageError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const PACKAGE_DIAGNOSTIC = {
|
|
57
|
+
manifest: 'E0901', 'path-escape': 'E0902', 'symlink-escape': 'E0903', 'path-collision': 'E0904', 'undeclared-file': 'E0905',
|
|
58
|
+
'missing-module': 'E0906', 'lock-missing': 'E0907', 'lock-mismatch': 'E0908', 'lock-stale': 'E0909', 'version-conflict': 'E0910',
|
|
59
|
+
'package-cycle': 'E0911', parse: 'E0912', 'unknown-alias': 'E0913', 'not-exported': 'E0914', 'missing-symbol': 'E0915',
|
|
60
|
+
visibility: 'E0916', 'duplicate-name': 'E0917', 'import-cycle': 'E0918', 'declaration-only': 'E0919', limit: 'E0920',
|
|
61
|
+
instance: 'E0930', 'root-cycle': 'E0931',
|
|
62
|
+
branch: 'E0921', unfetched: 'E0922', locator: 'E0923', fetch: 'E0924',
|
|
63
|
+
};
|
|
64
|
+
/** CLI view of a package error. The library still throws `PackageError` with its own code. */
|
|
65
|
+
export function packageCompileError(error, sources = new SourceManager()) {
|
|
66
|
+
const primary = error.file ? { file: error.file, ...(error.span ? { span: error.span } : {}) } : undefined;
|
|
67
|
+
return new CompileError([diagnostic(PACKAGE_DIAGNOSTIC[error.code], error.detail, primary)], sources);
|
|
68
|
+
}
|
|
69
|
+
const utf8 = (text) => new TextEncoder().encode(text);
|
|
70
|
+
const str = (text) => bytes(utf8(text));
|
|
71
|
+
const fold = (text) => text.normalize('NFKC').toUpperCase().toLowerCase().normalize('NFKC');
|
|
72
|
+
const posix = (...parts) => parts.filter(part => part !== '' && part !== '.').join('/') || '.';
|
|
73
|
+
const sorted = (record) => Object.fromEntries([...record].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
74
|
+
function graphDependencies(pkg, ws) {
|
|
75
|
+
if (!ws.modules)
|
|
76
|
+
return sorted(pkg.manifest.dependencies);
|
|
77
|
+
const mapped = new Map();
|
|
78
|
+
for (const [alias, spec] of pkg.manifest.dependencies) {
|
|
79
|
+
const req = classifyRequirement(spec, pkg.manifestFile);
|
|
80
|
+
const selected = req.kind === 'module' ? ws.modules.get(req.module) : ws.packages.get(req.name);
|
|
81
|
+
if (!selected)
|
|
82
|
+
throw new PackageError('manifest', `missing dependency ${spec}`, pkg.manifestFile);
|
|
83
|
+
mapped.set(alias, selected.id);
|
|
84
|
+
}
|
|
85
|
+
return sorted(mapped);
|
|
86
|
+
}
|
|
87
|
+
const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
88
|
+
function decode(data, file) {
|
|
89
|
+
try {
|
|
90
|
+
return new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(data);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
throw new PackageError('manifest', 'file is not valid UTF-8', file);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Project/package-relative path: no absolute paths, traversal, empty or `.` segments, backslashes. */
|
|
97
|
+
export function relPath(value, what, file) {
|
|
98
|
+
if (value.startsWith('/') || /^[A-Za-z]:/.test(value) || value.includes('\\'))
|
|
99
|
+
throw new PackageError('path-escape', `${what} ${JSON.stringify(value)} must be a relative POSIX path`, file);
|
|
100
|
+
const parts = value.split('/');
|
|
101
|
+
if (parts.includes('..'))
|
|
102
|
+
throw new PackageError('path-escape', `${what} ${JSON.stringify(value)} contains path traversal`, file);
|
|
103
|
+
for (const part of parts)
|
|
104
|
+
if (!/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(part))
|
|
105
|
+
throw new PackageError('manifest', `${what} ${JSON.stringify(value)} is not a normalized relative path`, file);
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
function inside(child, parent) { return child === parent || child.startsWith(parent.endsWith(sep) ? parent : parent + sep); }
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
// Manifest
|
|
111
|
+
export function parseManifest(text, file) {
|
|
112
|
+
let doc;
|
|
113
|
+
try {
|
|
114
|
+
doc = parseTomlSubset(text, file);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
throw new PackageError('manifest', error.message.replace(`${file}:`, 'line '), file);
|
|
118
|
+
}
|
|
119
|
+
for (const table of doc.keys())
|
|
120
|
+
if (!['package', 'build', 'dependencies', 'sources', 'replace'].includes(table))
|
|
121
|
+
throw new PackageError('manifest', `unknown table [${table}]`, file);
|
|
122
|
+
const pkg = doc.get('package');
|
|
123
|
+
if (!pkg)
|
|
124
|
+
throw new PackageError('manifest', 'missing [package] table', file);
|
|
125
|
+
for (const key of pkg.keys())
|
|
126
|
+
if (!['name', 'version', 'kind', 'source', 'modules', 'exports', 'entry', 'edition', 'optimizer', 'optimizer_version'].includes(key))
|
|
127
|
+
throw new PackageError('manifest', `unknown package key ${key}`, file);
|
|
128
|
+
const buildTable = doc.get('build');
|
|
129
|
+
if (buildTable) {
|
|
130
|
+
for (const key of buildTable.keys())
|
|
131
|
+
if (!['edition', 'optimizer', 'optimizer_version'].includes(key))
|
|
132
|
+
throw new PackageError('manifest', `unknown build key ${key}`, file);
|
|
133
|
+
}
|
|
134
|
+
const string = (key, required = true) => {
|
|
135
|
+
const value = pkg.get(key);
|
|
136
|
+
if (value === undefined) {
|
|
137
|
+
if (required)
|
|
138
|
+
throw new PackageError('manifest', `missing package.${key}`, file);
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
if (typeof value !== 'string')
|
|
142
|
+
throw new PackageError('manifest', `package.${key} must be a string`, file);
|
|
143
|
+
return value;
|
|
144
|
+
};
|
|
145
|
+
const buildString = (key) => {
|
|
146
|
+
const value = buildTable?.get(key);
|
|
147
|
+
if (value === undefined)
|
|
148
|
+
return undefined;
|
|
149
|
+
if (typeof value !== 'string')
|
|
150
|
+
throw new PackageError('manifest', `build.${key} must be a string`, file);
|
|
151
|
+
return value;
|
|
152
|
+
};
|
|
153
|
+
const list = (key) => {
|
|
154
|
+
const value = pkg.get(key);
|
|
155
|
+
if (value === undefined)
|
|
156
|
+
return [];
|
|
157
|
+
if (!Array.isArray(value))
|
|
158
|
+
throw new PackageError('manifest', `package.${key} must be a string array`, file);
|
|
159
|
+
return value;
|
|
160
|
+
};
|
|
161
|
+
const name = string('name');
|
|
162
|
+
if (/^[a-z_][a-z0-9_]{0,63}$/.test(name)) {
|
|
163
|
+
try {
|
|
164
|
+
assertPortableName(name);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
throw new PackageError('manifest', `package name ${name} is reserved`, file);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else if (!isModulePath(name))
|
|
171
|
+
throw new PackageError('manifest', `package name ${JSON.stringify(name)} must be a short name or a module path`, file);
|
|
172
|
+
const version = string('version');
|
|
173
|
+
if (!/^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/.test(version))
|
|
174
|
+
throw new PackageError('manifest', `version ${JSON.stringify(version)} must be exact MAJOR.MINOR.PATCH`, file);
|
|
175
|
+
const kind = string('kind');
|
|
176
|
+
if (kind !== 'library' && kind !== 'contract')
|
|
177
|
+
throw new PackageError('manifest', 'package.kind must be "library" or "contract"', file);
|
|
178
|
+
const source = relPath(string('source'), 'package.source', file);
|
|
179
|
+
const modules = list('modules');
|
|
180
|
+
if (!modules.length)
|
|
181
|
+
throw new PackageError('manifest', 'package.modules must declare at least one module', file);
|
|
182
|
+
const folded = new Map();
|
|
183
|
+
for (const module of modules) {
|
|
184
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*(\/[A-Za-z_][A-Za-z0-9_]*)*$/.test(module)) {
|
|
185
|
+
if (module.split('/').includes('..') || module.startsWith('/'))
|
|
186
|
+
throw new PackageError('path-escape', `module path ${JSON.stringify(module)} escapes the source root`, file);
|
|
187
|
+
throw new PackageError('manifest', `module path ${JSON.stringify(module)} must be '/'-separated identifiers`, file);
|
|
188
|
+
}
|
|
189
|
+
const key = fold(module), prior = folded.get(key);
|
|
190
|
+
if (prior !== undefined)
|
|
191
|
+
throw new PackageError(prior === module ? 'manifest' : 'path-collision', prior === module ? `duplicate module ${module}` : `module paths ${prior} and ${module} collide under case folding`, file);
|
|
192
|
+
folded.set(key, module);
|
|
193
|
+
}
|
|
194
|
+
const exports = list('exports');
|
|
195
|
+
for (const module of exports)
|
|
196
|
+
if (!modules.includes(module))
|
|
197
|
+
throw new PackageError('manifest', `exported module ${module} is not declared in package.modules`, file);
|
|
198
|
+
if (new Set(exports).size !== exports.length)
|
|
199
|
+
throw new PackageError('manifest', 'duplicate exported module', file);
|
|
200
|
+
const entry = string('entry', false);
|
|
201
|
+
if (kind === 'contract' && (entry === undefined || !modules.includes(entry)))
|
|
202
|
+
throw new PackageError('manifest', 'contract packages require package.entry naming a declared module', file);
|
|
203
|
+
if (kind === 'library' && entry !== undefined)
|
|
204
|
+
throw new PackageError('manifest', 'library packages are declaration-only and have no entry', file);
|
|
205
|
+
const pkgEdition = string('edition', false), buildEdition = buildString('edition');
|
|
206
|
+
if (pkgEdition !== undefined && buildEdition !== undefined && pkgEdition !== buildEdition) {
|
|
207
|
+
throw new PackageError('manifest', `conflicting edition in [package] (${JSON.stringify(pkgEdition)}) and [build] (${JSON.stringify(buildEdition)})`, file);
|
|
208
|
+
}
|
|
209
|
+
const rawEdition = pkgEdition ?? buildEdition;
|
|
210
|
+
if (rawEdition !== undefined && !isSupportedCompilerEdition(rawEdition)) {
|
|
211
|
+
throw new PackageError('manifest', `unsupported compiler edition ${JSON.stringify(rawEdition)}; expected one of: ${SUPPORTED_COMPILER_EDITIONS.join(', ')}`, file);
|
|
212
|
+
}
|
|
213
|
+
const pkgOpt = string('optimizer', false), pkgOptVer = string('optimizer_version', false);
|
|
214
|
+
const buildOpt = buildString('optimizer'), buildOptVer = buildString('optimizer_version');
|
|
215
|
+
const optCandidates = [pkgOpt, pkgOptVer, buildOpt, buildOptVer].filter((x) => x !== undefined);
|
|
216
|
+
if (new Set(optCandidates).size > 1) {
|
|
217
|
+
throw new PackageError('manifest', `conflicting optimizer version settings in manifest: ${optCandidates.map(x => JSON.stringify(x)).join(', ')}`, file);
|
|
218
|
+
}
|
|
219
|
+
const rawOptimizer = optCandidates[0];
|
|
220
|
+
if (rawOptimizer !== undefined && !isSupportedOptimizerVersion(rawOptimizer)) {
|
|
221
|
+
throw new PackageError('manifest', `unsupported optimizer version ${JSON.stringify(rawOptimizer)}; expected one of: ${SUPPORTED_OPTIMIZER_VERSIONS.join(', ')}`, file);
|
|
222
|
+
}
|
|
223
|
+
const table = (title) => {
|
|
224
|
+
const out = new Map();
|
|
225
|
+
for (const [key, value] of doc.get(title) ?? []) {
|
|
226
|
+
if (typeof value !== 'string')
|
|
227
|
+
throw new PackageError('manifest', `[${title}] ${key} must be a string`, file);
|
|
228
|
+
out.set(key, value);
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
};
|
|
232
|
+
const dependencies = table('dependencies');
|
|
233
|
+
for (const [alias, target] of dependencies) {
|
|
234
|
+
try {
|
|
235
|
+
assertPortableName(alias);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
throw new PackageError('manifest', `dependency alias ${alias} is reserved or invalid`, file);
|
|
239
|
+
}
|
|
240
|
+
const req = classifyRequirement(target, file);
|
|
241
|
+
if ((req.kind === 'path' ? req.name : req.module) === name)
|
|
242
|
+
throw new PackageError('package-cycle', `package ${name} depends on itself`, file);
|
|
243
|
+
}
|
|
244
|
+
const sources = table('sources');
|
|
245
|
+
for (const [pkgName, path] of sources) {
|
|
246
|
+
if (isModulePath(pkgName)) {
|
|
247
|
+
if (!isGitLocator(path))
|
|
248
|
+
throw new PackageError('manifest', `[sources] ${pkgName} must be an https or file locator`, file);
|
|
249
|
+
assertGitLocator(path, file);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
if (!/^[a-z_][a-z0-9_]{0,63}$/.test(pkgName))
|
|
253
|
+
throw new PackageError('manifest', `[sources] key ${pkgName} must be a package name`, file);
|
|
254
|
+
relPath(path, `[sources] ${pkgName}`, file);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const replace = table('replace');
|
|
258
|
+
for (const [pkgName, path] of replace) {
|
|
259
|
+
if (!isModulePath(pkgName))
|
|
260
|
+
throw new PackageError('manifest', `[replace] key ${pkgName} must be a module path`, file);
|
|
261
|
+
if (isGitLocator(path))
|
|
262
|
+
assertGitLocator(path, file);
|
|
263
|
+
else
|
|
264
|
+
relPath(path, `[replace] ${pkgName}`, file);
|
|
265
|
+
}
|
|
266
|
+
return { name, version, kind, source, modules, exports, ...(entry !== undefined ? { entry } : {}),
|
|
267
|
+
...(rawEdition !== undefined ? { edition: rawEdition } : {}),
|
|
268
|
+
...(rawOptimizer !== undefined ? { optimizer: rawOptimizer } : {}),
|
|
269
|
+
dependencies, sources, replace };
|
|
270
|
+
}
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
// Package scanning: one immutable snapshot of each package's declared files.
|
|
273
|
+
export function scanPackage(project, locator, isRoot, budget) {
|
|
274
|
+
const dir = locator === '.' ? project : join(project, ...locator.split('/'));
|
|
275
|
+
let real;
|
|
276
|
+
try {
|
|
277
|
+
real = realpathSync(dir);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
throw new PackageError('manifest', `package directory ${locator} does not exist`, locator);
|
|
281
|
+
}
|
|
282
|
+
if (!inside(real, project))
|
|
283
|
+
throw new PackageError('symlink-escape', `package directory ${locator} resolves outside the root project`, locator);
|
|
284
|
+
if (!isRoot && real === project)
|
|
285
|
+
throw new PackageError('manifest', 'a dependency cannot be the root project', locator);
|
|
286
|
+
// The resolved package root (after any in-project symlinks) names the package in diagnostics, lock and build graph.
|
|
287
|
+
const root = relative(project, real).split(sep).join('/') || '.';
|
|
288
|
+
const manifestFile = posix(root, MANIFEST_FILE);
|
|
289
|
+
const readContained = (abs, display) => {
|
|
290
|
+
let st;
|
|
291
|
+
try {
|
|
292
|
+
st = lstatSync(abs);
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
throw new PackageError('missing-module', 'file not found', display);
|
|
296
|
+
}
|
|
297
|
+
if (st.isSymbolicLink()) {
|
|
298
|
+
let target;
|
|
299
|
+
try {
|
|
300
|
+
target = realpathSync(abs);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
throw new PackageError('symlink-escape', 'dangling symlink', display);
|
|
304
|
+
}
|
|
305
|
+
if (!inside(target, real))
|
|
306
|
+
throw new PackageError('symlink-escape', 'symlink resolves outside the package root', display);
|
|
307
|
+
if (!statSync(target).isFile())
|
|
308
|
+
throw new PackageError('manifest', 'symlinked directories and special files are not supported', display);
|
|
309
|
+
}
|
|
310
|
+
else if (!st.isFile())
|
|
311
|
+
throw new PackageError('manifest', 'expected a regular file', display);
|
|
312
|
+
const data = readFileSync(abs);
|
|
313
|
+
budget.bytes += data.length;
|
|
314
|
+
if (budget.bytes > budget.limit)
|
|
315
|
+
throw new PackageError('limit', `total package source exceeds ${budget.limit} bytes`, display);
|
|
316
|
+
return Uint8Array.from(data);
|
|
317
|
+
};
|
|
318
|
+
const manifestBytes = readContained(join(real, MANIFEST_FILE), manifestFile);
|
|
319
|
+
const manifest = parseManifest(decode(manifestBytes, manifestFile), manifestFile);
|
|
320
|
+
const srcAbs = join(real, ...manifest.source.split('/'));
|
|
321
|
+
let srcReal;
|
|
322
|
+
try {
|
|
323
|
+
srcReal = realpathSync(srcAbs);
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
throw new PackageError('manifest', `source root ${manifest.source} does not exist`, manifestFile);
|
|
327
|
+
}
|
|
328
|
+
if (!inside(srcReal, real) || srcReal === real)
|
|
329
|
+
throw new PackageError('symlink-escape', `source root ${manifest.source} must resolve to a subdirectory inside the package`, manifestFile);
|
|
330
|
+
if (!statSync(srcReal).isDirectory())
|
|
331
|
+
throw new PackageError('manifest', `source root ${manifest.source} is not a directory`, manifestFile);
|
|
332
|
+
// Walk the source root with exact on-disk names (case-insensitive file systems
|
|
333
|
+
// cannot satisfy a differently cased declaration), rejecting undeclared files,
|
|
334
|
+
// escaping symlinks and case/Unicode-folding collisions.
|
|
335
|
+
const declared = new Map(manifest.modules.map(module => [`${module}.lotus`, module]));
|
|
336
|
+
const found = new Map();
|
|
337
|
+
const folded = new Map();
|
|
338
|
+
let entries = 0;
|
|
339
|
+
const walk = (abs, rel) => {
|
|
340
|
+
for (const name of readdirSync(abs).sort()) {
|
|
341
|
+
if (++entries > MAX_WALK_ENTRIES)
|
|
342
|
+
throw new PackageError('limit', `source root has more than ${MAX_WALK_ENTRIES} entries`, posix(root, manifest.source));
|
|
343
|
+
const childRel = rel ? `${rel}/${name}` : name, childAbs = join(abs, name), display = posix(root, manifest.source, childRel);
|
|
344
|
+
const key = fold(childRel), prior = folded.get(key);
|
|
345
|
+
if (prior !== undefined)
|
|
346
|
+
throw new PackageError('path-collision', `${prior} and ${childRel} collide under case/Unicode folding`, display);
|
|
347
|
+
folded.set(key, childRel);
|
|
348
|
+
const st = lstatSync(childAbs);
|
|
349
|
+
if (st.isSymbolicLink()) {
|
|
350
|
+
let target;
|
|
351
|
+
try {
|
|
352
|
+
target = realpathSync(childAbs);
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
throw new PackageError('symlink-escape', 'dangling symlink', display);
|
|
356
|
+
}
|
|
357
|
+
if (!inside(target, real))
|
|
358
|
+
throw new PackageError('symlink-escape', 'symlink resolves outside the package root', display);
|
|
359
|
+
if (!statSync(target).isFile())
|
|
360
|
+
throw new PackageError('manifest', 'symlinked directories are not supported', display);
|
|
361
|
+
}
|
|
362
|
+
else if (st.isDirectory()) {
|
|
363
|
+
walk(childAbs, childRel);
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
else if (!st.isFile())
|
|
367
|
+
throw new PackageError('manifest', 'unsupported file type', display);
|
|
368
|
+
if (!declared.has(childRel))
|
|
369
|
+
throw new PackageError('undeclared-file', 'file is not a declared module of this package', display);
|
|
370
|
+
found.set(childRel, childAbs);
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
walk(srcReal, '');
|
|
374
|
+
const files = [{ path: MANIFEST_FILE, content: manifestBytes, digest: tagged('package/file', bytes(manifestBytes)) }];
|
|
375
|
+
for (const [rel, module] of declared) {
|
|
376
|
+
const abs = found.get(rel), display = posix(root, manifest.source, rel);
|
|
377
|
+
if (!abs)
|
|
378
|
+
throw new PackageError('missing-module', `declared module ${module} has no file (names are case-sensitive)`, display);
|
|
379
|
+
const content = readContained(abs, display);
|
|
380
|
+
decode(content, display);
|
|
381
|
+
files.push({ path: posix(manifest.source, rel), content, digest: tagged('package/file', bytes(content)) });
|
|
382
|
+
}
|
|
383
|
+
files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
384
|
+
const treeDigest = tagged('package/tree', concat(str(manifest.name), str(manifest.version), cs(files.length), ...files.map(f => concat(str(f.path), f.digest))));
|
|
385
|
+
return { id: `${manifest.name}@${manifest.version}`, manifest, root, manifestFile, files, treeDigest, isRoot };
|
|
386
|
+
}
|
|
387
|
+
function needsDistributed(info) {
|
|
388
|
+
if (info.manifest.replace.size > 0)
|
|
389
|
+
return true;
|
|
390
|
+
for (const spec of info.manifest.dependencies.values())
|
|
391
|
+
if (spec.includes('/'))
|
|
392
|
+
return true;
|
|
393
|
+
for (const [key, value] of info.manifest.sources)
|
|
394
|
+
if (key.includes('/') || isGitLocator(value))
|
|
395
|
+
return true;
|
|
396
|
+
for (const file of info.files) {
|
|
397
|
+
if (!file.path.endsWith('.lotus'))
|
|
398
|
+
continue;
|
|
399
|
+
if (/(^|\n)[ \t]*import[ \t]+"/.test(decode(file.content, posix(info.root, file.path))))
|
|
400
|
+
return true;
|
|
401
|
+
}
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
function finishDistributed(project, root, limits, budget, online) {
|
|
405
|
+
const resolved = resolveDistributedSources(project, root, limits, budget, online);
|
|
406
|
+
return { project, root, packages: resolved.packages, lockText: resolved.lockText, modules: resolved.modules };
|
|
407
|
+
}
|
|
408
|
+
export function resolveWorkspace(projectDir, limits, online) {
|
|
409
|
+
let project;
|
|
410
|
+
try {
|
|
411
|
+
project = realpathSync(projectDir);
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
throw new PackageError('manifest', 'root project directory does not exist');
|
|
415
|
+
}
|
|
416
|
+
const budget = { bytes: 0, limit: limits.maxSourceBytes };
|
|
417
|
+
const root = scanPackage(project, '.', true, budget);
|
|
418
|
+
const fresh = () => ({ bytes: root.files.reduce((sum, file) => sum + file.content.length, 0), limit: limits.maxSourceBytes });
|
|
419
|
+
if (needsDistributed(root))
|
|
420
|
+
return finishDistributed(project, root, limits, budget, online);
|
|
421
|
+
const packages = new Map();
|
|
422
|
+
const queue = [...root.manifest.dependencies.values()].map(id => ({ id, from: root }));
|
|
423
|
+
while (queue.length) {
|
|
424
|
+
const { id, from } = queue.shift();
|
|
425
|
+
if (id.includes('/'))
|
|
426
|
+
return finishDistributed(project, root, limits, fresh(), online);
|
|
427
|
+
const [name, version] = id.split('@');
|
|
428
|
+
if (name === root.manifest.name)
|
|
429
|
+
throw new PackageError('package-cycle', `${from.id} depends on the root package ${root.id}`, from.manifestFile);
|
|
430
|
+
const prior = packages.get(name);
|
|
431
|
+
if (prior) {
|
|
432
|
+
if (prior.manifest.version !== version)
|
|
433
|
+
throw new PackageError('version-conflict', `${from.id} requires ${id} but ${prior.id} is already in the graph`, from.manifestFile);
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
// Locators come only from the root manifest; dependency [sources] are never inherited.
|
|
437
|
+
const locator = root.manifest.sources.get(name);
|
|
438
|
+
if (locator === undefined)
|
|
439
|
+
throw new PackageError('manifest', `no [sources] locator for ${name} in the root manifest`, root.manifestFile);
|
|
440
|
+
if (packages.size >= limits.maxPackages)
|
|
441
|
+
throw new PackageError('limit', `package graph exceeds ${limits.maxPackages} packages`, from.manifestFile);
|
|
442
|
+
const info = scanPackage(project, locator, false, budget);
|
|
443
|
+
if (info.id !== id)
|
|
444
|
+
throw new PackageError('version-conflict', `locator ${locator} contains ${info.id}, expected ${id}`, info.manifestFile);
|
|
445
|
+
if (info.manifest.kind !== 'library')
|
|
446
|
+
throw new PackageError('declaration-only', `dependency ${id} must be a library package`, info.manifestFile);
|
|
447
|
+
packages.set(name, info);
|
|
448
|
+
for (const dep of info.manifest.dependencies.values())
|
|
449
|
+
queue.push({ id: dep, from: info });
|
|
450
|
+
}
|
|
451
|
+
for (const name of root.manifest.sources.keys())
|
|
452
|
+
if (!packages.has(name))
|
|
453
|
+
throw new PackageError('manifest', `[sources] locator ${name} is not used by the dependency graph`, root.manifestFile);
|
|
454
|
+
// Package-level dependency cycles (module cycles are diagnosed separately with spans).
|
|
455
|
+
const state = new Map();
|
|
456
|
+
const visit = (pkg, chain) => {
|
|
457
|
+
if (state.get(pkg.id) === 'done')
|
|
458
|
+
return;
|
|
459
|
+
if (state.get(pkg.id) === 'active')
|
|
460
|
+
throw new PackageError('package-cycle', `package dependency cycle: ${[...chain, pkg.id].join(' -> ')}`, pkg.manifestFile);
|
|
461
|
+
state.set(pkg.id, 'active');
|
|
462
|
+
for (const dep of pkg.manifest.dependencies.values())
|
|
463
|
+
visit(packages.get(dep.split('@')[0]), [...chain, pkg.id]);
|
|
464
|
+
state.set(pkg.id, 'done');
|
|
465
|
+
};
|
|
466
|
+
for (const pkg of packages.values())
|
|
467
|
+
visit(pkg, []);
|
|
468
|
+
if ([root, ...packages.values()].some(needsDistributed))
|
|
469
|
+
return finishDistributed(project, root, limits, fresh(), online);
|
|
470
|
+
return { project, root, packages, lockText: renderLock(root, packages) };
|
|
471
|
+
}
|
|
472
|
+
function renderLock(root, packages) {
|
|
473
|
+
const lock = {
|
|
474
|
+
schema: LOCK_SCHEMA,
|
|
475
|
+
root: {
|
|
476
|
+
name: root.manifest.name,
|
|
477
|
+
version: root.manifest.version,
|
|
478
|
+
...(root.manifest.edition !== undefined ? { edition: root.manifest.edition } : {}),
|
|
479
|
+
...(root.manifest.optimizer !== undefined ? { optimizer: root.manifest.optimizer } : {}),
|
|
480
|
+
dependencies: sorted(root.manifest.dependencies),
|
|
481
|
+
},
|
|
482
|
+
packages: [...packages.values()].map(pkg => ({ name: pkg.manifest.name, version: pkg.manifest.version,
|
|
483
|
+
locator: { kind: 'path', path: root.manifest.sources.get(pkg.manifest.name) }, root: pkg.root,
|
|
484
|
+
dependencies: sorted(pkg.manifest.dependencies), files: pkg.files.map(f => ({ path: f.path, digest: hex(f.digest) })), treeDigest: hex(pkg.treeDigest) })).sort(byName),
|
|
485
|
+
};
|
|
486
|
+
return JSON.stringify(lock, null, 2) + '\n';
|
|
487
|
+
}
|
|
488
|
+
/** Compute the canonical lock text from local files only (no network). */
|
|
489
|
+
export function generateLock(projectDir, limits = {}) {
|
|
490
|
+
return resolveWorkspace(projectDir, { ...DEFAULT_PACKAGE_LIMITS, ...limits }).lockText;
|
|
491
|
+
}
|
|
492
|
+
/** Rewrite `lotus.lock` from local files. Returns the written text. */
|
|
493
|
+
export function updateLock(projectDir, limits = {}) {
|
|
494
|
+
const text = generateLock(projectDir, limits);
|
|
495
|
+
writeFileSync(join(projectDir, LOCK_FILE), text);
|
|
496
|
+
return text;
|
|
497
|
+
}
|
|
498
|
+
function verifyLock(ws) {
|
|
499
|
+
let actual;
|
|
500
|
+
try {
|
|
501
|
+
actual = Uint8Array.from(readFileSync(join(ws.project, LOCK_FILE)));
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
throw new PackageError('lock-missing', `missing ${LOCK_FILE}; run lotus-package-lock`, LOCK_FILE);
|
|
505
|
+
}
|
|
506
|
+
const text = decode(actual, LOCK_FILE);
|
|
507
|
+
if (text !== ws.lockText) {
|
|
508
|
+
// Explain the first difference: a changed file digest is the common case.
|
|
509
|
+
let lock;
|
|
510
|
+
try {
|
|
511
|
+
lock = JSON.parse(text);
|
|
512
|
+
}
|
|
513
|
+
catch { /* reported below */ }
|
|
514
|
+
if (lock?.root) {
|
|
515
|
+
if (lock.root.edition !== ws.root.manifest.edition) {
|
|
516
|
+
throw new PackageError('lock-mismatch', `manifest edition ${JSON.stringify(ws.root.manifest.edition)} differs from locked ${JSON.stringify(lock.root.edition)}; run lotus-package-lock`, LOCK_FILE);
|
|
517
|
+
}
|
|
518
|
+
if (lock.root.optimizer !== ws.root.manifest.optimizer) {
|
|
519
|
+
throw new PackageError('lock-mismatch', `manifest optimizer ${JSON.stringify(ws.root.manifest.optimizer)} differs from locked ${JSON.stringify(lock.root.optimizer)}; run lotus-package-lock`, LOCK_FILE);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (lock && Array.isArray(lock.packages))
|
|
523
|
+
for (const entry of lock.packages) {
|
|
524
|
+
const pkg = ws.packages.get(entry?.name);
|
|
525
|
+
// Git lock versions are selected tags (`vX.Y.Z`) or commits, not the manifest's MAJOR.MINOR.PATCH.
|
|
526
|
+
if (!pkg || !Array.isArray(entry.files))
|
|
527
|
+
continue;
|
|
528
|
+
for (const file of pkg.files) {
|
|
529
|
+
const pinned = entry.files.find(x => x?.path === file.path);
|
|
530
|
+
if (pinned && pinned.digest !== hex(file.digest))
|
|
531
|
+
throw new PackageError('lock-mismatch', `source digest ${hex(file.digest)} of ${pkg.id} differs from locked ${String(pinned.digest)}; review the change and run lotus-package-lock`, posix(pkg.root, file.path));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
throw new PackageError('lock-stale', `${LOCK_FILE} does not match the manifests and local package files; run lotus-package-lock`, LOCK_FILE);
|
|
535
|
+
}
|
|
536
|
+
return tagged('package/lock', bytes(actual));
|
|
537
|
+
}
|
|
538
|
+
// ---------------------------------------------------------------------------
|
|
539
|
+
// Module graph, import resolution and linking.
|
|
540
|
+
function signature(helper) { return `${helper.name}(${helper.params.map(p => `${p.name}: ${p.type}`).join(', ')}): ${helper.result}`; }
|
|
541
|
+
/** Validate explicit bindings and the complete root DAG before emitting any program. */
|
|
542
|
+
function bindInstances(contracts, templates, owners, resolve, options, linkedHelpersForBindings) {
|
|
543
|
+
const fail = (message) => { throw new PackageError('instance', message); };
|
|
544
|
+
const instances = options.instances ?? {};
|
|
545
|
+
if (!instances || typeof instances !== 'object' || Array.isArray(instances))
|
|
546
|
+
fail('instances must be a named map');
|
|
547
|
+
const inputs = { ...options.bindings };
|
|
548
|
+
const templateNames = new Map();
|
|
549
|
+
const rewrite = (e, from, to) => ({ ...e,
|
|
550
|
+
...(e.kind === 'name' && (e.value === from || e.value?.startsWith(from + '.')) ? { value: to + e.value.slice(from.length) } : {}),
|
|
551
|
+
...(e.args ? { args: e.args.map(a => rewrite(a, from, to)) } : {}),
|
|
552
|
+
...(e.left ? { left: rewrite(e.left, from, to) } : {}), ...(e.right ? { right: rewrite(e.right, from, to) } : {}) });
|
|
553
|
+
const statements = (body, from, to) => body.map(s => ({ ...s,
|
|
554
|
+
...(s.expr ? { expr: rewrite(s.expr, from, to) } : {}), ...(s.then ? { then: statements(s.then, from, to) } : {}),
|
|
555
|
+
...(s.otherwise ? { otherwise: statements(s.otherwise, from, to) } : {}) }));
|
|
556
|
+
for (const [name, instance] of Object.entries(instances)) {
|
|
557
|
+
try {
|
|
558
|
+
assertPortableName(name);
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
fail(`invalid instance name ${name}`);
|
|
562
|
+
}
|
|
563
|
+
if (contracts.has(name) || Object.hasOwn(options.bindings, name))
|
|
564
|
+
fail(`duplicate instance binding ${name}`);
|
|
565
|
+
if (!instance || typeof instance !== 'object' || Object.keys(instance).some(k => !['template', 'bindings'].includes(k)) || typeof instance.template !== 'string')
|
|
566
|
+
fail(`invalid instance ${name}; expected template and bindings only (state/effect lowering is unsupported)`);
|
|
567
|
+
const key = resolve(instance.template), template = templates.get(key);
|
|
568
|
+
if (!template)
|
|
569
|
+
fail(`unresolved template ${instance.template}`);
|
|
570
|
+
const c = template.contract;
|
|
571
|
+
templateNames.set(name, c.name);
|
|
572
|
+
contracts.set(name, { ...c, name, methods: c.methods.map(m => ({ ...m, body: statements(m.body, c.name, name) })) });
|
|
573
|
+
owners.set(name, { pkg: template.owner.pkg, moduleId: template.owner.id, kind: c.kind });
|
|
574
|
+
inputs[name] = instance.bindings;
|
|
575
|
+
}
|
|
576
|
+
// Local contracts use their ordinary names; canonical self references must follow them.
|
|
577
|
+
for (const [name, c] of contracts) {
|
|
578
|
+
const owner = owners.get(name);
|
|
579
|
+
const canonical = `${owner.moduleId}::${name}`;
|
|
580
|
+
if (!templateNames.has(name))
|
|
581
|
+
templateNames.set(name, canonical);
|
|
582
|
+
if (!Object.hasOwn(instances, name))
|
|
583
|
+
contracts.set(name, { ...c, methods: c.methods.map(m => ({ ...m, body: statements(m.body, canonical, name) })) });
|
|
584
|
+
}
|
|
585
|
+
const references = new Map();
|
|
586
|
+
const bindings = {};
|
|
587
|
+
const deps = new Map();
|
|
588
|
+
for (const [name, c] of contracts) {
|
|
589
|
+
const input = inputs[name] ?? (c.params.length === 0 ? {} : undefined);
|
|
590
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
591
|
+
fail(`missing binding map for ${name}`);
|
|
592
|
+
const extra = Object.keys(input).find(p => !c.params.some(param => param.name === p));
|
|
593
|
+
if (extra !== undefined)
|
|
594
|
+
fail(`unexpected constructor binding ${name}.${extra}`);
|
|
595
|
+
const refs = [], edges = new Set();
|
|
596
|
+
const values = {};
|
|
597
|
+
for (const p of c.params) {
|
|
598
|
+
if (!Object.hasOwn(input, p.name))
|
|
599
|
+
fail(`missing constructor binding ${name}.${p.name}`);
|
|
600
|
+
const value = input[p.name];
|
|
601
|
+
if (value !== null && typeof value === 'object') {
|
|
602
|
+
const keys = Object.keys(value);
|
|
603
|
+
if (keys.length !== 1 || !['root', 'leaf'].includes(keys[0]))
|
|
604
|
+
fail(`unsupported binding ${name}.${p.name}; expected a literal, root or leaf reference`);
|
|
605
|
+
const leaf = keys[0] === 'leaf', text = leaf ? value.leaf : value.root;
|
|
606
|
+
if (typeof text !== 'string')
|
|
607
|
+
fail(`invalid reference ${name}.${p.name}`);
|
|
608
|
+
const parts = text.split('.'), target = contracts.get(parts[0]);
|
|
609
|
+
if (!target || parts.length !== (leaf ? 2 : 1))
|
|
610
|
+
fail(`unresolved bound program reference ${text}`);
|
|
611
|
+
if (leaf && !target.methods.some(m => m.name === parts[1]))
|
|
612
|
+
fail(`missing entry ${text}`);
|
|
613
|
+
const valid = leaf ? ['MethodLeafHash', 'Bytes32'] : target.kind === 'token' ? ['TokenId', 'Bytes32'] : ['ContractRootHash', 'BranchRoot', 'Bytes32'];
|
|
614
|
+
if (!valid.includes(p.type))
|
|
615
|
+
fail(`reference type mismatch for ${name}.${p.name}: ${p.type}`);
|
|
616
|
+
refs.push([p.name, { name: parts[0], ...(leaf ? { method: parts[1] } : {}) }]);
|
|
617
|
+
edges.add(parts[0]);
|
|
618
|
+
}
|
|
619
|
+
else
|
|
620
|
+
values[p.name] = value;
|
|
621
|
+
}
|
|
622
|
+
bindings[name] = values;
|
|
623
|
+
references.set(name, refs);
|
|
624
|
+
deps.set(name, edges);
|
|
625
|
+
}
|
|
626
|
+
for (const name of Object.keys(options.bindings))
|
|
627
|
+
if (!contracts.has(name))
|
|
628
|
+
fail(`binding names unbound template ${name}`);
|
|
629
|
+
// Include source/helper root dependencies, so constructor edges cannot hide mixed cycles.
|
|
630
|
+
let scanningName = '';
|
|
631
|
+
const scanExpr = (e, edges, seen) => {
|
|
632
|
+
if (e.kind === 'call') {
|
|
633
|
+
if (COMMITMENT_BUILTINS.has(e.value) && e.args?.[0]?.kind === 'name') {
|
|
634
|
+
const text = e.args[0].value;
|
|
635
|
+
const reference = e.value === 'leaf_hash' ? text.slice(0, text.lastIndexOf('.')) : text;
|
|
636
|
+
const target = reference === templateNames.get(scanningName) ? scanningName : reference;
|
|
637
|
+
if (!contracts.has(target))
|
|
638
|
+
fail(`root reference ${target} requires an explicit bound instance`);
|
|
639
|
+
edges.add(target);
|
|
640
|
+
}
|
|
641
|
+
else if (!seen.has(e.value)) {
|
|
642
|
+
seen.add(e.value);
|
|
643
|
+
const h = linkedHelpersForBindings?.get(e.value);
|
|
644
|
+
if (h)
|
|
645
|
+
scanBody(h.body, edges, seen);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
for (const arg of e.args ?? [])
|
|
649
|
+
scanExpr(arg, edges, seen);
|
|
650
|
+
if (e.left)
|
|
651
|
+
scanExpr(e.left, edges, seen);
|
|
652
|
+
if (e.right)
|
|
653
|
+
scanExpr(e.right, edges, seen);
|
|
654
|
+
};
|
|
655
|
+
const scanBody = (body, edges, seen) => {
|
|
656
|
+
for (const s of body) {
|
|
657
|
+
if (s.expr)
|
|
658
|
+
scanExpr(s.expr, edges, seen);
|
|
659
|
+
if ('then' in s && s.then)
|
|
660
|
+
scanBody(s.then, edges, seen);
|
|
661
|
+
if ('otherwise' in s && s.otherwise)
|
|
662
|
+
scanBody(s.otherwise, edges, seen);
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
for (const [name, c] of contracts) {
|
|
666
|
+
scanningName = name;
|
|
667
|
+
for (const m of c.methods)
|
|
668
|
+
scanBody(m.body, deps.get(name), new Set());
|
|
669
|
+
}
|
|
670
|
+
const active = [], done = new Set(), order = [];
|
|
671
|
+
const visit = (name) => {
|
|
672
|
+
if (done.has(name))
|
|
673
|
+
return;
|
|
674
|
+
if (active.includes(name))
|
|
675
|
+
throw new PackageError('root-cycle', `root dependency cycle: ${[...active.slice(active.indexOf(name)), name].join(' -> ')}`);
|
|
676
|
+
if (!deps.has(name))
|
|
677
|
+
fail(`unknown bound program ${name}`);
|
|
678
|
+
active.push(name);
|
|
679
|
+
for (const dependency of deps.get(name))
|
|
680
|
+
visit(dependency);
|
|
681
|
+
active.pop();
|
|
682
|
+
done.add(name);
|
|
683
|
+
order.push(name);
|
|
684
|
+
};
|
|
685
|
+
visit(options.contract);
|
|
686
|
+
for (const name of Object.keys(instances).sort())
|
|
687
|
+
visit(name);
|
|
688
|
+
return { bindings, references, order };
|
|
689
|
+
}
|
|
690
|
+
export async function compilePackage(projectDir, options) {
|
|
691
|
+
if (typeof options?.contract !== 'string' || !options.bindings || typeof options.bindings !== 'object')
|
|
692
|
+
throw new Error('compile options require contract and bindings');
|
|
693
|
+
if (options.instances !== undefined && options.languageVersion !== 1)
|
|
694
|
+
throw new PackageError('instance', 'explicit instances require languageVersion 1');
|
|
695
|
+
const limits = { ...DEFAULT_PACKAGE_LIMITS, ...(options.limits ?? {}) };
|
|
696
|
+
const ws = resolveWorkspace(projectDir, limits);
|
|
697
|
+
const { root } = ws;
|
|
698
|
+
if (root.manifest.kind !== 'contract' || !root.manifest.entry)
|
|
699
|
+
throw new PackageError('declaration-only', 'the root package must be a contract package with an entry module', root.manifestFile);
|
|
700
|
+
const lockDigest = verifyLock(ws);
|
|
701
|
+
const byId = new Map([[root.id, root], ...[...ws.packages.values()].map(pkg => [pkg.id, pkg])]);
|
|
702
|
+
const modules = new Map();
|
|
703
|
+
const parses = {};
|
|
704
|
+
const sources = new SourceManager();
|
|
705
|
+
let bindings = 0;
|
|
706
|
+
const load = (pkg, path, from) => {
|
|
707
|
+
const id = `${pkg.id}/${path}`;
|
|
708
|
+
const old = modules.get(id);
|
|
709
|
+
if (old)
|
|
710
|
+
return old;
|
|
711
|
+
if (modules.size >= limits.maxModules)
|
|
712
|
+
throw new PackageError('limit', `module graph exceeds ${limits.maxModules} modules`, from?.file, from?.span);
|
|
713
|
+
const rel = posix(pkg.manifest.source, `${path}.lotus`), file = posix(pkg.root, rel);
|
|
714
|
+
const data = pkg.files.find(f => f.path === rel);
|
|
715
|
+
const isEntry = pkg.isRoot && path === pkg.manifest.entry;
|
|
716
|
+
let program;
|
|
717
|
+
try {
|
|
718
|
+
program = parseModuleSource(decode(data.content, file), isEntry, file, sources, options.languageVersion);
|
|
719
|
+
}
|
|
720
|
+
catch (error) {
|
|
721
|
+
if (error instanceof CompileError)
|
|
722
|
+
throw error;
|
|
723
|
+
throw new PackageError('parse', error.message, file);
|
|
724
|
+
}
|
|
725
|
+
parses[id] = (parses[id] ?? 0) + 1;
|
|
726
|
+
const node = { id, pkg, path, file, digest: data.digest, program, isEntry, imports: [] };
|
|
727
|
+
modules.set(id, node);
|
|
728
|
+
return node;
|
|
729
|
+
};
|
|
730
|
+
const entry = load(root, root.manifest.entry);
|
|
731
|
+
// Depth-first import resolution with an explicit stack: cycles report every hop.
|
|
732
|
+
const done = new Set();
|
|
733
|
+
const visit = (node, stack) => {
|
|
734
|
+
if (done.has(node.id))
|
|
735
|
+
return;
|
|
736
|
+
if (stack.length > limits.maxImportDepth) {
|
|
737
|
+
const last = stack.at(-1);
|
|
738
|
+
throw new PackageError('limit', `import depth exceeds ${limits.maxImportDepth}`, last.node.file, last.decl.span);
|
|
739
|
+
}
|
|
740
|
+
const active = stack.map(x => x.node.id);
|
|
741
|
+
for (const decl of node.program.imports) {
|
|
742
|
+
bindings += decl.items?.length ?? 1;
|
|
743
|
+
if (bindings > limits.maxImportBindings)
|
|
744
|
+
throw new PackageError('limit', `import bindings exceed ${limits.maxImportBindings}`, node.file, decl.span);
|
|
745
|
+
let pkg;
|
|
746
|
+
if (decl.target === 'package')
|
|
747
|
+
pkg = node.pkg;
|
|
748
|
+
else if (ws.modules && decl.target.includes('/')) {
|
|
749
|
+
const req = classifyRequirement(decl.target, node.file);
|
|
750
|
+
const selected = req.kind === 'module' ? ws.modules.get(req.module) : undefined;
|
|
751
|
+
if (!selected)
|
|
752
|
+
throw new PackageError('unknown-alias', `${decl.target} is not a resolved module of ${node.pkg.id}`, node.file, decl.targetSpan);
|
|
753
|
+
pkg = selected;
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
const dep = node.pkg.manifest.dependencies.get(decl.target);
|
|
757
|
+
if (!dep)
|
|
758
|
+
throw new PackageError('unknown-alias', `${decl.target} is not a dependency alias of ${node.pkg.id}`, node.file, decl.targetSpan);
|
|
759
|
+
if (ws.modules) {
|
|
760
|
+
const req = classifyRequirement(dep, node.pkg.manifestFile);
|
|
761
|
+
const selected = req.kind === 'module' ? ws.modules.get(req.module) : ws.packages.get(req.name);
|
|
762
|
+
if (!selected)
|
|
763
|
+
throw new PackageError('unknown-alias', `${decl.target} does not resolve in ${node.pkg.id}`, node.file, decl.targetSpan);
|
|
764
|
+
pkg = selected;
|
|
765
|
+
}
|
|
766
|
+
else
|
|
767
|
+
pkg = byId.get(dep);
|
|
768
|
+
}
|
|
769
|
+
const path = decl.path.join('/');
|
|
770
|
+
if (!pkg.manifest.modules.includes(path))
|
|
771
|
+
throw new PackageError('missing-module', `module ${decl.target}::${decl.path.join('::')} does not exist in ${pkg.id}`, node.file, decl.pathSpan);
|
|
772
|
+
if (pkg !== node.pkg && !pkg.manifest.exports.includes(path))
|
|
773
|
+
throw new PackageError('not-exported', `module ${path} is not exported by ${pkg.id}`, node.file, decl.pathSpan);
|
|
774
|
+
const target = load(pkg, path, { file: node.file, span: decl.span });
|
|
775
|
+
const at = active.indexOf(target.id);
|
|
776
|
+
if (target === node || at >= 0) {
|
|
777
|
+
const hops = [...stack.slice(at < 0 ? stack.length : at), { node, decl }];
|
|
778
|
+
throw new PackageError('import-cycle', `import cycle: ${hops.map(h => `${h.node.id} (${h.node.file}:${h.decl.span.start}..${h.decl.span.end})`).join(' -> ')} -> ${target.id}`, node.file, decl.span);
|
|
779
|
+
}
|
|
780
|
+
node.imports.push({ decl, target });
|
|
781
|
+
visit(target, [...stack, { node, decl }]);
|
|
782
|
+
}
|
|
783
|
+
done.add(node.id);
|
|
784
|
+
};
|
|
785
|
+
visit(entry, []);
|
|
786
|
+
// One scheduler job per module identity; each job links its module after its imports.
|
|
787
|
+
const trace = [];
|
|
788
|
+
const scheduler = new PromiseScheduler(event => trace.push(event), { maxJobs: limits.maxModules });
|
|
789
|
+
const states = new Map();
|
|
790
|
+
const helpers = new Map();
|
|
791
|
+
const contracts = new Map();
|
|
792
|
+
const owners = new Map();
|
|
793
|
+
const templates = new Map();
|
|
794
|
+
let resolveTemplate;
|
|
795
|
+
const lc1 = options.languageVersion === 1;
|
|
796
|
+
const interfaces = new Map();
|
|
797
|
+
for (const node of modules.values())
|
|
798
|
+
scheduler.register(`module:${node.id}`, [...new Set(node.imports.map(x => `module:${x.target.id}`))], () => link(node));
|
|
799
|
+
const link = (node) => {
|
|
800
|
+
const scope = new Map();
|
|
801
|
+
const declare = (name, entryValue, span) => {
|
|
802
|
+
if (BUILTINS.has(name))
|
|
803
|
+
throw new PackageError('duplicate-name', `${name} shadows a builtin`, node.file, span);
|
|
804
|
+
if (scope.has(name))
|
|
805
|
+
throw new PackageError('duplicate-name', `ambiguous local name ${name} (already declared or imported in this module)`, node.file, span);
|
|
806
|
+
scope.set(name, entryValue);
|
|
807
|
+
};
|
|
808
|
+
const canonical = (owner, name) => `${owner.id}::${name}`;
|
|
809
|
+
// Helpers and contracts share a module namespace. Visibility matches helpers: private to the module,
|
|
810
|
+
// package within the package, export only from another package (and only via an exported module).
|
|
811
|
+
const lookup = (owner, name, span) => {
|
|
812
|
+
const helper = owner.program.helpers.get(name);
|
|
813
|
+
const contract = owner.program.contracts.get(name);
|
|
814
|
+
if (helper && contract)
|
|
815
|
+
throw new PackageError('duplicate-name', `${owner.id} declares both a function and a contract named ${name}`, node.file, span);
|
|
816
|
+
if (!helper && !contract)
|
|
817
|
+
throw new PackageError('missing-symbol', `${owner.id} has no function or contract ${name}`, node.file, span);
|
|
818
|
+
const visibility = helper ? helper.visibility : contract.visibility;
|
|
819
|
+
if (owner !== node) {
|
|
820
|
+
if (visibility === 'private')
|
|
821
|
+
throw new PackageError('visibility', `${name} is private to module ${owner.id}`, node.file, span);
|
|
822
|
+
if (owner.pkg !== node.pkg && visibility !== 'export')
|
|
823
|
+
throw new PackageError('visibility', `${name} is package-scoped in ${owner.pkg.id}`, node.file, span);
|
|
824
|
+
}
|
|
825
|
+
return helper ? { kind: 'helper', canonical: canonical(owner, helper.name) } : { kind: 'contract', programName: contract.name };
|
|
826
|
+
};
|
|
827
|
+
for (const helper of node.program.helpers.values())
|
|
828
|
+
declare(helper.name, { kind: 'helper', canonical: canonical(node, helper.name) }, helper.span);
|
|
829
|
+
for (const contract of node.program.contracts.values())
|
|
830
|
+
declare(contract.name, { kind: 'contract', programName: contract.name, owner: node }, contract.span);
|
|
831
|
+
for (const { decl, target } of node.imports) {
|
|
832
|
+
if (decl.moduleAlias)
|
|
833
|
+
declare(decl.moduleAlias.name, { kind: 'module', target }, decl.moduleAlias.span);
|
|
834
|
+
for (const item of decl.items ?? []) {
|
|
835
|
+
const symbol = lookup(target, item.name, item.span);
|
|
836
|
+
if (symbol.kind === 'helper')
|
|
837
|
+
declare(item.local, { kind: 'helper', canonical: symbol.canonical }, item.span);
|
|
838
|
+
else
|
|
839
|
+
declare(item.local, { kind: 'contract', programName: symbol.programName, owner: target }, item.span);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
const span = (s) => ({ start: s.start, end: s.end, module: node.id, ...(s.file !== undefined ? { file: s.file } : {}) });
|
|
843
|
+
// Rewrite commitment arguments to the contract's declared name. The compiler then pins that bytecode root.
|
|
844
|
+
const rewriteContractRef = (text, at, expectMethod) => {
|
|
845
|
+
const direct = text.split('.');
|
|
846
|
+
if (lc1 && options.instances && Object.hasOwn(options.instances, direct[0])) {
|
|
847
|
+
if (expectMethod !== (direct.length === 2) || direct.length > 2)
|
|
848
|
+
throw new PackageError('instance', `invalid bound program reference ${text}`, node.file, at);
|
|
849
|
+
return text;
|
|
850
|
+
}
|
|
851
|
+
let owner = node, body = text;
|
|
852
|
+
if (text.includes('::')) {
|
|
853
|
+
const parts = text.split('::');
|
|
854
|
+
if (parts.length !== 2)
|
|
855
|
+
throw new PackageError('missing-symbol', `invalid contract reference ${text}`, node.file, at);
|
|
856
|
+
const alias = parts[0], rest = parts[1];
|
|
857
|
+
const bound = scope.get(alias);
|
|
858
|
+
if (bound?.kind !== 'module')
|
|
859
|
+
throw new PackageError('missing-symbol', `${alias} is not an imported module alias`, node.file, at);
|
|
860
|
+
owner = bound.target;
|
|
861
|
+
body = rest;
|
|
862
|
+
}
|
|
863
|
+
const dot = body.split('.');
|
|
864
|
+
if (dot.length > 2 || !dot[0])
|
|
865
|
+
throw new PackageError('missing-symbol', `invalid contract reference ${text}`, node.file, at);
|
|
866
|
+
const method = dot[1];
|
|
867
|
+
if (expectMethod !== (method !== undefined))
|
|
868
|
+
throw new PackageError('missing-symbol', expectMethod ? 'leaf_hash requires Contract.method' : `${text} must name a contract`, node.file, at);
|
|
869
|
+
let programName, home;
|
|
870
|
+
if (text.includes('::')) {
|
|
871
|
+
const symbol = lookup(owner, dot[0], at);
|
|
872
|
+
if (symbol.kind !== 'contract')
|
|
873
|
+
throw new PackageError('missing-symbol', `${dot[0]} is not a contract`, node.file, at);
|
|
874
|
+
programName = symbol.programName;
|
|
875
|
+
home = owner;
|
|
876
|
+
}
|
|
877
|
+
else {
|
|
878
|
+
const bound = scope.get(dot[0]);
|
|
879
|
+
if (bound?.kind !== 'contract')
|
|
880
|
+
throw new PackageError('missing-symbol', `${dot[0]} is not a contract in scope`, node.file, at);
|
|
881
|
+
programName = bound.programName;
|
|
882
|
+
home = bound.owner;
|
|
883
|
+
}
|
|
884
|
+
const contract = home.program.contracts.get(programName);
|
|
885
|
+
if (method && !contract?.methods.some(m => m.name === method))
|
|
886
|
+
throw new PackageError('missing-symbol', `${programName} has no method ${method}`, node.file, at);
|
|
887
|
+
const selectedName = lc1 ? canonical(home, programName) : programName;
|
|
888
|
+
return method ? `${selectedName}.${method}` : selectedName;
|
|
889
|
+
};
|
|
890
|
+
if (node.isEntry)
|
|
891
|
+
resolveTemplate = name => rewriteContractRef(name, node.program.contracts.values().next().value?.span ?? { start: 0, end: 0 }, false);
|
|
892
|
+
const expr = (e) => {
|
|
893
|
+
let value = e.value, args = e.args;
|
|
894
|
+
if (e.kind === 'call' && value !== undefined && COMMITMENT_BUILTINS.has(value)) {
|
|
895
|
+
const arg = args?.[0];
|
|
896
|
+
if (args?.length === 1 && arg?.kind === 'name' && arg.value !== undefined)
|
|
897
|
+
args = [{ ...arg, span: span(arg.span), value: rewriteContractRef(arg.value, arg.span, value === 'leaf_hash') }];
|
|
898
|
+
else if (args)
|
|
899
|
+
args = args.map(expr);
|
|
900
|
+
}
|
|
901
|
+
else if (e.kind === 'call' && value !== undefined && !BUILTINS.has(value) && !value.includes('.')) {
|
|
902
|
+
if (value.includes('::')) {
|
|
903
|
+
const [alias, member] = value.split('::');
|
|
904
|
+
const bound = scope.get(alias);
|
|
905
|
+
if (bound?.kind !== 'module')
|
|
906
|
+
throw new PackageError('missing-symbol', `${alias} is not an imported module alias`, node.file, e.span);
|
|
907
|
+
const symbol = lookup(bound.target, member, e.span);
|
|
908
|
+
if (symbol.kind !== 'helper')
|
|
909
|
+
throw new PackageError('missing-symbol', `${member} is not a function`, node.file, e.span);
|
|
910
|
+
value = symbol.canonical;
|
|
911
|
+
}
|
|
912
|
+
else {
|
|
913
|
+
const bound = scope.get(value);
|
|
914
|
+
if (bound?.kind === 'contract')
|
|
915
|
+
throw new PackageError('missing-symbol', `${value} is a contract, not a function`, node.file, e.span);
|
|
916
|
+
if (bound?.kind !== 'helper')
|
|
917
|
+
throw new PackageError('missing-symbol', `unknown function ${value}`, node.file, e.span);
|
|
918
|
+
value = bound.canonical;
|
|
919
|
+
}
|
|
920
|
+
if (args)
|
|
921
|
+
args = args.map(expr);
|
|
922
|
+
}
|
|
923
|
+
else if (args)
|
|
924
|
+
args = args.map(expr);
|
|
925
|
+
return { ...e, span: span(e.span), ...(value !== undefined ? { value } : {}),
|
|
926
|
+
...(args ? { args } : {}), ...(e.left ? { left: expr(e.left) } : {}), ...(e.right ? { right: expr(e.right) } : {}) };
|
|
927
|
+
};
|
|
928
|
+
const stmt = (s) => ({
|
|
929
|
+
...s, span: span(s.span),
|
|
930
|
+
...(s.expr ? { expr: expr(s.expr) } : {}),
|
|
931
|
+
...(s.variables ? { variables: s.variables.map(v => ({ ...v, span: span(v.span) })) } : {}),
|
|
932
|
+
...(s.then ? { then: s.then.map(stmt) } : {}),
|
|
933
|
+
...(s.otherwise ? { otherwise: s.otherwise.map(stmt) } : {}),
|
|
934
|
+
});
|
|
935
|
+
const helperStmt = (s) => s.kind === 'let'
|
|
936
|
+
? { ...s, span: span(s.span), nameSpan: span(s.nameSpan), expr: expr(s.expr) }
|
|
937
|
+
: s.kind === 'let_tuple'
|
|
938
|
+
? { ...s, span: span(s.span), variables: s.variables.map(v => ({ ...v, span: span(v.span) })), expr: expr(s.expr) }
|
|
939
|
+
: s.kind === 'if'
|
|
940
|
+
? { ...s, span: span(s.span), expr: expr(s.expr), then: s.then.map(helperStmt), otherwise: s.otherwise.map(helperStmt) }
|
|
941
|
+
: { ...s, span: span(s.span), expr: expr(s.expr) };
|
|
942
|
+
const param = (p) => ({ ...p, span: span(p.span) });
|
|
943
|
+
for (const st of node.program.states?.values() ?? []) {
|
|
944
|
+
if (states.has(st.name))
|
|
945
|
+
throw new PackageError('duplicate-name', `state ${st.name} is already declared`, node.file, st.span);
|
|
946
|
+
states.set(st.name, { ...st, fields: st.fields.map(param), span: span(st.span) });
|
|
947
|
+
}
|
|
948
|
+
for (const helper of node.program.helpers.values()) {
|
|
949
|
+
const name = canonical(node, helper.name);
|
|
950
|
+
helpers.set(name, { ...helper, name, params: helper.params.map(param), body: helper.body.map(helperStmt), span: span(helper.span) });
|
|
951
|
+
}
|
|
952
|
+
for (const contract of node.program.contracts.values()) {
|
|
953
|
+
if (!lc1 && contracts.has(contract.name))
|
|
954
|
+
throw new PackageError('duplicate-name', `contract ${contract.name} is already declared in ${owners.get(contract.name).moduleId}`, node.file, contract.span);
|
|
955
|
+
const linked = { ...contract, params: contract.params.map(param), span: span(contract.span),
|
|
956
|
+
methods: contract.methods.map((m) => ({ ...m, params: m.params.map(param), body: m.body.map(stmt), span: span(m.span) })) };
|
|
957
|
+
const name = lc1 ? canonical(node, contract.name) : contract.name;
|
|
958
|
+
templates.set(canonical(node, contract.name), { contract: { ...linked, name }, owner: node });
|
|
959
|
+
if (!lc1 || (node.isEntry && contract.name === options.contract && !Object.hasOwn(options.instances ?? {}, contract.name))) {
|
|
960
|
+
// LC1 imports expose templates only. A local entry contract may still be selected directly.
|
|
961
|
+
const selected = lc1 ? contract.name : name;
|
|
962
|
+
owners.set(selected, { pkg: node.pkg, moduleId: node.id, kind: contract.kind });
|
|
963
|
+
contracts.set(selected, { ...linked, name: selected });
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
// Stable interface: exported helper signatures, then exported contract/token signatures.
|
|
967
|
+
// Helper declaration bytes stay exactly as before so helper-only modules keep their digest.
|
|
968
|
+
const helperExports = [...node.program.helpers.values()].filter(h => h.visibility === 'export').sort(byName).map(h => {
|
|
969
|
+
const digest = tagged('package/declaration', concat(str(h.name), cs(h.params.length), ...h.params.map(p => concat(str(p.name), str(p.type))), str(h.result)));
|
|
970
|
+
return { name: h.name, signature: signature(h), digest };
|
|
971
|
+
});
|
|
972
|
+
const contractExports = [...node.program.contracts.values()].filter(c => c.visibility === 'export').sort(byName).map(c => {
|
|
973
|
+
const head = c.params.length ? `${c.kind} ${c.name}<${c.params.map(p => `${p.name}: ${p.type}`).join(', ')}>` : `${c.kind} ${c.name}`;
|
|
974
|
+
const methods = c.methods.map(m => `${lc1 ? m.invocation + ' ' : ''}${m.name}(${m.params.map(p => `${p.name}: ${p.type}`).join(', ')})`).join('; ');
|
|
975
|
+
const digest = tagged(lc1 ? 'package/contract/lc1' : 'package/contract', concat(str(c.kind), str(c.name), cs(c.params.length), ...c.params.map(p => concat(str(p.name), str(p.type))), cs(c.methods.length), ...c.methods.flatMap(m => [...(lc1 ? [str(m.invocation)] : []), str(m.name), cs(m.params.length), ...m.params.map(p => concat(str(p.name), str(p.type)))])));
|
|
976
|
+
return { name: c.name, signature: `${head} { ${methods} }`, digest };
|
|
977
|
+
});
|
|
978
|
+
const exported = [...helperExports, ...contractExports];
|
|
979
|
+
interfaces.set(node.id, { digest: tagged(lc1 ? 'package/interface/lc1' : 'package/interface', concat(str(node.pkg.manifest.name), str(node.path), cs(exported.length), ...exported.map(x => x.digest))),
|
|
980
|
+
exports: exported.map(x => ({ name: x.name, signature: x.signature, digest: hex(x.digest) })) });
|
|
981
|
+
};
|
|
982
|
+
await scheduler.run(`module:${entry.id}`);
|
|
983
|
+
if (options.edition !== undefined && !isSupportedCompilerEdition(options.edition)) {
|
|
984
|
+
throw new PackageError('manifest', `unsupported compiler edition ${JSON.stringify(options.edition)}; expected one of: ${SUPPORTED_COMPILER_EDITIONS.join(', ')}`, root.manifestFile);
|
|
985
|
+
}
|
|
986
|
+
if (options.optimizerVersion !== undefined && !isSupportedOptimizerVersion(options.optimizerVersion)) {
|
|
987
|
+
throw new PackageError('manifest', `unsupported optimizerVersion ${JSON.stringify(options.optimizerVersion)}; expected one of: ${SUPPORTED_OPTIMIZER_VERSIONS.join(', ')}`, root.manifestFile);
|
|
988
|
+
}
|
|
989
|
+
if (options.edition !== undefined && root.manifest.edition !== undefined && options.edition !== root.manifest.edition) {
|
|
990
|
+
throw new PackageError('manifest', `compile option edition ${JSON.stringify(options.edition)} conflicts with manifest edition ${JSON.stringify(root.manifest.edition)}`, root.manifestFile);
|
|
991
|
+
}
|
|
992
|
+
if (options.optimizerVersion !== undefined && root.manifest.optimizer !== undefined && options.optimizerVersion !== root.manifest.optimizer) {
|
|
993
|
+
throw new PackageError('manifest', `compile option optimizerVersion ${JSON.stringify(options.optimizerVersion)} conflicts with manifest optimizer ${JSON.stringify(root.manifest.optimizer)}`, root.manifestFile);
|
|
994
|
+
}
|
|
995
|
+
if (options.optimize === false && root.manifest.optimizer !== undefined && root.manifest.optimizer !== 'none') {
|
|
996
|
+
throw new PackageError('manifest', `compile option optimize: false conflicts with manifest optimizer ${JSON.stringify(root.manifest.optimizer)}`, root.manifestFile);
|
|
997
|
+
}
|
|
998
|
+
if (options.optimize === true && root.manifest.optimizer === 'none') {
|
|
999
|
+
throw new PackageError('manifest', 'compile option optimize: true conflicts with manifest optimizer "none"', root.manifestFile);
|
|
1000
|
+
}
|
|
1001
|
+
let pragmaEdition;
|
|
1002
|
+
let pragmaOptimizer;
|
|
1003
|
+
for (const node of modules.values()) {
|
|
1004
|
+
if (node.program.edition !== undefined) {
|
|
1005
|
+
if (pragmaEdition !== undefined && pragmaEdition !== node.program.edition) {
|
|
1006
|
+
throw new PackageError('manifest', `conflicting source pragma edition ${JSON.stringify(node.program.edition)} vs ${JSON.stringify(pragmaEdition)}`, node.file);
|
|
1007
|
+
}
|
|
1008
|
+
pragmaEdition = node.program.edition;
|
|
1009
|
+
}
|
|
1010
|
+
if (node.program.optimizerVersion !== undefined) {
|
|
1011
|
+
if (pragmaOptimizer !== undefined && pragmaOptimizer !== node.program.optimizerVersion) {
|
|
1012
|
+
throw new PackageError('manifest', `conflicting source pragma optimizer ${JSON.stringify(node.program.optimizerVersion)} vs ${JSON.stringify(pragmaOptimizer)}`, node.file);
|
|
1013
|
+
}
|
|
1014
|
+
pragmaOptimizer = node.program.optimizerVersion;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
if (pragmaEdition !== undefined && root.manifest.edition !== undefined && pragmaEdition !== root.manifest.edition) {
|
|
1018
|
+
throw new PackageError('manifest', `source pragma edition ${JSON.stringify(pragmaEdition)} conflicts with manifest edition ${JSON.stringify(root.manifest.edition)}`, root.manifestFile);
|
|
1019
|
+
}
|
|
1020
|
+
if (pragmaEdition !== undefined && options.edition !== undefined && pragmaEdition !== options.edition) {
|
|
1021
|
+
throw new PackageError('manifest', `compile option edition ${JSON.stringify(options.edition)} conflicts with source pragma edition ${JSON.stringify(pragmaEdition)}`, root.manifestFile);
|
|
1022
|
+
}
|
|
1023
|
+
if (pragmaOptimizer !== undefined && root.manifest.optimizer !== undefined && pragmaOptimizer !== root.manifest.optimizer) {
|
|
1024
|
+
throw new PackageError('manifest', `source pragma optimizer ${JSON.stringify(pragmaOptimizer)} conflicts with manifest optimizer ${JSON.stringify(root.manifest.optimizer)}`, root.manifestFile);
|
|
1025
|
+
}
|
|
1026
|
+
if (pragmaOptimizer !== undefined && options.optimizerVersion !== undefined && pragmaOptimizer !== options.optimizerVersion) {
|
|
1027
|
+
throw new PackageError('manifest', `compile option optimizerVersion ${JSON.stringify(options.optimizerVersion)} conflicts with source pragma optimizer ${JSON.stringify(pragmaOptimizer)}`, root.manifestFile);
|
|
1028
|
+
}
|
|
1029
|
+
if (options.optimize === false && pragmaOptimizer !== undefined && pragmaOptimizer !== 'none') {
|
|
1030
|
+
throw new PackageError('manifest', `compile option optimize: false conflicts with source pragma optimizer ${JSON.stringify(pragmaOptimizer)}`, root.manifestFile);
|
|
1031
|
+
}
|
|
1032
|
+
if (options.optimize === true && pragmaOptimizer === 'none') {
|
|
1033
|
+
throw new PackageError('manifest', 'compile option optimize: true conflicts with source pragma optimizer "none"', root.manifestFile);
|
|
1034
|
+
}
|
|
1035
|
+
const explicitEdition = options.edition ?? root.manifest.edition ?? pragmaEdition;
|
|
1036
|
+
const explicitOptimizer = options.optimizerVersion ?? root.manifest.optimizer ?? pragmaOptimizer;
|
|
1037
|
+
const effectiveOptimize = explicitOptimizer !== undefined ? explicitOptimizer !== 'none' : options.optimize;
|
|
1038
|
+
let effectiveOptions = {
|
|
1039
|
+
...options,
|
|
1040
|
+
...(explicitEdition !== undefined ? { edition: explicitEdition } : {}),
|
|
1041
|
+
...(explicitOptimizer !== undefined ? { optimizerVersion: explicitOptimizer } : {}),
|
|
1042
|
+
...(effectiveOptimize !== undefined ? { optimize: effectiveOptimize } : {}),
|
|
1043
|
+
};
|
|
1044
|
+
const instanceArtifacts = new Map();
|
|
1045
|
+
if (lc1) {
|
|
1046
|
+
if (Object.keys(options.instances ?? {}).length > limits.maxImportBindings)
|
|
1047
|
+
throw new PackageError('limit', `instances exceed ${limits.maxImportBindings}`);
|
|
1048
|
+
const bound = bindInstances(contracts, templates, owners, resolveTemplate, options, helpers);
|
|
1049
|
+
effectiveOptions = { ...effectiveOptions, bindings: bound.bindings };
|
|
1050
|
+
const program = { languageVersion: 1, ...(states.size ? { states } : {}), helpers, contracts, imports: [] };
|
|
1051
|
+
// Resolve constructor references in topological order. Every explicitly requested binding is checked.
|
|
1052
|
+
const completed = instanceArtifacts;
|
|
1053
|
+
for (const name of bound.order) {
|
|
1054
|
+
for (const [param, reference] of bound.references.get(name) ?? []) {
|
|
1055
|
+
const target = completed.get(reference.name);
|
|
1056
|
+
bound.bindings[name][param] = reference.method ? target.methods.find(m => m.name === reference.method).leaf : target.policy.root;
|
|
1057
|
+
}
|
|
1058
|
+
const result = await compileLinkedProgramAsync(program, { ...effectiveOptions, contract: name }, undefined, sources);
|
|
1059
|
+
completed.set(name, result.artifact);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
const { artifact, roots } = await compileLinkedProgramAsync({ ...(options.languageVersion === 1 ? { languageVersion: 1 } : {}), ...(states.size ? { states } : {}), helpers, contracts, imports: [] }, effectiveOptions, event => trace.push(event), sources);
|
|
1063
|
+
const allRoots = new Map(roots.map(item => [item.name, item]));
|
|
1064
|
+
for (const [name, item] of instanceArtifacts)
|
|
1065
|
+
allRoots.set(name, { name, root: item.policy.root, methods: item.methods.map(m => ({ name: m.name, leaf: m.leaf })) });
|
|
1066
|
+
const links = [...allRoots.values()].filter(item => item.name !== artifact.contract && owners.get(item.name)?.pkg.id !== root.id).map(item => {
|
|
1067
|
+
const owner = owners.get(item.name);
|
|
1068
|
+
return { name: item.name, kind: owner.kind, package: owner.pkg.id, module: owner.moduleId, packageDigest: hex(owner.pkg.treeDigest), root: item.root, methods: item.methods };
|
|
1069
|
+
}).sort(byName);
|
|
1070
|
+
const graph = {
|
|
1071
|
+
schema: BUILD_GRAPH_SCHEMA,
|
|
1072
|
+
...(lc1 ? { interfaceVersion: 'lotus/module-interface/lc1',
|
|
1073
|
+
instances: [...instanceArtifacts].filter(([name]) => Object.hasOwn(options.instances ?? {}, name)).map(([name, item]) => ({ name, template: options.instances[name].template, bindings: item.bindings, root: item.policy.root })).sort(byName) } : {}),
|
|
1074
|
+
compiler: {
|
|
1075
|
+
name: COMPILER_NAME,
|
|
1076
|
+
version: COMPILER_VERSION,
|
|
1077
|
+
profile: effectiveOptimize === false ? 'unoptimized' : 'optimized',
|
|
1078
|
+
...(explicitEdition !== undefined ? { edition: explicitEdition } : {}),
|
|
1079
|
+
...(explicitOptimizer !== undefined ? { optimizerVersion: explicitOptimizer } : {}),
|
|
1080
|
+
},
|
|
1081
|
+
target: TARGET,
|
|
1082
|
+
root: { package: root.id, module: entry.id },
|
|
1083
|
+
lockDigest: hex(lockDigest),
|
|
1084
|
+
packages: [...byId.values()].map(pkg => ({ id: pkg.id, name: pkg.manifest.name, version: pkg.selectedVersion ?? pkg.manifest.version, root: pkg.root, treeDigest: hex(pkg.treeDigest),
|
|
1085
|
+
dependencies: graphDependencies(pkg, ws) })).sort((a, b) => a.id < b.id ? -1 : 1),
|
|
1086
|
+
modules: [...modules.values()].map(node => ({ id: node.id, package: node.pkg.id, path: node.path, file: node.file, sourceDigest: hex(node.digest),
|
|
1087
|
+
interfaceDigest: hex(interfaces.get(node.id).digest), exports: interfaces.get(node.id).exports,
|
|
1088
|
+
imports: [...new Set(node.imports.map(x => x.target.id))].sort() })).sort((a, b) => a.id < b.id ? -1 : 1),
|
|
1089
|
+
};
|
|
1090
|
+
const build = { ...graph, digest: hex(tagged('build-graph', utf8(JSON.stringify(graph)))) };
|
|
1091
|
+
const linked = { ...(options.languageVersion === 1 ? { languageVersion: 1 } : {}), helpers, contracts, imports: [] };
|
|
1092
|
+
const source = { program: linkedProgramSource(linked), bindings: sourceBindings(effectiveOptions.bindings) };
|
|
1093
|
+
return { artifact: links.length ? { ...artifact, links, build, source } : { ...artifact, build, source }, trace, parses };
|
|
1094
|
+
}
|
|
1095
|
+
// ---------------------------------------------------------------------------
|
|
1096
|
+
// Permanent BranchRoot Spendability & Source-Lock Reproducibility Verifier
|
|
1097
|
+
export const SPEND_BUNDLE_SCHEMA = 'lotus/spend-bundle/1';
|
|
1098
|
+
function sourceFileDigest(content) {
|
|
1099
|
+
return hex(tagged('package/file', bytes(utf8(content))));
|
|
1100
|
+
}
|
|
1101
|
+
function normalizeSpendBundleSources(sources, defaultEntryFile) {
|
|
1102
|
+
if (typeof sources === 'string') {
|
|
1103
|
+
const entryFile = defaultEntryFile;
|
|
1104
|
+
return {
|
|
1105
|
+
entryFile,
|
|
1106
|
+
files: [{ path: entryFile, content: sources, digest: sourceFileDigest(sources) }],
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
if (Array.isArray(sources)) {
|
|
1110
|
+
if (!sources.length)
|
|
1111
|
+
throw new Error('spend bundle requires at least one source file');
|
|
1112
|
+
const files = sources
|
|
1113
|
+
.map(item => ({ path: item.path, content: item.content, digest: sourceFileDigest(item.content) }))
|
|
1114
|
+
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
1115
|
+
const entryFile = defaultEntryFile !== '<source>' ? defaultEntryFile : files[0].path;
|
|
1116
|
+
return { entryFile, files };
|
|
1117
|
+
}
|
|
1118
|
+
if (sources && typeof sources === 'object') {
|
|
1119
|
+
const entries = Object.entries(sources);
|
|
1120
|
+
if (!entries.length)
|
|
1121
|
+
throw new Error('spend bundle requires at least one source file');
|
|
1122
|
+
const files = entries
|
|
1123
|
+
.map(([path, content]) => ({ path, content, digest: sourceFileDigest(content) }))
|
|
1124
|
+
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
1125
|
+
const entryFile = defaultEntryFile !== '<source>' ? defaultEntryFile : entries[0][0];
|
|
1126
|
+
return { entryFile, files };
|
|
1127
|
+
}
|
|
1128
|
+
throw new Error('invalid sources for spend bundle');
|
|
1129
|
+
}
|
|
1130
|
+
function serializeBindingsForDigest(bindings) {
|
|
1131
|
+
const out = {};
|
|
1132
|
+
for (const contractName of Object.keys(bindings).sort()) {
|
|
1133
|
+
const inner = bindings[contractName];
|
|
1134
|
+
const innerSorted = {};
|
|
1135
|
+
for (const key of Object.keys(inner).sort()) {
|
|
1136
|
+
const val = inner[key];
|
|
1137
|
+
innerSorted[key] = typeof val === 'bigint' ? val.toString() : val;
|
|
1138
|
+
}
|
|
1139
|
+
out[contractName] = innerSorted;
|
|
1140
|
+
}
|
|
1141
|
+
return out;
|
|
1142
|
+
}
|
|
1143
|
+
function computeSpendBundleDigest(bundle) {
|
|
1144
|
+
const canonical = {
|
|
1145
|
+
schema: bundle.schema,
|
|
1146
|
+
contract: bundle.contract,
|
|
1147
|
+
kind: bundle.kind,
|
|
1148
|
+
edition: bundle.edition,
|
|
1149
|
+
optimizerVersion: bundle.optimizerVersion,
|
|
1150
|
+
languageVersion: bundle.languageVersion,
|
|
1151
|
+
entryFile: bundle.entryFile,
|
|
1152
|
+
sources: bundle.sources.map(s => ({ path: s.path, digest: s.digest })),
|
|
1153
|
+
bindings: serializeBindingsForDigest(bundle.bindings),
|
|
1154
|
+
expectedRoot: bundle.expectedRoot,
|
|
1155
|
+
expectedMethods: bundle.expectedMethods,
|
|
1156
|
+
};
|
|
1157
|
+
return hex(tagged('spend-bundle', utf8(JSON.stringify(canonical))));
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Package canonical `.lotus` source files, compiler `edition`, `optimizerVersion`, constructor
|
|
1161
|
+
* `bindings`, and expected `BranchRoot` + leaf commitments into a self-contained `SpendBundle`
|
|
1162
|
+
* so covenant UTXOs remain permanently spendable and reproducible across compiler upgrades.
|
|
1163
|
+
*/
|
|
1164
|
+
export function createSpendBundle(artifact, sources, options = {}) {
|
|
1165
|
+
const edition = resolveCompilerEdition(options.edition ?? artifact.build?.compiler?.edition ?? artifact.compiler?.edition ?? DEFAULT_COMPILER_EDITION);
|
|
1166
|
+
const optimizerVersion = resolveOptimizerVersion({
|
|
1167
|
+
optimize: options.optimize ?? (artifact.build?.compiler?.profile === 'unoptimized' ? false : undefined),
|
|
1168
|
+
optimizerVersion: options.optimizerVersion ?? artifact.build?.compiler?.optimizerVersion ?? artifact.compiler?.optimizerVersion,
|
|
1169
|
+
});
|
|
1170
|
+
const languageVersion = options.languageVersion ?? artifact.languageVersion ?? 0;
|
|
1171
|
+
const reconstructedContractBindings = {};
|
|
1172
|
+
for (const b of artifact.bindings) {
|
|
1173
|
+
reconstructedContractBindings[b.name] = b.value;
|
|
1174
|
+
}
|
|
1175
|
+
const bindings = {
|
|
1176
|
+
[artifact.contract]: reconstructedContractBindings,
|
|
1177
|
+
...(options.bindings ?? {}),
|
|
1178
|
+
};
|
|
1179
|
+
const { entryFile, files } = normalizeSpendBundleSources(sources, options.entryFile ?? '<source>');
|
|
1180
|
+
const expectedMethods = artifact.methods.map(m => ({
|
|
1181
|
+
name: m.name,
|
|
1182
|
+
leaf: m.leaf,
|
|
1183
|
+
scriptHex: m.scriptHex,
|
|
1184
|
+
proof: [...m.proof],
|
|
1185
|
+
}));
|
|
1186
|
+
const unsigned = {
|
|
1187
|
+
schema: SPEND_BUNDLE_SCHEMA,
|
|
1188
|
+
contract: artifact.contract,
|
|
1189
|
+
kind: artifact.kind ?? 'contract',
|
|
1190
|
+
edition,
|
|
1191
|
+
optimizerVersion,
|
|
1192
|
+
languageVersion,
|
|
1193
|
+
entryFile,
|
|
1194
|
+
sources: files,
|
|
1195
|
+
bindings,
|
|
1196
|
+
expectedRoot: artifact.policy.root,
|
|
1197
|
+
expectedMethods,
|
|
1198
|
+
};
|
|
1199
|
+
return {
|
|
1200
|
+
...unsigned,
|
|
1201
|
+
bundleDigest: computeSpendBundleDigest(unsigned),
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* Verify that a `SpendBundle` has intact BLAKE3 source/bundle digests and that recompiling its
|
|
1206
|
+
* sources under the pinned `edition` and `optimizerVersion` reproduces the exact byte-for-byte
|
|
1207
|
+
* method leaf scripts, Merkle proofs, and 32-byte `BranchRoot`.
|
|
1208
|
+
*/
|
|
1209
|
+
export function verifySpendBundleReproducibility(bundle) {
|
|
1210
|
+
const fail = (error, recomputedRoot) => ({
|
|
1211
|
+
ok: false,
|
|
1212
|
+
contractRoot: bundle?.expectedRoot ?? '',
|
|
1213
|
+
...(recomputedRoot !== undefined ? { recomputedRoot } : {}),
|
|
1214
|
+
matchesRoot: false,
|
|
1215
|
+
matchesMethods: false,
|
|
1216
|
+
edition: (bundle?.edition ?? DEFAULT_COMPILER_EDITION),
|
|
1217
|
+
optimizerVersion: (bundle?.optimizerVersion ?? DEFAULT_OPTIMIZER_VERSION),
|
|
1218
|
+
error,
|
|
1219
|
+
});
|
|
1220
|
+
if (!bundle || bundle.schema !== SPEND_BUNDLE_SCHEMA) {
|
|
1221
|
+
return fail(`unsupported spend bundle schema "${String(bundle?.schema)}"`);
|
|
1222
|
+
}
|
|
1223
|
+
if (!isSupportedCompilerEdition(bundle.edition)) {
|
|
1224
|
+
return fail(`unsupported compiler edition "${String(bundle.edition)}"; expected one of: ${SUPPORTED_COMPILER_EDITIONS.join(', ')}`);
|
|
1225
|
+
}
|
|
1226
|
+
if (!isSupportedOptimizerVersion(bundle.optimizerVersion)) {
|
|
1227
|
+
return fail(`unsupported optimizerVersion "${String(bundle.optimizerVersion)}"; expected one of: ${SUPPORTED_OPTIMIZER_VERSIONS.join(', ')}`);
|
|
1228
|
+
}
|
|
1229
|
+
if (!Array.isArray(bundle.sources) || !bundle.sources.length) {
|
|
1230
|
+
return fail('spend bundle has no source files');
|
|
1231
|
+
}
|
|
1232
|
+
for (const file of bundle.sources) {
|
|
1233
|
+
if (typeof file?.path !== 'string' || typeof file?.content !== 'string' || typeof file?.digest !== 'string') {
|
|
1234
|
+
return fail('malformed source file entry in spend bundle');
|
|
1235
|
+
}
|
|
1236
|
+
const actualDigest = sourceFileDigest(file.content);
|
|
1237
|
+
if (actualDigest !== file.digest) {
|
|
1238
|
+
return fail(`source digest mismatch for ${file.path}: expected ${file.digest}, got ${actualDigest}`);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
const expectedBundleDigest = computeSpendBundleDigest(bundle);
|
|
1242
|
+
if (bundle.bundleDigest !== expectedBundleDigest) {
|
|
1243
|
+
return fail(`spend bundle digest mismatch: expected ${bundle.bundleDigest}, computed ${expectedBundleDigest}`);
|
|
1244
|
+
}
|
|
1245
|
+
const entry = bundle.sources.find(s => s.path === bundle.entryFile) ?? bundle.sources[0];
|
|
1246
|
+
let artifact;
|
|
1247
|
+
try {
|
|
1248
|
+
artifact = compileContract(entry.content, {
|
|
1249
|
+
contract: bundle.contract,
|
|
1250
|
+
bindings: bundle.bindings,
|
|
1251
|
+
edition: bundle.edition,
|
|
1252
|
+
optimizerVersion: bundle.optimizerVersion,
|
|
1253
|
+
languageVersion: bundle.languageVersion,
|
|
1254
|
+
}, entry.path);
|
|
1255
|
+
}
|
|
1256
|
+
catch (error) {
|
|
1257
|
+
return fail(`recompilation failed: ${error.message}`);
|
|
1258
|
+
}
|
|
1259
|
+
const recomputedRoot = artifact.policy.root;
|
|
1260
|
+
const matchesRoot = recomputedRoot === bundle.expectedRoot;
|
|
1261
|
+
let matchesMethods = artifact.methods.length === bundle.expectedMethods.length;
|
|
1262
|
+
if (matchesMethods) {
|
|
1263
|
+
for (let i = 0; i < bundle.expectedMethods.length; i++) {
|
|
1264
|
+
const exp = bundle.expectedMethods[i];
|
|
1265
|
+
const got = artifact.methods.find(m => m.name === exp.name);
|
|
1266
|
+
if (!got ||
|
|
1267
|
+
got.leaf !== exp.leaf ||
|
|
1268
|
+
got.scriptHex !== exp.scriptHex ||
|
|
1269
|
+
JSON.stringify(got.proof) !== JSON.stringify(exp.proof)) {
|
|
1270
|
+
matchesMethods = false;
|
|
1271
|
+
break;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
if (!matchesRoot || !matchesMethods) {
|
|
1276
|
+
return {
|
|
1277
|
+
ok: false,
|
|
1278
|
+
contractRoot: bundle.expectedRoot,
|
|
1279
|
+
recomputedRoot,
|
|
1280
|
+
matchesRoot,
|
|
1281
|
+
matchesMethods,
|
|
1282
|
+
edition: bundle.edition,
|
|
1283
|
+
optimizerVersion: bundle.optimizerVersion,
|
|
1284
|
+
artifact,
|
|
1285
|
+
error: !matchesRoot
|
|
1286
|
+
? `recomputed BranchRoot ${recomputedRoot} does not match expected ${bundle.expectedRoot}`
|
|
1287
|
+
: 'recomputed method leaves or scriptHex do not match expected methods',
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
return {
|
|
1291
|
+
ok: true,
|
|
1292
|
+
contractRoot: bundle.expectedRoot,
|
|
1293
|
+
recomputedRoot,
|
|
1294
|
+
matchesRoot: true,
|
|
1295
|
+
matchesMethods: true,
|
|
1296
|
+
edition: bundle.edition,
|
|
1297
|
+
optimizerVersion: bundle.optimizerVersion,
|
|
1298
|
+
artifact,
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
export const verifyBranchRootReproducibility = verifySpendBundleReproducibility;
|
|
1302
|
+
export function assertSpendBundleReproducibility(bundle) {
|
|
1303
|
+
const result = verifySpendBundleReproducibility(bundle);
|
|
1304
|
+
if (!result.ok)
|
|
1305
|
+
throw new Error(result.error ?? 'spend bundle reproducibility verification failed');
|
|
1306
|
+
return result.artifact;
|
|
1307
|
+
}
|