midnight-shield 0.0.0-stage → 0.4.1
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/CHANGELOG.md +68 -0
- package/LICENSE +21 -0
- package/README.md +382 -2
- package/action.yml +56 -0
- package/dist/src/analyzer.d.ts +97 -0
- package/dist/src/analyzer.js +895 -0
- package/dist/src/ast.d.ts +211 -0
- package/dist/src/ast.js +2 -0
- package/dist/src/browser.d.ts +3 -0
- package/dist/src/browser.js +5 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +336 -0
- package/dist/src/config.d.ts +26 -0
- package/dist/src/config.js +87 -0
- package/dist/src/fixes.d.ts +10 -0
- package/dist/src/fixes.js +45 -0
- package/dist/src/index.d.ts +10 -0
- package/dist/src/index.js +10 -0
- package/dist/src/lexer.d.ts +18 -0
- package/dist/src/lexer.js +135 -0
- package/dist/src/linter.d.ts +67 -0
- package/dist/src/linter.js +137 -0
- package/dist/src/node.d.ts +13 -0
- package/dist/src/node.js +98 -0
- package/dist/src/parser.d.ts +2 -0
- package/dist/src/parser.js +791 -0
- package/dist/src/plugin-loader.d.ts +3 -0
- package/dist/src/plugin-loader.js +31 -0
- package/dist/src/plugins.d.ts +34 -0
- package/dist/src/plugins.js +59 -0
- package/dist/src/reporters.d.ts +22 -0
- package/dist/src/reporters.js +286 -0
- package/dist/src/rules.d.ts +23 -0
- package/dist/src/rules.js +104 -0
- package/dist/src/sdk.d.ts +6 -0
- package/dist/src/sdk.js +130 -0
- package/dist/src/walk.d.ts +28 -0
- package/dist/src/walk.js +110 -0
- package/docs/rules/MS000.md +7 -0
- package/docs/rules/MS001.md +46 -0
- package/docs/rules/MS002.md +42 -0
- package/docs/rules/MS003.md +41 -0
- package/docs/rules/MS004.md +41 -0
- package/docs/rules/MS005.md +32 -0
- package/docs/rules/MS006.md +17 -0
- package/docs/rules/MS007.md +44 -0
- package/docs/rules/MS008.md +59 -0
- package/docs/rules/MS009.md +45 -0
- package/docs/rules/MS010.md +46 -0
- package/docs/rules/MS101.md +32 -0
- package/docs/rules/MS102.md +31 -0
- package/package.json +67 -4
- package/skills/midnight-shield/SKILL.md +67 -0
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
// Data-flow analyzer for Compact.
|
|
2
|
+
//
|
|
3
|
+
// Every expression evaluates to an `Info` that describes where its value comes
|
|
4
|
+
// from (witnesses, private parameters, public ledger state, constants) and how
|
|
5
|
+
// much secret entropy it carries. Calls to circuits defined in the same file are
|
|
6
|
+
// evaluated inline with the caller's argument infos, so flows through helper
|
|
7
|
+
// circuits are followed. Rules hook into this walk.
|
|
8
|
+
import { RULES_BY_ID } from "./rules.js";
|
|
9
|
+
const HASH_FNS = new Set(["persistentHash", "transientHash"]);
|
|
10
|
+
const COMMIT_FNS = new Set(["persistentCommit", "transientCommit"]);
|
|
11
|
+
const WRAPPER_FNS = new Set(["left", "right", "some", "disclose"]);
|
|
12
|
+
const LEDGER_READ_METHODS = new Set(["member", "read", "lookup", "size", "isEmpty", "checkRoot", "isFull", "head", "length", "first", "root", "history"]);
|
|
13
|
+
const LOW_ENTROPY_BITS = 32;
|
|
14
|
+
const STRONG_RANDOMNESS_BITS = 128;
|
|
15
|
+
const MAX_INLINE_DEPTH = 8;
|
|
16
|
+
function empty() {
|
|
17
|
+
return { sources: new Set(), rawWitness: new Set(), constant: true, ownpkDirect: false, bits: 0 };
|
|
18
|
+
}
|
|
19
|
+
function unknown() {
|
|
20
|
+
return { sources: new Set(), rawWitness: new Set(), constant: false, ownpkDirect: false, bits: undefined };
|
|
21
|
+
}
|
|
22
|
+
function union(infos) {
|
|
23
|
+
const out = empty();
|
|
24
|
+
// keep the protection only if every private part shares it
|
|
25
|
+
const privateParts = infos.filter((i) => isPrivate(i));
|
|
26
|
+
const prot = privateParts.length && privateParts.every((i) => i.protection === privateParts[0].protection) ? privateParts[0].protection : undefined;
|
|
27
|
+
for (const i of infos) {
|
|
28
|
+
i.sources.forEach((s) => out.sources.add(s));
|
|
29
|
+
i.rawWitness.forEach((s) => out.rawWitness.add(s));
|
|
30
|
+
if (i.rawSecret?.size) {
|
|
31
|
+
out.rawSecret = out.rawSecret ?? new Set();
|
|
32
|
+
i.rawSecret.forEach((s) => out.rawSecret.add(s));
|
|
33
|
+
}
|
|
34
|
+
out.constant = out.constant && i.constant;
|
|
35
|
+
out.ownpkDirect = out.ownpkDirect || i.ownpkDirect;
|
|
36
|
+
out.bits = out.bits === undefined || i.bits === undefined ? undefined : out.bits + i.bits;
|
|
37
|
+
if (!out.lowHash && i.lowHash) {
|
|
38
|
+
out.lowHash = i.lowHash;
|
|
39
|
+
out.lowHashBits = i.lowHashBits;
|
|
40
|
+
}
|
|
41
|
+
out.identity = out.identity ?? i.identity;
|
|
42
|
+
}
|
|
43
|
+
out.protection = prot;
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
const SECRET_WORDS = new Set(["sk", "secret", "seed", "mnemonic", "password", "passphrase", "privkey"]);
|
|
47
|
+
/** Does an identifier look like it names a secret? (`secretKey`, `localSk`, `_secret`, `privateKey`) */
|
|
48
|
+
export function isSecretName(name) {
|
|
49
|
+
const words = name
|
|
50
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
51
|
+
.toLowerCase()
|
|
52
|
+
.split(/[^a-z0-9]+/)
|
|
53
|
+
.filter(Boolean);
|
|
54
|
+
if (words.some((w) => SECRET_WORDS.has(w)))
|
|
55
|
+
return true;
|
|
56
|
+
return words.some((w, i) => w === "private" && words[i + 1] === "key");
|
|
57
|
+
}
|
|
58
|
+
function noSecret(i) {
|
|
59
|
+
return { ...i, rawSecret: undefined };
|
|
60
|
+
}
|
|
61
|
+
function isPrivate(i) {
|
|
62
|
+
for (const s of i.sources)
|
|
63
|
+
if (s.startsWith("w:") || s.startsWith("p:"))
|
|
64
|
+
return true;
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
const MAX_IMPORT_DEPTH = 6;
|
|
68
|
+
export class Analyzer {
|
|
69
|
+
program;
|
|
70
|
+
resolver;
|
|
71
|
+
file;
|
|
72
|
+
ledgers = new Map();
|
|
73
|
+
witnesses = new Map();
|
|
74
|
+
circuits = new Map();
|
|
75
|
+
visitedFiles = new Set();
|
|
76
|
+
enums = new Map();
|
|
77
|
+
structs = new Map();
|
|
78
|
+
aliases = new Map();
|
|
79
|
+
findings = [];
|
|
80
|
+
seen = new Set();
|
|
81
|
+
constrainedWitnesses = new Set();
|
|
82
|
+
witnessSinks = new Map();
|
|
83
|
+
hashSites = new Map();
|
|
84
|
+
/** MS010: identity key -> circuits that publish it (first location per circuit) */
|
|
85
|
+
identityUses = new Map();
|
|
86
|
+
/** exported circuits that authorize with anonymous Merkle membership */
|
|
87
|
+
anonymousCircuits = new Set();
|
|
88
|
+
constructor(program, resolver, file) {
|
|
89
|
+
this.program = program;
|
|
90
|
+
this.resolver = resolver;
|
|
91
|
+
this.file = file;
|
|
92
|
+
if (file)
|
|
93
|
+
this.visitedFiles.add(file);
|
|
94
|
+
this.collect(program.decls, "", false, 0, file);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Register declarations. Imported modules are registered under their import
|
|
98
|
+
* prefix (e.g. `Utils_hash`) so calls from the analyzed file resolve, and
|
|
99
|
+
* marked external: they are followed when called, but not reported on.
|
|
100
|
+
*/
|
|
101
|
+
collect(decls, prefix, external, depth, file) {
|
|
102
|
+
const setType = (map, name, value) => {
|
|
103
|
+
map.set(prefix + name, value);
|
|
104
|
+
if (prefix && !map.has(name))
|
|
105
|
+
map.set(name, value);
|
|
106
|
+
};
|
|
107
|
+
for (const d of decls) {
|
|
108
|
+
switch (d.kind) {
|
|
109
|
+
case "ledger":
|
|
110
|
+
this.ledgers.set(prefix + d.name, d.type);
|
|
111
|
+
break;
|
|
112
|
+
case "witness":
|
|
113
|
+
this.witnesses.set(prefix + d.name, d);
|
|
114
|
+
break;
|
|
115
|
+
case "circuit":
|
|
116
|
+
this.circuits.set(prefix + d.name, { decl: d, prefix, external });
|
|
117
|
+
break;
|
|
118
|
+
case "enum":
|
|
119
|
+
setType(this.enums, d.name, d.members.length);
|
|
120
|
+
break;
|
|
121
|
+
case "struct":
|
|
122
|
+
setType(this.structs, d.name, d.fields);
|
|
123
|
+
break;
|
|
124
|
+
case "typeAlias":
|
|
125
|
+
setType(this.aliases, d.name, d.type);
|
|
126
|
+
break;
|
|
127
|
+
case "module":
|
|
128
|
+
this.collect(d.decls, prefix, external, depth, file);
|
|
129
|
+
break;
|
|
130
|
+
case "import":
|
|
131
|
+
case "include": {
|
|
132
|
+
if (!this.resolver || depth >= MAX_IMPORT_DEPTH)
|
|
133
|
+
break;
|
|
134
|
+
if (d.kind === "import" && !d.isPath)
|
|
135
|
+
break; // standard library or a module in this file
|
|
136
|
+
const target = d.kind === "import" ? d.target : d.path;
|
|
137
|
+
const resolved = this.resolver(file, target);
|
|
138
|
+
if (!resolved || this.visitedFiles.has(resolved.file + "|" + prefix))
|
|
139
|
+
break;
|
|
140
|
+
this.visitedFiles.add(resolved.file + "|" + prefix);
|
|
141
|
+
const nextPrefix = d.kind === "import" ? prefix + d.prefix : prefix;
|
|
142
|
+
this.collect(resolved.program.decls, nextPrefix, true, depth + 1, resolved.file);
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Resolve a name used inside code of the module with `frame.prefix`. */
|
|
149
|
+
resolveName(map, name, frame) {
|
|
150
|
+
if (frame.prefix && map.has(frame.prefix + name))
|
|
151
|
+
return frame.prefix + name;
|
|
152
|
+
return map.has(name) ? name : undefined;
|
|
153
|
+
}
|
|
154
|
+
run() {
|
|
155
|
+
for (const d of this.program.diagnostics) {
|
|
156
|
+
this.report("MS000", d.loc, `Could not parse this part of the file (${d.message}); it was skipped.`);
|
|
157
|
+
}
|
|
158
|
+
if (!this.program.decls.some((d) => d.kind === "pragma")) {
|
|
159
|
+
this.report("MS006", { line: 1, col: 1 }, "No `pragma language_version` declared. Pin the Compact language version this contract was written for.");
|
|
160
|
+
}
|
|
161
|
+
this.analyzeDecls(this.program.decls);
|
|
162
|
+
for (const site of this.hashSites.values()) {
|
|
163
|
+
if (site.private && !site.tagged) {
|
|
164
|
+
this.report("MS005", site.loc, "This hash has no constant domain tag. If the same secret is hashed elsewhere (or in another contract), the outputs can be linked. Add a tag such as pad(32, \"myapp:purpose:\") as the first input.");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// MS010 only matters where the contract promises anonymity: in account-style
|
|
168
|
+
// designs a stable identifier (like an address) is linkable by design.
|
|
169
|
+
for (const uses of this.identityUses.values()) {
|
|
170
|
+
if (uses.size < 2)
|
|
171
|
+
continue;
|
|
172
|
+
if (![...uses.keys()].some((c) => this.anonymousCircuits.has(c)))
|
|
173
|
+
continue;
|
|
174
|
+
const entries = [...uses.entries()].sort((a, b) => a[1].line - b[1].line || a[1].col - b[1].col);
|
|
175
|
+
const names = entries.map(([c]) => `'${c}'`).join(", ");
|
|
176
|
+
this.report("MS010", entries[0][1], `The same identifier, derived only from a secret, is published by ${names}. Observers can link these actions to one user. If they should be unlinkable, mix a per-action value (a round, a nonce, or the action name) into the hash.`);
|
|
177
|
+
}
|
|
178
|
+
for (const [w, loc] of this.witnessSinks) {
|
|
179
|
+
if (!this.constrainedWitnesses.has(w) && this.isFactualWitness(w)) {
|
|
180
|
+
this.report("MS002", loc, `Witness '${w}()' reaches public state here, but no assert anywhere constrains its value. The prover controls witness results, so check them (range, membership, or relation to ledger state) before trusting them.`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return this.findings;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* MS002 targets witnesses that report facts (amounts, flags, states, records).
|
|
187
|
+
* Free-form user input (Bytes, Opaque) and randomness are expected to be
|
|
188
|
+
* unconstrained, so they are skipped to avoid noise.
|
|
189
|
+
*/
|
|
190
|
+
isFactualWitness(name) {
|
|
191
|
+
if (/rand|salt|nonce|seed|entropy|blind/i.test(name))
|
|
192
|
+
return false;
|
|
193
|
+
const t = this.witnesses.get(name)?.returnType;
|
|
194
|
+
return t !== undefined && this.isFactualType(t, 0);
|
|
195
|
+
}
|
|
196
|
+
isFactualType(t, depth) {
|
|
197
|
+
if (depth > 6)
|
|
198
|
+
return false;
|
|
199
|
+
if (["Boolean", "Uint", "Field"].includes(t.name))
|
|
200
|
+
return true;
|
|
201
|
+
if (this.enums.has(t.name))
|
|
202
|
+
return true;
|
|
203
|
+
if (this.aliases.has(t.name))
|
|
204
|
+
return this.isFactualType(this.aliases.get(t.name), depth + 1);
|
|
205
|
+
if (t.name === "[]")
|
|
206
|
+
return t.args.some((a) => a.kind === "type" && this.isFactualType(a.type, depth + 1));
|
|
207
|
+
if (this.structs.has(t.name))
|
|
208
|
+
return this.structs.get(t.name).some((f) => f.type !== undefined && this.isFactualType(f.type, depth + 1));
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
analyzeDecls(decls) {
|
|
212
|
+
for (const d of decls) {
|
|
213
|
+
if (d.kind === "module")
|
|
214
|
+
this.analyzeDecls(d.decls);
|
|
215
|
+
if (d.kind === "constructor")
|
|
216
|
+
this.analyzeFunction("constructor", d.params, d.body, false);
|
|
217
|
+
if (d.kind === "circuit" && d.body)
|
|
218
|
+
this.analyzeFunction(d.name, d.params, d.body, d.exported);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
analyzeFunction(name, params, body, exported) {
|
|
222
|
+
const vars = new Map();
|
|
223
|
+
for (const p of params)
|
|
224
|
+
vars.set(p.name, this.paramInfo(p));
|
|
225
|
+
const nullifier = { negMember: false, writes: false, checkedPaths: new Map(), boundPaths: new Set(), rootVars: new Map() };
|
|
226
|
+
const frame = { name, exported, scopes: [{ vars }], silent: false, depth: 0, stack: [name], returns: [], commitRand: new Map(), prefix: "", nullifier };
|
|
227
|
+
this.execBlock(body, frame);
|
|
228
|
+
for (const [path, loc] of nullifier.checkedPaths) {
|
|
229
|
+
if (!nullifier.boundPaths.has(path)) {
|
|
230
|
+
this.report("MS009", loc, `The root of Merkle path '${path}' is checked, but nothing asserts that '${path}.leaf' belongs to the caller. Merkle paths are public, so anyone can submit another member's path and pass. Add e.g. assert(${path}.leaf == deriveLeaf(secretKey())).`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (exported && nullifier.anonAuth)
|
|
234
|
+
this.anonymousCircuits.add(name);
|
|
235
|
+
if (exported && nullifier.anonAuth && nullifier.writes && !nullifier.negMember) {
|
|
236
|
+
this.report("MS008", nullifier.anonAuth, `'${name}' authorizes the caller with an anonymous Merkle membership proof and then changes state, but never checks a nullifier. The same member can repeat this action. If each member should act once, derive a nullifier (hash of a tag and the member's secret), assert it is not in a set, then insert it.`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
paramInfo(p) {
|
|
240
|
+
return {
|
|
241
|
+
sources: new Set([`p:${p.name}`]),
|
|
242
|
+
rawWitness: new Set(),
|
|
243
|
+
constant: false,
|
|
244
|
+
ownpkDirect: false,
|
|
245
|
+
bits: this.typeBits(p.type),
|
|
246
|
+
type: p.type,
|
|
247
|
+
rawSecret: isSecretName(p.name) ? new Set([`p:${p.name}`]) : undefined,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
// ---------- reporting ----------
|
|
251
|
+
report(ruleId, loc, message, severity, confidence) {
|
|
252
|
+
const key = `${ruleId}:${loc.line}:${loc.col}`;
|
|
253
|
+
if (this.seen.has(key))
|
|
254
|
+
return;
|
|
255
|
+
this.seen.add(key);
|
|
256
|
+
const meta = RULES_BY_ID.get(ruleId);
|
|
257
|
+
this.findings.push({ ruleId, severity: severity ?? meta.severity, confidence: confidence ?? meta.confidence, message, loc });
|
|
258
|
+
}
|
|
259
|
+
// ---------- disclosure map ----------
|
|
260
|
+
disclosures = new Map();
|
|
261
|
+
getDisclosures() {
|
|
262
|
+
return [...this.disclosures.values()].sort((a, b) => a.loc.line - b.loc.line || a.loc.col - b.loc.col);
|
|
263
|
+
}
|
|
264
|
+
recordDisclosure(info, loc, frame, via, target) {
|
|
265
|
+
// A disclosed value written to the ledger was already recorded at disclose().
|
|
266
|
+
if (via === "ledger write" && info.sources.has("disclosed") && !isPrivate(info))
|
|
267
|
+
return;
|
|
268
|
+
const at = frame.anchor ?? loc;
|
|
269
|
+
const circuit = frame.stack[0];
|
|
270
|
+
const key = `${circuit}:${at.line}:${at.col}:${via}`;
|
|
271
|
+
const sources = [...info.sources]
|
|
272
|
+
.filter((s) => s.startsWith("w:") || s.startsWith("p:"))
|
|
273
|
+
.map((s) => (s.startsWith("w:") ? `witness:${s.slice(2)}` : `param:${s.slice(2)}`));
|
|
274
|
+
const protection = !isPrivate(info)
|
|
275
|
+
? info.constant
|
|
276
|
+
? "constant"
|
|
277
|
+
: "public"
|
|
278
|
+
: info.protection ?? "raw";
|
|
279
|
+
const prev = this.disclosures.get(key);
|
|
280
|
+
if (prev) {
|
|
281
|
+
for (const src of sources)
|
|
282
|
+
if (!prev.sources.includes(src))
|
|
283
|
+
prev.sources.push(src);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
this.disclosures.set(key, {
|
|
287
|
+
circuit,
|
|
288
|
+
loc: at,
|
|
289
|
+
via,
|
|
290
|
+
target,
|
|
291
|
+
sources,
|
|
292
|
+
protection,
|
|
293
|
+
secretBits: protection === "raw" || protection === "hash" ? info.bits : undefined,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
// ---------- types ----------
|
|
297
|
+
typeBits(t, depth = 0) {
|
|
298
|
+
if (!t || depth > 8)
|
|
299
|
+
return undefined;
|
|
300
|
+
const num = (i) => {
|
|
301
|
+
const a = t.args[i];
|
|
302
|
+
return a && a.kind === "number" ? a.value : undefined;
|
|
303
|
+
};
|
|
304
|
+
switch (t.name) {
|
|
305
|
+
case "Boolean":
|
|
306
|
+
return 1;
|
|
307
|
+
case "Field":
|
|
308
|
+
return 254;
|
|
309
|
+
case "Uint": {
|
|
310
|
+
const a = t.args[0];
|
|
311
|
+
if (a?.kind === "number")
|
|
312
|
+
return a.value;
|
|
313
|
+
if (a?.kind === "range")
|
|
314
|
+
return Math.max(1, Math.ceil(Math.log2(Math.max(2, a.to - a.from))));
|
|
315
|
+
return undefined;
|
|
316
|
+
}
|
|
317
|
+
case "Bytes": {
|
|
318
|
+
const n = num(0);
|
|
319
|
+
return n === undefined ? undefined : n * 8;
|
|
320
|
+
}
|
|
321
|
+
case "Vector": {
|
|
322
|
+
const n = num(0);
|
|
323
|
+
const inner = t.args[1];
|
|
324
|
+
if (n === undefined || inner?.kind !== "type")
|
|
325
|
+
return undefined;
|
|
326
|
+
const b = this.typeBits(inner.type, depth + 1);
|
|
327
|
+
return b === undefined ? undefined : n * b;
|
|
328
|
+
}
|
|
329
|
+
case "[]": {
|
|
330
|
+
let sum = 0;
|
|
331
|
+
for (const a of t.args) {
|
|
332
|
+
if (a.kind !== "type")
|
|
333
|
+
return undefined;
|
|
334
|
+
const b = this.typeBits(a.type, depth + 1);
|
|
335
|
+
if (b === undefined)
|
|
336
|
+
return undefined;
|
|
337
|
+
sum += b;
|
|
338
|
+
}
|
|
339
|
+
return sum;
|
|
340
|
+
}
|
|
341
|
+
case "ZswapCoinPublicKey":
|
|
342
|
+
case "ContractAddress":
|
|
343
|
+
case "UserAddress":
|
|
344
|
+
return 256;
|
|
345
|
+
}
|
|
346
|
+
if (this.enums.has(t.name))
|
|
347
|
+
return Math.max(1, Math.ceil(Math.log2(this.enums.get(t.name))));
|
|
348
|
+
if (this.aliases.has(t.name))
|
|
349
|
+
return this.typeBits(this.aliases.get(t.name), depth + 1);
|
|
350
|
+
if (this.structs.has(t.name)) {
|
|
351
|
+
let sum = 0;
|
|
352
|
+
for (const f of this.structs.get(t.name)) {
|
|
353
|
+
const b = this.typeBits(f.type, depth + 1);
|
|
354
|
+
if (b === undefined)
|
|
355
|
+
return undefined;
|
|
356
|
+
sum += b;
|
|
357
|
+
}
|
|
358
|
+
return sum;
|
|
359
|
+
}
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
// ---------- statements ----------
|
|
363
|
+
lookup(name, frame) {
|
|
364
|
+
for (let i = frame.scopes.length - 1; i >= 0; i--) {
|
|
365
|
+
const v = frame.scopes[i].vars.get(name);
|
|
366
|
+
if (v)
|
|
367
|
+
return v;
|
|
368
|
+
}
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
execBlock(body, frame) {
|
|
372
|
+
frame.scopes.push({ vars: new Map() });
|
|
373
|
+
for (const s of body)
|
|
374
|
+
this.execStmt(s, frame);
|
|
375
|
+
frame.scopes.pop();
|
|
376
|
+
}
|
|
377
|
+
execStmt(s, frame) {
|
|
378
|
+
const scope = frame.scopes[frame.scopes.length - 1];
|
|
379
|
+
switch (s.kind) {
|
|
380
|
+
case "const": {
|
|
381
|
+
const path = findPathRootArg(s.init);
|
|
382
|
+
if (path && s.names.length === 1)
|
|
383
|
+
frame.nullifier.rootVars.set(this.pathKey(s.names[0], frame), path);
|
|
384
|
+
const info = this.evalExpr(s.init, frame);
|
|
385
|
+
if (s.type)
|
|
386
|
+
info.type = s.type;
|
|
387
|
+
for (const n of s.names)
|
|
388
|
+
scope.vars.set(n, info);
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
case "assign": {
|
|
392
|
+
const value = this.evalExpr(s.value, frame);
|
|
393
|
+
this.evalExpr(s.target, frame);
|
|
394
|
+
const root = rootIdent(s.target);
|
|
395
|
+
if (root && !this.lookup(root, frame) && this.resolveName(this.ledgers, root, frame))
|
|
396
|
+
this.sink(value, s.loc, frame, true, root);
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
case "if": {
|
|
400
|
+
const test = this.evalExpr(s.test, frame);
|
|
401
|
+
this.markConstrained(test);
|
|
402
|
+
this.execBlock(s.then, frame);
|
|
403
|
+
if (s.else)
|
|
404
|
+
this.execBlock(s.else, frame);
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
case "for": {
|
|
408
|
+
const iter = this.evalExpr(s.iter, frame);
|
|
409
|
+
frame.scopes.push({ vars: new Map([[s.name, { ...iter, sources: new Set(iter.sources), rawWitness: new Set(iter.rawWitness) }]]) });
|
|
410
|
+
for (const st of s.body)
|
|
411
|
+
this.execStmt(st, frame);
|
|
412
|
+
frame.scopes.pop();
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
case "return": {
|
|
416
|
+
if (s.value) {
|
|
417
|
+
const v = this.evalExpr(s.value, frame);
|
|
418
|
+
frame.returns.push(v);
|
|
419
|
+
if (frame.exported && frame.depth === 0)
|
|
420
|
+
this.recordDisclosure(v, s.loc, frame, "return");
|
|
421
|
+
}
|
|
422
|
+
break;
|
|
423
|
+
}
|
|
424
|
+
case "expr":
|
|
425
|
+
this.evalExpr(s.expr, frame);
|
|
426
|
+
break;
|
|
427
|
+
case "block":
|
|
428
|
+
this.execBlock(s.body, frame);
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
markConstrained(info) {
|
|
433
|
+
for (const s of info.sources)
|
|
434
|
+
if (s.startsWith("w:"))
|
|
435
|
+
this.constrainedWitnesses.add(s.slice(2));
|
|
436
|
+
for (const w of info.rawWitness)
|
|
437
|
+
this.constrainedWitnesses.add(w);
|
|
438
|
+
}
|
|
439
|
+
/** A value becomes public here (disclose() or a ledger write). */
|
|
440
|
+
sink(info, loc, frame, isWrite = false, target) {
|
|
441
|
+
if (isWrite)
|
|
442
|
+
frame.nullifier.writes = true;
|
|
443
|
+
if (info.identity && frame.exported !== false) {
|
|
444
|
+
const uses = this.identityUses.get(info.identity) ?? new Map();
|
|
445
|
+
const circuit = frame.stack[0];
|
|
446
|
+
if (!uses.has(circuit))
|
|
447
|
+
uses.set(circuit, frame.anchor ?? loc);
|
|
448
|
+
this.identityUses.set(info.identity, uses);
|
|
449
|
+
}
|
|
450
|
+
this.recordDisclosure(info, loc, frame, isWrite ? "ledger write" : "disclose", target);
|
|
451
|
+
for (const w of info.rawWitness)
|
|
452
|
+
if (!this.witnessSinks.has(w))
|
|
453
|
+
this.witnessSinks.set(w, frame.anchor ?? loc);
|
|
454
|
+
if (info.rawSecret?.size) {
|
|
455
|
+
const names = [...info.rawSecret].map((s) => (s.startsWith("w:") ? `witness '${s.slice(2)}()'` : `parameter '${s.slice(2)}'`));
|
|
456
|
+
this.report("MS007", frame.anchor ?? loc, `The raw value of ${names.join(" and ")} is made public here, and the name says it is a secret. Anyone can read it from the ledger or transaction. Publish a domain-separated hash or a commitment of it instead, or keep it private.`);
|
|
457
|
+
}
|
|
458
|
+
if (info.lowHash && !frame.silent) {
|
|
459
|
+
this.report("MS003", info.lowHash, `This hash only covers low-entropy private values (about ${info.lowHashBits ?? "?"} bit${info.lowHashBits === 1 ? "" : "s"} of entropy), and it is made public. Anyone can hash every possible input and recover the value. Use persistentCommit(value, randomness) with fresh 32-byte randomness instead.`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
// ---------- expressions ----------
|
|
463
|
+
evalExpr(e, frame) {
|
|
464
|
+
switch (e.kind) {
|
|
465
|
+
case "number":
|
|
466
|
+
case "string":
|
|
467
|
+
return empty();
|
|
468
|
+
case "ident":
|
|
469
|
+
return this.evalIdent(e.name, frame);
|
|
470
|
+
case "member": {
|
|
471
|
+
if (e.object.kind === "ident" && this.enums.has(e.object.name))
|
|
472
|
+
return empty();
|
|
473
|
+
const obj = this.evalExpr(e.object, frame);
|
|
474
|
+
return { ...obj, sources: new Set(obj.sources), rawWitness: new Set(obj.rawWitness), type: undefined };
|
|
475
|
+
}
|
|
476
|
+
case "index": {
|
|
477
|
+
const obj = this.evalExpr(e.object, frame);
|
|
478
|
+
const idx = this.evalExpr(e.index, frame);
|
|
479
|
+
const out = union([obj, idx]);
|
|
480
|
+
out.ownpkDirect = obj.ownpkDirect;
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
case "vector":
|
|
484
|
+
return union(e.elements.map((x) => this.evalExpr(x, frame)));
|
|
485
|
+
case "struct":
|
|
486
|
+
return union(e.fields.map((f) => this.evalExpr(f.value, frame)));
|
|
487
|
+
case "spread":
|
|
488
|
+
return this.evalExpr(e.arg, frame);
|
|
489
|
+
case "unary": {
|
|
490
|
+
const a = this.evalExpr(e.arg, frame);
|
|
491
|
+
return { ...a, ownpkDirect: false };
|
|
492
|
+
}
|
|
493
|
+
case "cast": {
|
|
494
|
+
const a = this.evalExpr(e.expr, frame);
|
|
495
|
+
const tb = this.typeBits(e.type);
|
|
496
|
+
const bits = a.bits === undefined ? tb : tb === undefined ? a.bits : Math.min(a.bits, tb);
|
|
497
|
+
return { ...a, bits, type: e.type };
|
|
498
|
+
}
|
|
499
|
+
case "cond":
|
|
500
|
+
return union([this.evalExpr(e.test, frame), this.evalExpr(e.then, frame), this.evalExpr(e.else, frame)]);
|
|
501
|
+
case "binary": {
|
|
502
|
+
const l = this.evalExpr(e.left, frame);
|
|
503
|
+
const r = this.evalExpr(e.right, frame);
|
|
504
|
+
// Comparing ownPublicKey() to a stored or supplied key is authorization;
|
|
505
|
+
// comparing it to a constant (e.g. the zero key) is only a sanity check.
|
|
506
|
+
if ((e.op === "==" || e.op === "!=") && ((l.ownpkDirect && !r.constant) || (r.ownpkDirect && !l.constant))) {
|
|
507
|
+
this.ownpkCompare(l.ownpkDirect ? e.left.loc : e.right.loc, frame);
|
|
508
|
+
}
|
|
509
|
+
const out = union([l, r]);
|
|
510
|
+
out.ownpkDirect = false;
|
|
511
|
+
if (["==", "!=", "<", "<=", ">", ">=", "&&", "||"].includes(e.op)) {
|
|
512
|
+
out.bits = isPrivate(out) ? 1 : 0;
|
|
513
|
+
out.rawSecret = undefined; // a comparison reveals one bit, not the secret
|
|
514
|
+
out.identity = undefined;
|
|
515
|
+
}
|
|
516
|
+
return out;
|
|
517
|
+
}
|
|
518
|
+
case "lambda": {
|
|
519
|
+
// Evaluated by the enclosing call (fold/map); standalone it carries no data.
|
|
520
|
+
return unknown();
|
|
521
|
+
}
|
|
522
|
+
case "call":
|
|
523
|
+
return this.evalCall(e, frame);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
evalIdent(name, frame) {
|
|
527
|
+
const local = this.lookup(name, frame);
|
|
528
|
+
if (local)
|
|
529
|
+
return local;
|
|
530
|
+
if (name === "true" || name === "false" || name === "default")
|
|
531
|
+
return empty();
|
|
532
|
+
const ledger = this.resolveName(this.ledgers, name, frame);
|
|
533
|
+
if (ledger) {
|
|
534
|
+
return { sources: new Set([`l:${ledger}`]), rawWitness: new Set(), constant: false, ownpkDirect: false, bits: 0, type: this.ledgers.get(ledger) };
|
|
535
|
+
}
|
|
536
|
+
if (this.enums.has(name))
|
|
537
|
+
return empty();
|
|
538
|
+
return unknown();
|
|
539
|
+
}
|
|
540
|
+
ownpkCompare(loc, frame) {
|
|
541
|
+
if (frame.silent) {
|
|
542
|
+
frame.ownpkCompare = frame.ownpkCompare ?? loc;
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
this.report("MS001", loc, "ownPublicKey() is used to authorize the caller. It is supplied by the prover, so anyone can supply the stored key and pass this check. Prove knowledge of a secret instead: store hash(domain, secret) on the ledger and recompute it from a witness.");
|
|
546
|
+
}
|
|
547
|
+
evalCall(e, frame) {
|
|
548
|
+
const callee = e.callee;
|
|
549
|
+
// method call: x.method(args)
|
|
550
|
+
if (callee.kind === "member") {
|
|
551
|
+
const obj = this.evalExpr(callee.object, frame);
|
|
552
|
+
const args = e.args.map((a) => this.evalExpr(a, frame));
|
|
553
|
+
const root = rootIdent(callee.object);
|
|
554
|
+
const isLedger = root !== undefined && !this.lookup(root, frame) && this.resolveName(this.ledgers, root, frame) !== undefined;
|
|
555
|
+
if (isLedger) {
|
|
556
|
+
if (callee.property === "member" && args.some((a) => a.ownpkDirect))
|
|
557
|
+
this.ownpkCompare(e.loc, frame);
|
|
558
|
+
if (callee.property === "checkRoot" && e.args[0] && !frame.anchor) {
|
|
559
|
+
let path = findPathRootArg(e.args[0]);
|
|
560
|
+
const argRoot = e.args[0].kind === "ident" ? e.args[0].name : undefined;
|
|
561
|
+
if (!path && argRoot)
|
|
562
|
+
path = frame.nullifier.rootVars.get(this.pathKey(argRoot, frame));
|
|
563
|
+
if (path) {
|
|
564
|
+
const key = this.pathKey(path, frame);
|
|
565
|
+
if (!frame.nullifier.checkedPaths.has(key))
|
|
566
|
+
frame.nullifier.checkedPaths.set(key, e.loc);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (LEDGER_READ_METHODS.has(callee.property)) {
|
|
570
|
+
const out = union([obj, ...args]);
|
|
571
|
+
out.rawWitness = new Set();
|
|
572
|
+
out.rawSecret = undefined;
|
|
573
|
+
out.identity = undefined;
|
|
574
|
+
out.bits = callee.property === "member" ? (args.some(isPrivate) ? 1 : 0) : 0;
|
|
575
|
+
out.ownpkDirect = false;
|
|
576
|
+
return out;
|
|
577
|
+
}
|
|
578
|
+
// ledger write: insert, increment, write, push, ...
|
|
579
|
+
frame.nullifier.writes = true;
|
|
580
|
+
for (const a of args)
|
|
581
|
+
this.sink(a, e.loc, frame, true, `${root}.${callee.property}()`);
|
|
582
|
+
return empty();
|
|
583
|
+
}
|
|
584
|
+
const out = union([obj, ...args]);
|
|
585
|
+
out.ownpkDirect = false;
|
|
586
|
+
return out;
|
|
587
|
+
}
|
|
588
|
+
const name = callee.kind === "ident" ? callee.name : undefined;
|
|
589
|
+
if (name === "ownPublicKey") {
|
|
590
|
+
return { sources: new Set(["ownpk"]), rawWitness: new Set(), constant: false, ownpkDirect: true, bits: 0 };
|
|
591
|
+
}
|
|
592
|
+
if (name === "pad" || name === "default")
|
|
593
|
+
return empty();
|
|
594
|
+
if (name === "assert") {
|
|
595
|
+
const infos = e.args.map((a) => this.evalExpr(a, frame));
|
|
596
|
+
if (infos[0])
|
|
597
|
+
this.markConstrained(infos[0]);
|
|
598
|
+
if (e.args[0])
|
|
599
|
+
this.scanAuthorization(e.args[0], false, frame);
|
|
600
|
+
return empty();
|
|
601
|
+
}
|
|
602
|
+
// lambdas passed to fold/map: bind their parameters to the data being iterated
|
|
603
|
+
const lambdas = e.args.filter((a) => a.kind === "lambda");
|
|
604
|
+
const plain = e.args.filter((a) => a.kind !== "lambda").map((a) => this.evalExpr(a, frame));
|
|
605
|
+
if (lambdas.length) {
|
|
606
|
+
const data = union(plain);
|
|
607
|
+
const results = lambdas.map((l) => this.evalLambda(l, data, frame));
|
|
608
|
+
return union([...plain, ...results]);
|
|
609
|
+
}
|
|
610
|
+
const witnessName = name ? this.resolveName(this.witnesses, name, frame) : undefined;
|
|
611
|
+
if (witnessName) {
|
|
612
|
+
const w = this.witnesses.get(witnessName);
|
|
613
|
+
return {
|
|
614
|
+
sources: new Set([`w:${witnessName}`]),
|
|
615
|
+
rawWitness: new Set([witnessName]),
|
|
616
|
+
rawSecret: isSecretName(witnessName.slice(witnessName.lastIndexOf("_") + 1)) || isSecretName(witnessName) ? new Set([`w:${witnessName}`]) : undefined,
|
|
617
|
+
constant: false,
|
|
618
|
+
ownpkDirect: false,
|
|
619
|
+
bits: this.typeBits(w.returnType),
|
|
620
|
+
type: w.returnType,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
if (name && /^merkleTreePathRoot/.test(name)) {
|
|
624
|
+
// the root of a Merkle path: a hash that equals a root already on the ledger
|
|
625
|
+
const out = union(plain);
|
|
626
|
+
out.rawWitness = new Set();
|
|
627
|
+
out.rawSecret = undefined;
|
|
628
|
+
out.identity = undefined;
|
|
629
|
+
out.ownpkDirect = false;
|
|
630
|
+
out.bits = undefined;
|
|
631
|
+
out.protection = "hash";
|
|
632
|
+
return out;
|
|
633
|
+
}
|
|
634
|
+
if (name && HASH_FNS.has(name))
|
|
635
|
+
return this.evalHash(e, plain, frame);
|
|
636
|
+
if (name && COMMIT_FNS.has(name))
|
|
637
|
+
return this.evalCommit(e, plain, frame);
|
|
638
|
+
if (name === "disclose") {
|
|
639
|
+
const v = plain[0] ?? empty();
|
|
640
|
+
this.sink(v, e.loc, frame);
|
|
641
|
+
// After disclose() the value is public: it carries no secret entropy.
|
|
642
|
+
const sources = new Set([...v.sources].filter((x) => !x.startsWith("w:") && !x.startsWith("p:")));
|
|
643
|
+
sources.add("disclosed");
|
|
644
|
+
return { ...v, sources, bits: 0, lowHash: undefined, rawSecret: undefined };
|
|
645
|
+
}
|
|
646
|
+
if (name && WRAPPER_FNS.has(name))
|
|
647
|
+
return union(plain);
|
|
648
|
+
const circuitName = name ? this.resolveName(this.circuits, name, frame) : undefined;
|
|
649
|
+
if (circuitName)
|
|
650
|
+
return this.inlineCircuit(circuitName, plain, e.loc, frame);
|
|
651
|
+
// unknown or standard-library call: the result is derived (e.g. a public key
|
|
652
|
+
// from a secret), so it is no longer the raw secret
|
|
653
|
+
const out = union(plain);
|
|
654
|
+
out.ownpkDirect = false;
|
|
655
|
+
out.rawSecret = undefined;
|
|
656
|
+
out.identity = undefined;
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
/** MS008: look for Merkle membership proofs and nullifier checks inside an assert condition. */
|
|
660
|
+
scanAuthorization(e, negated, frame) {
|
|
661
|
+
if (e.kind === "unary" && e.op === "!")
|
|
662
|
+
return this.scanAuthorization(e.arg, !negated, frame);
|
|
663
|
+
if (e.kind === "call" && e.callee.kind === "ident" && e.callee.name === "disclose" && e.args[0]) {
|
|
664
|
+
return this.scanAuthorization(e.args[0], negated, frame);
|
|
665
|
+
}
|
|
666
|
+
if (e.kind === "binary" && (e.op === "==" || e.op === "!=")) {
|
|
667
|
+
// MS009: `path.leaf == ...` binds the Merkle path to a value
|
|
668
|
+
for (const side of [e.left, e.right]) {
|
|
669
|
+
if (side.kind === "member" && side.property === "leaf") {
|
|
670
|
+
const root = rootIdent(side.object);
|
|
671
|
+
if (root)
|
|
672
|
+
frame.nullifier.boundPaths.add(this.pathKey(root, frame));
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (e.kind === "binary" && (e.op === "&&" || e.op === "||")) {
|
|
678
|
+
this.scanAuthorization(e.left, negated, frame);
|
|
679
|
+
this.scanAuthorization(e.right, negated, frame);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (e.kind === "call" && e.callee.kind === "member") {
|
|
683
|
+
const root = rootIdent(e.callee.object);
|
|
684
|
+
const isLedger = root !== undefined && !this.lookup(root, frame) && this.resolveName(this.ledgers, root, frame) !== undefined;
|
|
685
|
+
if (!isLedger)
|
|
686
|
+
return;
|
|
687
|
+
const method = e.callee.property;
|
|
688
|
+
if (method === "member" && negated)
|
|
689
|
+
frame.nullifier.negMember = true;
|
|
690
|
+
if (method === "checkRoot" && !negated) {
|
|
691
|
+
const args = e.args.map((a) => this.evalExpr(a, frame));
|
|
692
|
+
if (args.some((a) => isPrivate(a) || a.sources.has("disclosed")))
|
|
693
|
+
frame.nullifier.anonAuth = frame.nullifier.anonAuth ?? frame.anchor ?? e.loc;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
/** Paths are tracked by name within one top-level circuit; helper frames get their own namespace. */
|
|
698
|
+
pathKey(name, frame) {
|
|
699
|
+
return frame.depth === 0 ? name : `${frame.stack.join(">")}:${name}`;
|
|
700
|
+
}
|
|
701
|
+
evalLambda(l, data, frame) {
|
|
702
|
+
const vars = new Map();
|
|
703
|
+
for (const p of l.params)
|
|
704
|
+
vars.set(p.name, data);
|
|
705
|
+
frame.scopes.push({ vars });
|
|
706
|
+
let result;
|
|
707
|
+
if (Array.isArray(l.body)) {
|
|
708
|
+
const before = frame.returns.length;
|
|
709
|
+
for (const s of l.body)
|
|
710
|
+
this.execStmt(s, frame);
|
|
711
|
+
result = union(frame.returns.splice(before));
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
result = this.evalExpr(l.body, frame);
|
|
715
|
+
}
|
|
716
|
+
frame.scopes.pop();
|
|
717
|
+
return result;
|
|
718
|
+
}
|
|
719
|
+
/** Flatten the inputs of a hash: vector literals and struct literals become their elements. */
|
|
720
|
+
hashInputs(e) {
|
|
721
|
+
if (e.kind === "vector")
|
|
722
|
+
return e.elements.flatMap((x) => this.hashInputs(x));
|
|
723
|
+
if (e.kind === "struct")
|
|
724
|
+
return e.fields.flatMap((f) => this.hashInputs(f.value));
|
|
725
|
+
return [e];
|
|
726
|
+
}
|
|
727
|
+
evalHash(e, argInfos, frame) {
|
|
728
|
+
const inputs = e.args.flatMap((a) => this.hashInputs(a));
|
|
729
|
+
const infos = inputs.map((x) => this.evalExpr(x, frame));
|
|
730
|
+
const all = union(infos.length ? infos : argInfos);
|
|
731
|
+
// MS005: decided at the end, because a helper circuit may receive its tag
|
|
732
|
+
// as an argument from the caller (seen when the helper is inlined).
|
|
733
|
+
if (!frame.anchor) {
|
|
734
|
+
const key = `${e.loc.line}:${e.loc.col}`;
|
|
735
|
+
const site = this.hashSites.get(key) ?? { loc: e.loc, tagged: false, private: false };
|
|
736
|
+
if (infos.some((i) => i.constant))
|
|
737
|
+
site.tagged = true;
|
|
738
|
+
if (isPrivate(all))
|
|
739
|
+
site.private = true;
|
|
740
|
+
this.hashSites.set(key, site);
|
|
741
|
+
}
|
|
742
|
+
const out = {
|
|
743
|
+
sources: new Set(all.sources),
|
|
744
|
+
rawWitness: new Set(),
|
|
745
|
+
constant: all.constant,
|
|
746
|
+
ownpkDirect: false,
|
|
747
|
+
bits: all.bits === undefined ? undefined : Math.min(all.bits, 256),
|
|
748
|
+
protection: "hash",
|
|
749
|
+
};
|
|
750
|
+
// MS010: deterministic in the secret alone (no fresh randomness)
|
|
751
|
+
const privateInputs = infos.filter((i) => isPrivate(i));
|
|
752
|
+
if (privateInputs.length && privateInputs.every((i) => (i.rawSecret?.size ?? 0) > 0 || i.identity)) {
|
|
753
|
+
out.identity = `${frame.prefix}${e.loc.line}:${e.loc.col}`;
|
|
754
|
+
}
|
|
755
|
+
// MS003 candidate: every input is constant, public, or low-entropy. If a
|
|
756
|
+
// high-entropy secret is mixed in, the result is safe even when an input
|
|
757
|
+
// was itself a low-entropy hash.
|
|
758
|
+
if (isPrivate(all) && all.bits !== undefined && all.bits <= LOW_ENTROPY_BITS) {
|
|
759
|
+
out.lowHash = all.lowHash ?? frame.anchor ?? e.loc;
|
|
760
|
+
out.lowHashBits = all.bits;
|
|
761
|
+
}
|
|
762
|
+
return out;
|
|
763
|
+
}
|
|
764
|
+
evalCommit(e, argInfos, frame) {
|
|
765
|
+
const value = argInfos[0] ?? empty();
|
|
766
|
+
const rand = argInfos[1] ?? unknown();
|
|
767
|
+
const randExpr = e.args[1];
|
|
768
|
+
if (!frame.silent && randExpr) {
|
|
769
|
+
if (rand.constant) {
|
|
770
|
+
this.report("MS004", e.loc, "This commitment uses constant randomness, so it hides nothing: anyone can recompute it for every candidate value. Use fresh random bytes from a witness.");
|
|
771
|
+
}
|
|
772
|
+
else if (rand.sources.size > 0 && !isPrivate(rand)) {
|
|
773
|
+
this.report("MS004", e.loc, "This commitment's randomness comes from public ledger state, so anyone can recompute the commitment for every candidate value. Use secret randomness from a witness or private input.");
|
|
774
|
+
}
|
|
775
|
+
else if (rand.bits !== undefined && rand.bits < STRONG_RANDOMNESS_BITS) {
|
|
776
|
+
this.report("MS004", e.loc, `This commitment's randomness has only about ${rand.bits} bits of entropy. Use at least 32 random bytes (Bytes<32>).`, undefined, "medium");
|
|
777
|
+
}
|
|
778
|
+
else {
|
|
779
|
+
const key = exprText(randExpr);
|
|
780
|
+
const valueKey = exprText(e.args[0]);
|
|
781
|
+
const prev = frame.commitRand.get(key);
|
|
782
|
+
if (prev && prev.value !== valueKey) {
|
|
783
|
+
this.report("MS004", e.loc, `The same randomness '${key}' is used by another commitment on line ${prev.loc.line}. Reusing randomness lets observers link the two commitments. Derive separate randomness for each (e.g. hash(tag, salt)).`, "medium", "medium");
|
|
784
|
+
}
|
|
785
|
+
else if (!prev) {
|
|
786
|
+
frame.commitRand.set(key, { loc: e.loc, value: valueKey });
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// A commitment with good randomness hides the value; its entropy is not reversible.
|
|
791
|
+
return {
|
|
792
|
+
sources: new Set([...value.sources, ...rand.sources]),
|
|
793
|
+
rawWitness: new Set(),
|
|
794
|
+
constant: false,
|
|
795
|
+
ownpkDirect: false,
|
|
796
|
+
bits: undefined,
|
|
797
|
+
protection: "commit",
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
inlineCircuit(name, args, loc, frame) {
|
|
801
|
+
const entry = this.circuits.get(name);
|
|
802
|
+
const c = entry.decl;
|
|
803
|
+
if (!c.body || frame.depth >= MAX_INLINE_DEPTH || frame.stack.includes(name)) {
|
|
804
|
+
// Too deep or recursive: treat the result as derived from the arguments.
|
|
805
|
+
const out = union(args);
|
|
806
|
+
out.ownpkDirect = false;
|
|
807
|
+
out.rawWitness = new Set();
|
|
808
|
+
out.rawSecret = undefined;
|
|
809
|
+
return out;
|
|
810
|
+
}
|
|
811
|
+
const vars = new Map();
|
|
812
|
+
c.params.forEach((p, i) => {
|
|
813
|
+
const a = args[i] ?? unknown();
|
|
814
|
+
vars.set(p.name, { ...a, type: p.type ?? a.type });
|
|
815
|
+
});
|
|
816
|
+
const inner = {
|
|
817
|
+
name,
|
|
818
|
+
scopes: [{ vars }],
|
|
819
|
+
silent: true,
|
|
820
|
+
depth: frame.depth + 1,
|
|
821
|
+
stack: [...frame.stack, name],
|
|
822
|
+
returns: [],
|
|
823
|
+
commitRand: new Map(),
|
|
824
|
+
prefix: entry.prefix,
|
|
825
|
+
anchor: frame.anchor ?? (entry.external ? loc : undefined),
|
|
826
|
+
nullifier: frame.nullifier,
|
|
827
|
+
exported: frame.exported,
|
|
828
|
+
};
|
|
829
|
+
for (const s of c.body)
|
|
830
|
+
this.execStmt(s, inner);
|
|
831
|
+
if (inner.ownpkCompare) {
|
|
832
|
+
if (frame.silent)
|
|
833
|
+
frame.ownpkCompare = frame.ownpkCompare ?? loc;
|
|
834
|
+
else
|
|
835
|
+
this.report("MS001", loc, `ownPublicKey() is passed to '${name}()', which compares it to authorize the caller (${inner.anchor ? "in an imported module" : `line ${inner.ownpkCompare.line}`}). It is supplied by the prover, so this check can be bypassed. Prove knowledge of a secret instead.`);
|
|
836
|
+
}
|
|
837
|
+
const ret = inner.returns.length ? union(inner.returns) : empty();
|
|
838
|
+
if (c.returnType) {
|
|
839
|
+
const tb = this.typeBits(c.returnType);
|
|
840
|
+
if (ret.bits !== undefined && tb !== undefined)
|
|
841
|
+
ret.bits = Math.min(ret.bits, tb);
|
|
842
|
+
ret.type = c.returnType;
|
|
843
|
+
}
|
|
844
|
+
return ret;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
/** In `merkleTreePathRoot<n, T>(path)` (possibly wrapped in disclose), return `path`'s variable name. */
|
|
848
|
+
function findPathRootArg(e) {
|
|
849
|
+
if (e.kind === "call" && e.callee.kind === "ident") {
|
|
850
|
+
if (e.callee.name === "disclose" && e.args[0])
|
|
851
|
+
return findPathRootArg(e.args[0]);
|
|
852
|
+
if (/^merkleTreePathRoot/.test(e.callee.name) && e.args[0])
|
|
853
|
+
return rootIdent(e.args[0]);
|
|
854
|
+
}
|
|
855
|
+
return undefined;
|
|
856
|
+
}
|
|
857
|
+
function rootIdent(e) {
|
|
858
|
+
if (e.kind === "ident")
|
|
859
|
+
return e.name;
|
|
860
|
+
if (e.kind === "member" || e.kind === "index")
|
|
861
|
+
return rootIdent(e.object);
|
|
862
|
+
return undefined;
|
|
863
|
+
}
|
|
864
|
+
export function exprText(e) {
|
|
865
|
+
switch (e.kind) {
|
|
866
|
+
case "ident":
|
|
867
|
+
return e.name;
|
|
868
|
+
case "number":
|
|
869
|
+
return e.value;
|
|
870
|
+
case "string":
|
|
871
|
+
return JSON.stringify(e.value);
|
|
872
|
+
case "member":
|
|
873
|
+
return `${exprText(e.object)}.${e.property}`;
|
|
874
|
+
case "index":
|
|
875
|
+
return `${exprText(e.object)}[${exprText(e.index)}]`;
|
|
876
|
+
case "call":
|
|
877
|
+
return `${exprText(e.callee)}(${e.args.map(exprText).join(", ")})`;
|
|
878
|
+
case "vector":
|
|
879
|
+
return `[${e.elements.map(exprText).join(", ")}]`;
|
|
880
|
+
case "struct":
|
|
881
|
+
return `${e.type.name} { ${e.fields.map((f) => `${f.name}: ${exprText(f.value)}`).join(", ")} }`;
|
|
882
|
+
case "binary":
|
|
883
|
+
return `${exprText(e.left)} ${e.op} ${exprText(e.right)}`;
|
|
884
|
+
case "unary":
|
|
885
|
+
return `${e.op}${exprText(e.arg)}`;
|
|
886
|
+
case "cast":
|
|
887
|
+
return `${exprText(e.expr)} as ${e.type.text}`;
|
|
888
|
+
case "cond":
|
|
889
|
+
return `${exprText(e.test)} ? ${exprText(e.then)} : ${exprText(e.else)}`;
|
|
890
|
+
case "spread":
|
|
891
|
+
return `...${exprText(e.arg)}`;
|
|
892
|
+
case "lambda":
|
|
893
|
+
return "(lambda)";
|
|
894
|
+
}
|
|
895
|
+
}
|