doppelcode 0.7.0b5.post1__py3-none-any.whl

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.
@@ -0,0 +1,899 @@
1
+ """Secret constants: numeric literals and tables that must not reach the AI.
2
+
3
+ Marked values (line tag ``doppel:secret``, or the old ``cobf:secret``, ``secret_symbols``, ``secret_values``) are replaced in the
4
+ twin by aliases ``K_NNNN``; the vault keeps the literal text. A twin-only file (``doppel_secrets.py`` /
5
+ ``doppel_secrets.h``) gives the aliases neutral dummy values so the twin still parses, compiles and runs.
6
+
7
+ Every occurrence of a marked scalar value in code is hidden (each site with its own alias), so the
8
+ value never appears in the twin. Tables are hidden as a whole. The common values 0, 1, -1, 2 and 0.5
9
+ are never hidden by value (only at a tagged or named site) and never count as leaks.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import re
16
+ from dataclasses import dataclass, field
17
+
18
+ from . import lexer
19
+ from . import pyparse
20
+
21
+ SECRET_PREFIX = "K_"
22
+ SECRET_ALIAS_RE = re.compile(r"K_\d{4,}")
23
+ TAG = "doppel:secret"
24
+ LEGACY_TAG = "cobf:secret" # still read in the original's comments
25
+ COMMON = {0.0, 1.0, -1.0, 2.0, 0.5}
26
+ HINT_WORDS = ("threshold", "coef", "gain", "alpha", "beta", "limit", "cutoff", "freq")
27
+ PY_MODULE = "doppel_secrets"
28
+ LEGACY_PY_MODULE = "cobf_secrets"
29
+ PY_IMPORT_RE = re.compile(r"^from (?:doppel|cobf)_secrets import [\w, ]* # (?:doppel|cobf)[ \t]*\r?\n", re.M)
30
+ TWIN_NOTE = "DoppelCode: twin-only dummy values. Real values stay on the owner's PC. Do not edit."
31
+
32
+ # Numbers inside comments, strings and text: 145, 0x91, 1.45e2, .5 (also "145Hz").
33
+ TEXT_NUM_RE = re.compile(r"(?<![\w.])(?:0[xX][0-9a-fA-F]+|(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?)(?![\d.])")
34
+ # Format specifications are never numbers of the program: printf "%.2f" "%-8.3lf" "%5d",
35
+ # Python / C++ std::format "{:.2f}" "{0:>8.3f}" "{value:.1%}".
36
+ PRINTF_SPEC_RE = re.compile(r"%[-+ #0']*(?:\d+|\*)?(?:\.(?:\d+|\*))?(?:hh|h|ll|l|L|q|j|z|t|I64|I32)?"
37
+ r"[diouxXeEfFgGaAcspn%]")
38
+ # A replacement field's format spec (Python str.format / f-string, C++ std::format): only the part after
39
+ # ':' is protected, and only when it follows the spec grammar and either ends in a presentation type or
40
+ # has no precision - so JSON / dict text ('{"gain": 0.97}', "{a: 0.97}") is never protected. The field
41
+ # itself ("{0.97 * x:.2f}") is still scanned.
42
+ _SPEC_HEAD = r"(?:[^{}]?[<>=^])?[-+ ]?z?#?0?\d*[_,]?"
43
+ BRACE_SPEC_RE = re.compile(r"\{[^{}:]*:(?P<spec>" + _SPEC_HEAD + r"(?:\.\d+)?[bcdeEfFgGnosxX%]|" + _SPEC_HEAD
44
+ + r")\}")
45
+
46
+ # Well-known constants that name an algorithm (sequence of values, in order).
47
+ TELLTALE = {
48
+ "AES S-box": [0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B],
49
+ "AES inverse S-box": [0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36],
50
+ "AES Rcon": [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36],
51
+ "FIPS-197 plaintext": [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77],
52
+ "FIPS-197 AES-128 ciphertext": [0x69, 0xC4, 0xE0, 0xD8, 0x6A, 0x7B, 0x04, 0x30],
53
+ "FIPS-197 AES-128 key": [0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6],
54
+ "CRC-32 polynomial": [0xEDB88320],
55
+ "CRC-32 polynomial (normal)": [0x04C11DB7],
56
+ "SHA-256 IV": [0x6A09E667],
57
+ "MD5 / SHA-1 IV": [0x67452301],
58
+ }
59
+
60
+
61
+ def num_value(text: str) -> float | None:
62
+ """Numeric value of a Python / C literal ('0x1bU' -> 27, '1.0f' -> 1.0, '1_000' -> 1000)."""
63
+ t = text.replace("_", "").replace("'", "")
64
+ if t.lower().startswith("0x"):
65
+ t = t.rstrip("uUlL")
66
+ try:
67
+ return float(int(t, 16))
68
+ except ValueError:
69
+ return None
70
+ if t[-1:] in "jJ":
71
+ return None
72
+ t = re.sub(r"[uUlLfF]+$", "", t)
73
+ try:
74
+ if re.fullmatch(r"0[0-7]+", t):
75
+ return float(int(t, 8))
76
+ if re.fullmatch(r"0[bB][01]+", t):
77
+ return float(int(t, 2))
78
+ if re.fullmatch(r"0[oO][0-7]+", t):
79
+ return float(int(t, 8))
80
+ return float(t)
81
+ except ValueError:
82
+ return None
83
+
84
+
85
+ def is_float_text(text: str) -> bool:
86
+ t = text.lower()
87
+ return not t.startswith("0x") and ("." in t or "e" in t or t.endswith("f"))
88
+
89
+
90
+ def num_key(text: str) -> tuple[float, bool] | None:
91
+ """What a marked value matches: the value and whether it is written as a float. "3.0", "3." and
92
+ "3.0f" are one key; the integer 3 is another, so marking 3.0 never hides loop bounds or indexes."""
93
+ v = num_value(text)
94
+ return None if v is None else (v, is_float_text(text))
95
+
96
+
97
+ def value_keys(values) -> set[tuple[float, bool]]:
98
+ """secret_values from the config (strings or JSON numbers) -> keys."""
99
+ return {k for k in (num_key(str(x)) for x in values) if k is not None and k[0] not in COMMON}
100
+
101
+
102
+ def small_int(v: float) -> bool:
103
+ """0..15 and their negatives: indexes, loop bounds, symbol numbers - never hidden as table elements."""
104
+ return v.is_integer() and abs(v) < 16
105
+
106
+
107
+ def power_of_two(v: float) -> bool:
108
+ """32, 0x80, 256, 4096: sizes and bit masks - generic, never hidden as table elements."""
109
+ return v.is_integer() and v > 0 and (int(v) & (int(v) - 1)) == 0
110
+
111
+
112
+ def _telling_small_table(text: str, lang: str) -> bool:
113
+ """3..7 numbers, not an arithmetic progression, with a value other than 0 / 1 / a power of two: a
114
+ target sequence {10, 5, 3, 1}, a few tuned gains."""
115
+ vals = [num_value(t.text) for t, _, _ in _tokens_with_offsets(text, lang) if t.kind == lexer.NUMBER]
116
+ vals = [v for v in vals if v is not None]
117
+ if not 3 <= len(vals) <= 7 or len({b - a for a, b in zip(vals, vals[1:])}) == 1:
118
+ return False # {0, 1, 2, 3}: an index list, not know-how
119
+ return any(abs(v) not in (0, 1) and not power_of_two(abs(v)) for v in vals)
120
+
121
+
122
+ def table_keys(sites: list[Site], lang: str) -> set[tuple[float, bool]]:
123
+ """Keys of the elements of the secret tables among `sites`: a table's values must not show up as
124
+ literals elsewhere (pilot round 2: a test generator hard-coded 4 of the 16 secret tones)."""
125
+ out: set[tuple[float, bool]] = set()
126
+ for s in sites:
127
+ if s.kind == "array":
128
+ for t, _, _ in _tokens_with_offsets(s.text, lang):
129
+ k = num_key(t.text) if t.kind == lexer.NUMBER else None
130
+ if k is not None and k[0] not in COMMON and not small_int(k[0]) and not power_of_two(k[0]):
131
+ out.add(k)
132
+ return out
133
+
134
+
135
+ _TABLE_NAME_RE = re.compile(r"(\w+)\s*(?:\[[^\]]*\]\s*)*(?::[^=\n]*)?=\s*$")
136
+
137
+
138
+ def table_name(src: str, start: int) -> str | None:
139
+ """`const int target_sequence[] = {...}` / `TABLE = [...]`: the name the table at `start` is assigned to."""
140
+ m = _TABLE_NAME_RE.search(src[max(0, start - 200):start])
141
+ return m.group(1) if m else None
142
+
143
+
144
+ def local_small_values(marked) -> dict[str, list[tuple[int, int, set[float]]]]:
145
+ """Small integer elements of secret tables ({10, 5, 3, 1}) are too common to hide everywhere, but in the
146
+ strings and comments of a function that uses the table - its name, one of its other values, or a table
147
+ linked to it by indexing (`frequencies[target_sequence[i]]`) - they tell the table (pilot round 2: a test
148
+ generator printed "Symbol 10 / 5 / 3"). `marked`: (file, source, FileSecrets) of each file.
149
+ -> file -> [(body start, body end, small values to hide in that body's text)]."""
150
+ from . import ledger
151
+ tables: list[tuple[str | None, set[float], set[float]]] = []
152
+ for f, src, fs in marked:
153
+ for s in fs.sites:
154
+ if s.kind != "array":
155
+ continue
156
+ vals = array_values(s.text, f.mode)
157
+ small = {v for v in vals if small_int(v) and v not in COMMON}
158
+ big = {v for v in vals if not (small_int(v) or power_of_two(abs(v))) and v not in COMMON}
159
+ tables.append((table_name(src, s.start), small, big))
160
+ if not any(small for _, small, _ in tables):
161
+ return {}
162
+ group = list(range(len(tables)))
163
+
164
+ def root(i: int) -> int:
165
+ while group[i] != i:
166
+ i = group[i]
167
+ return i
168
+ every = "\n".join(src for _, src, _ in marked)
169
+ for i, (a, _, _) in enumerate(tables):
170
+ for j, (b, _, _) in enumerate(tables):
171
+ if a and b and i != j and re.search(rf"\b{re.escape(a)}\s*\[[^\]]*\b{re.escape(b)}\b", every):
172
+ group[root(i)] = root(j)
173
+ groups: dict[int, tuple[set[str], set[float], set[float]]] = {}
174
+ for i, (name, small, big) in enumerate(tables):
175
+ g = groups.setdefault(root(i), (set(), set(), set()))
176
+ if name:
177
+ g[0].add(name)
178
+ g[1].update(small)
179
+ g[2].update(big)
180
+ groups = {k: g for k, g in groups.items() if g[1]}
181
+ out: dict[str, list[tuple[int, int, set[float]]]] = {}
182
+ for f, src, fs in marked:
183
+ arrays = [(s.start, s.end) for s in fs.sites if s.kind == "array"]
184
+ toks = [(t, pos) for t, pos, _ in _tokens_with_offsets(src, f.mode)
185
+ if t.kind in (lexer.IDENT, lexer.NUMBER) and not any(a <= pos < b for a, b in arrays)]
186
+ for fn in ledger.functions(src, f.mode):
187
+ if fn.body_start < 0 or not fn.body_end:
188
+ continue
189
+ body = [t for t, pos in toks if fn.body_start <= pos < fn.body_end]
190
+ names = {t.text for t in body if t.kind == lexer.IDENT}
191
+ nums = {num_value(t.text) for t in body if t.kind == lexer.NUMBER}
192
+ hide: set[float] = set()
193
+ for tnames, small, big in groups.values():
194
+ if names & tnames or nums & big:
195
+ hide |= small
196
+ if hide:
197
+ out.setdefault(f.rel, []).append((fn.body_start, fn.body_end, hide))
198
+ return out
199
+
200
+
201
+ def format_spans(s: str) -> list[tuple[int, int]]:
202
+ """Format specifications in a text: printf conversions and the spec part of replacement fields."""
203
+ spans = [m.span() for m in PRINTF_SPEC_RE.finditer(s)]
204
+ spans += [m.span("spec") for m in BRACE_SPEC_RE.finditer(s)]
205
+ return sorted(spans)
206
+
207
+
208
+ def text_numbers(s: str):
209
+ """Numbers in a comment / string / text, outside format specifications."""
210
+ spans = format_spans(s)
211
+ for m in TEXT_NUM_RE.finditer(s):
212
+ if not any(a <= m.start() < b for a, b in spans):
213
+ yield m
214
+
215
+
216
+ def key_hit(k: tuple[float, bool] | None, marked: set[tuple[float, bool]]) -> bool:
217
+ """A literal with key k is marked: same value and form, or any form of an integer mark ("145" hides
218
+ 145, 145.0, 0x91 and 1.45e2; only a float mark "3.0" spares the integer 3)."""
219
+ return k is not None and (k in marked or (k[0], False) in marked)
220
+
221
+
222
+ def sub_text_numbers(s: str, repl) -> str:
223
+ """Replace numbers in text (repl(match) -> str or None), leaving format specifications alone."""
224
+ out, last = [], 0
225
+ for m in text_numbers(s):
226
+ new = repl(m)
227
+ if new is not None:
228
+ out += [s[last:m.start()], new]
229
+ last = m.end()
230
+ return "".join(out) + s[last:] if out else s
231
+
232
+
233
+ @dataclass
234
+ class Site:
235
+ start: int # offset of the literal (or the whole table) in the original file
236
+ end: int
237
+ text: str # exact original text
238
+ kind: str # "scalar" | "array"
239
+ line: int
240
+ key: str = "" # stable identity: file | function | text | n
241
+ count: int = 1 # number of elements (arrays)
242
+ is_float: bool = False
243
+
244
+
245
+ @dataclass
246
+ class FileSecrets:
247
+ sites: list[Site] = field(default_factory=list)
248
+ insert_after_line: int = 0 # Python: the twin's import line goes after this line
249
+
250
+
251
+ @dataclass
252
+ class Candidate:
253
+ rel: str
254
+ line: int
255
+ text: str
256
+ rule: str
257
+ symbol: str | None = None
258
+ function: str = "" # enclosing function ("" = file scope), filled by Project.secret_candidates
259
+
260
+
261
+ # Ranking of `secrets suggest` (large projects have thousands of candidates): tables first, then known
262
+ # algorithm constants, then values compared with a variable (thresholds), then the rest.
263
+ RULE_RANK = {"coefficient table": 0, "small table": 0, "known algorithm constant": 1,
264
+ "compared with a variable": 2, "name suggests a tuned value": 3, "tuned float": 4, "hex constant": 5}
265
+ _TABLE_SIZE_RE = re.compile(r"table of (\d+) numbers")
266
+
267
+
268
+ def table_size(c: Candidate) -> int:
269
+ m = _TABLE_SIZE_RE.fullmatch(c.text)
270
+ return int(m.group(1)) if m else 0
271
+
272
+
273
+ def rank_key(c: Candidate):
274
+ """Sort key: rule rank, larger tables first, then file and line."""
275
+ return RULE_RANK.get(c.rule, 9), -table_size(c), c.rel, c.line
276
+
277
+
278
+ def candidate_marks(cands) -> tuple[set[tuple[float, bool]], set[str]]:
279
+ """What marking these candidates means: the values (num_key) and the names (tables, tuned names)."""
280
+ values = {num_key(c.text) for c in cands if not table_size(c) and c.rule != "known algorithm constant"}
281
+ return {k for k in values if k is not None and k[0] not in COMMON}, {c.symbol for c in cands if c.symbol}
282
+
283
+
284
+ # ---------------------------------------------------------------------------------------------- tokens
285
+ def _tokens_with_offsets(src: str, lang: str):
286
+ out, pos, line = [], 0, 1
287
+ for t in lexer.tokenize(src, lang):
288
+ out.append((t, pos, line))
289
+ pos += len(t.text)
290
+ line += t.text.count("\n")
291
+ return out
292
+
293
+
294
+ def _line_starts(src: str) -> list[int]:
295
+ starts = [0]
296
+ for m in re.finditer("\n", src):
297
+ starts.append(m.end())
298
+ return starts
299
+
300
+
301
+ def _offset(src_lines: list[str], starts: list[int], lineno: int, col_bytes: int) -> int:
302
+ """AST (line, UTF-8 byte column) -> character offset."""
303
+ line = src_lines[lineno - 1] if lineno - 1 < len(src_lines) else ""
304
+ col = len(line.encode("utf-8", errors="surrogateescape")[:col_bytes].decode("utf-8", errors="ignore"))
305
+ return starts[lineno - 1] + col
306
+
307
+
308
+ def _numeric_const(node) -> bool:
309
+ return (isinstance(node, ast.Constant) and isinstance(node.value, (int, float))
310
+ and not isinstance(node.value, bool))
311
+
312
+
313
+ def _numeric_display(node) -> bool:
314
+ """[1.5, -2, 3] / (1, 2): a table of plain numbers with 2+ elements."""
315
+ if not isinstance(node, (ast.List, ast.Tuple)) or len(node.elts) < 2:
316
+ return False
317
+ return all(_numeric_const(e) or (isinstance(e, ast.UnaryOp) and isinstance(e.op, (ast.USub, ast.UAdd))
318
+ and _numeric_const(e.operand)) for e in node.elts)
319
+
320
+
321
+ def _target_names(node) -> list[str]:
322
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
323
+ out = []
324
+ for t in targets:
325
+ for n in ast.walk(t):
326
+ if isinstance(n, ast.Name):
327
+ out.append(n.id)
328
+ elif isinstance(n, ast.Attribute):
329
+ out.append(n.attr)
330
+ return out
331
+
332
+
333
+ def _qualnames(tree) -> list[tuple[int, int, str]]:
334
+ """(first line, last line, qualified name) of every function / class, outer first."""
335
+ out = []
336
+
337
+ def visit(node, prefix):
338
+ for child in ast.iter_child_nodes(node):
339
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
340
+ name = prefix + child.name
341
+ out.append((child.lineno, child.end_lineno or child.lineno, name))
342
+ visit(child, name + ".")
343
+ else:
344
+ visit(child, prefix)
345
+ visit(tree, "")
346
+ return out
347
+
348
+
349
+ def _qual_at(quals, line: int) -> str:
350
+ best = ""
351
+ for a, b, name in quals:
352
+ if a <= line <= b:
353
+ best = name # outer first, so the last hit is the innermost
354
+ return best
355
+
356
+
357
+ # ---------------------------------------------------------------------------------------------- Python
358
+ def _python_assignments(tree):
359
+ """(names, value node) for assignments, defaults and keyword arguments."""
360
+ for node in ast.walk(tree):
361
+ if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)) and node.value is not None:
362
+ yield _target_names(node), node.value
363
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
364
+ a = node.args
365
+ pos = a.posonlyargs + a.args
366
+ for arg, default in zip(pos[len(pos) - len(a.defaults):], a.defaults):
367
+ yield [arg.arg], default
368
+ for arg, default in zip(a.kwonlyargs, a.kw_defaults):
369
+ if default is not None:
370
+ yield [arg.arg], default
371
+ elif isinstance(node, ast.Call):
372
+ for kw in node.keywords:
373
+ if kw.arg:
374
+ yield [kw.arg], kw.value
375
+
376
+
377
+ def python_secrets(src: str, rel: str, symbols: set[str], values: set[tuple[float, bool]]) -> FileSecrets:
378
+ try:
379
+ tree = pyparse.parse(src)
380
+ except SyntaxError:
381
+ return FileSecrets()
382
+ lines = src.splitlines(keepends=True)
383
+ starts = _line_starts(src)
384
+ toks = _tokens_with_offsets(src, "python")
385
+ number_at = {pos: (t, line) for t, pos, line in toks if t.kind == lexer.NUMBER}
386
+ tagged = {line for t, _, line in toks if t.kind == lexer.COMMENT and (TAG in t.text or LEGACY_TAG in t.text)}
387
+ quals = _qualnames(tree)
388
+
389
+ scalars: dict[int, Site] = {}
390
+ arrays: list[Site] = []
391
+
392
+ def add_const(node) -> None:
393
+ off = _offset(lines, starts, node.lineno, node.col_offset)
394
+ if off in number_at:
395
+ t, line = number_at[off]
396
+ scalars[off] = Site(off, off + len(t.text), t.text, "scalar", line, is_float=is_float_text(t.text))
397
+
398
+ def add_value(node) -> None:
399
+ if _numeric_display(node):
400
+ a = _offset(lines, starts, node.lineno, node.col_offset)
401
+ b = _offset(lines, starts, node.end_lineno, node.end_col_offset)
402
+ arrays.append(Site(a, b, src[a:b], "array", node.lineno, count=len(node.elts)))
403
+ return
404
+ for n in ast.walk(node):
405
+ if _numeric_const(n):
406
+ add_const(n)
407
+
408
+ # 1. Named symbols (assignments, defaults, keyword arguments).
409
+ if symbols:
410
+ for names, value in _python_assignments(tree):
411
+ if any(n in symbols for n in names):
412
+ add_value(value)
413
+ # 2. Tagged lines: every number on the line; a table that starts there as a whole.
414
+ if tagged:
415
+ for node in ast.walk(tree):
416
+ if getattr(node, "lineno", None) in tagged:
417
+ if _numeric_display(node):
418
+ add_value(node)
419
+ elif _numeric_const(node):
420
+ add_const(node)
421
+ # Tables win over their own elements.
422
+ arrays = _dedupe_arrays(arrays)
423
+ scalars = {o: s for o, s in scalars.items() if not any(a.start <= o < a.end for a in arrays)}
424
+ # 3. Value list, and 4. every other occurrence of a marked scalar value.
425
+ marked = {num_key(s.text) for s in scalars.values()} | values
426
+ marked = {k for k in marked if k is not None and k[0] not in COMMON}
427
+ for off, (t, line) in number_at.items():
428
+ if off in scalars or any(a.start <= off < a.end for a in arrays):
429
+ continue
430
+ if key_hit(num_key(t.text), marked):
431
+ scalars[off] = Site(off, off + len(t.text), t.text, "scalar", line, is_float=is_float_text(t.text))
432
+
433
+ sites = sorted(list(scalars.values()) + arrays, key=lambda s: s.start)
434
+ seen: dict[tuple[str, str], int] = {}
435
+ for s in sites:
436
+ qual = _qual_at(quals, s.line)
437
+ ident = (qual, s.text if s.kind == "scalar" else "array")
438
+ n = seen.get(ident, 0)
439
+ seen[ident] = n + 1
440
+ s.key = f"{rel}|{qual}|{ident[1]}|{n}"
441
+ return FileSecrets(sites, _python_import_line(tree))
442
+
443
+
444
+ def _dedupe_arrays(arrays: list[Site]) -> list[Site]:
445
+ out: list[Site] = []
446
+ for a in sorted(arrays, key=lambda s: (s.start, -(s.end - s.start))):
447
+ if not any(o.start <= a.start and a.end <= o.end for o in out):
448
+ out.append(a)
449
+ return out
450
+
451
+
452
+ def _python_import_line(tree) -> int:
453
+ """Line after which the twin's `from doppel_secrets import ...` goes: after the leading imports
454
+ (and a module docstring / __future__ imports)."""
455
+ last = 0
456
+ for i, node in enumerate(tree.body):
457
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
458
+ last = node.end_lineno or node.lineno
459
+ elif i == 0 and isinstance(node, ast.Expr) and isinstance(getattr(node, "value", None), ast.Constant) \
460
+ and isinstance(node.value.value, str):
461
+ last = node.end_lineno or node.lineno
462
+ else:
463
+ break
464
+ return last
465
+
466
+
467
+ def python_dummy(site: Site) -> str:
468
+ if site.kind == "array":
469
+ return f"[0] * {site.count}" if site.text.lstrip().startswith("[") else f"(0,) * {site.count}"
470
+ return "1.0" if site.is_float else "1"
471
+
472
+
473
+ def python_twin_module(entries: dict[str, str]) -> str:
474
+ """entries: alias -> dummy expression."""
475
+ lines = [f"# {TWIN_NOTE}"] + [f"{a} = {d}" for a, d in sorted(entries.items())]
476
+ return "\n".join(lines) + "\n"
477
+
478
+
479
+ def python_import_line(aliases) -> str:
480
+ return f"from {PY_MODULE} import {', '.join(sorted(aliases))} # doppel\n"
481
+
482
+
483
+ def insert_after_line(text: str, line: int, insert: str) -> str:
484
+ parts = text.splitlines(keepends=True)
485
+ line = min(line, len(parts))
486
+ if line and parts and not parts[line - 1].endswith("\n"):
487
+ parts[line - 1] += "\n"
488
+ return "".join(parts[:line]) + insert + "".join(parts[line:])
489
+
490
+
491
+ def strip_python_import(text: str) -> str:
492
+ return PY_IMPORT_RE.sub("", text, count=1)
493
+
494
+
495
+ # ---------------------------------------------------------------------------------------------- suggest
496
+ def _value_seq(toks) -> list[tuple[float, int]]:
497
+ return [(num_value(t.text), line) for t, _, line in toks if t.kind == lexer.NUMBER]
498
+
499
+
500
+ def telltale_hits(toks) -> list[tuple[int, str]]:
501
+ seq = _value_seq(toks)
502
+ vals = [v for v, _ in seq]
503
+ hits = []
504
+ for name, pattern in TELLTALE.items():
505
+ n = len(pattern)
506
+ for i in range(len(vals) - n + 1):
507
+ if vals[i:i + n] == [float(p) for p in pattern]:
508
+ hits.append((seq[i][1], name))
509
+ break
510
+ return hits
511
+
512
+
513
+ def suggest(src: str, rel: str, lang: str) -> list[Candidate]:
514
+ toks = _tokens_with_offsets(src, lang)
515
+ sig = [(t, pos, line) for t, pos, line in toks if t.kind not in (lexer.WS, lexer.NEWLINE, lexer.COMMENT)]
516
+ out: list[Candidate] = []
517
+ found: dict[tuple[int, str], Candidate] = {}
518
+
519
+ def add(line: int, text: str, rule: str, symbol: str | None = None) -> None:
520
+ old = found.get((line, text))
521
+ if old is None:
522
+ found[(line, text)] = c = Candidate(rel, line, text, rule, symbol)
523
+ out.append(c)
524
+ elif RULE_RANK.get(rule, 9) < RULE_RANK.get(old.rule, 9): # the stronger reason wins (ranking)
525
+ old.rule, old.symbol = rule, symbol or old.symbol
526
+
527
+ for i, (t, _, line) in enumerate(sig):
528
+ if t.kind != lexer.NUMBER:
529
+ continue
530
+ v = num_value(t.text)
531
+ if v is None or v in COMMON:
532
+ continue
533
+ if is_float_text(t.text):
534
+ mant = re.split(r"[eE]", t.text.rstrip("fF"))[0]
535
+ digits = mant.replace(".", "").lstrip("0")
536
+ decimals = len(mant.split(".")[1]) if "." in mant else 0
537
+ if (len(digits) >= 3 or decimals >= 2) and not (re.search(r"[eE]", t.text) and len(digits) <= 1):
538
+ add(line, t.text, "tuned float")
539
+ if t.text.lower().startswith("0x") and v >= 0x10 and not power_of_two(v) and not power_of_two(v + 1) \
540
+ and not (v % 0x100 == 0):
541
+ add(line, t.text, "hex constant") # 0x63, 0x1b; not masks like 0xFF / 0x80 / 0x100
542
+ before = "".join(x.text for x, _, _ in sig[max(0, i - 2):i])
543
+ after = "".join(x.text for x, _, _ in sig[i + 1:i + 3])
544
+ if (before.endswith(("<", ">", "<=", ">=")) and not before.endswith(("<<", ">>", "->", "=>"))
545
+ or after.startswith(("<", ">")) and not after.startswith(("<<", ">>"))) \
546
+ and (is_float_text(t.text) or not (small_int(v) or power_of_two(abs(v)))): # loop bounds: i < 4, n <= 256
547
+ add(line, t.text, "compared with a variable")
548
+ for line, name in telltale_hits(toks):
549
+ add(line, name, "known algorithm constant")
550
+ tables: list[tuple[int, int]] = [] # line spans of tables: their elements are not listed one by one
551
+ if lang in ("c", "cpp"):
552
+ hinted = {t.text for t, _, _ in toks if t.kind == lexer.IDENT and any(h in t.text.lower() for h in HINT_WORDS)}
553
+ for site in c_secrets(src, rel, lang, hinted, set(), propagate=False).sites:
554
+ v = num_value(site.text) if site.kind == "scalar" else None
555
+ if site.kind == "scalar" and v not in COMMON:
556
+ name = next((n for n in hinted if re.search(r"\b%s\b" % re.escape(n),
557
+ src.splitlines()[site.line - 1])), None)
558
+ add(site.line, site.text, "name suggests a tuned value", name)
559
+ every = {t.text for t, _, _ in toks if t.kind == lexer.IDENT}
560
+ for site in c_secrets(src, rel, lang, every, set(), propagate=False).sites:
561
+ if site.kind == "array":
562
+ tables.append((site.line, site.line + site.text.count("\n")))
563
+ if site.kind == "array" and (site.count >= 8 or _telling_small_table(site.text, lang)):
564
+ name = re.findall(r"(\w+)\s*(?:\[[^\]]*\])*\s*=\s*$", src[:site.start])
565
+ add(site.line, f"table of {site.count} numbers",
566
+ "coefficient table" if site.count >= 8 else "small table", name[-1] if name else None)
567
+ if lang == "python":
568
+ try:
569
+ tree = pyparse.parse(src)
570
+ except SyntaxError:
571
+ return out
572
+ for names, value in _python_assignments(tree):
573
+ hint = next((n for n in names if any(h in n.lower() for h in HINT_WORDS)), None)
574
+ if hint:
575
+ for n in ast.walk(value):
576
+ if _numeric_const(n) and float(n.value) not in COMMON:
577
+ add(n.lineno, repr(n.value), "name suggests a tuned value", hint)
578
+ if _numeric_display(value):
579
+ tables.append((value.lineno, value.end_lineno or value.lineno))
580
+ if _numeric_display(value) and (len(value.elts) >= 8 or _telling_small_table(
581
+ ast.get_source_segment(src, value) or "", "python")):
582
+ add(value.lineno, f"table of {len(value.elts)} numbers",
583
+ "coefficient table" if len(value.elts) >= 8 else "small table", names[0] if names else None)
584
+ out = [c for c in out if not (c.rule in ("hex constant", "tuned float", "compared with a variable")
585
+ and any(a <= c.line <= b for a, b in tables))]
586
+ return sorted(out, key=lambda c: (c.rel, c.line))
587
+
588
+
589
+ # ---------------------------------------------------------------------------------------------- leaks
590
+ def leak_hits(text: str, lang: str | None, scalars: set[tuple[float, bool]],
591
+ arrays: list[list[float]], table_values: set[float] = frozenset()) -> list[tuple[int, str]]:
592
+ """(line, value text) of every marked value still visible in a twin file."""
593
+ hits: list[tuple[int, str]] = []
594
+ scalars = {k for k in scalars if k[0] not in COMMON}
595
+ as_int = {v for v, is_float in scalars if not is_float}
596
+ any_form = {v for v, _ in scalars}
597
+
598
+ def leaked(text: str, in_text: bool = False) -> bool:
599
+ """Any written form counts (0x91, 1.45e2 leak 145), except that an integer literal is no leak
600
+ of a value marked as a float (3 is not 3.0). In comments / strings a table element counts in
601
+ any form ("400Hz" for a table value 400.0)."""
602
+ k = num_key(text)
603
+ return k is not None and (k[0] in as_int or (k[1] and k[0] in any_form)
604
+ or (in_text and k[0] in table_values))
605
+
606
+ if lang:
607
+ toks = _tokens_with_offsets(text, lang)
608
+ for t, _, line in toks:
609
+ if t.kind == lexer.NUMBER:
610
+ if leaked(t.text):
611
+ hits.append((line, t.text))
612
+ elif t.kind in (lexer.STRING, lexer.COMMENT, lexer.CHAR) or t.kind == "directive_text":
613
+ for m in text_numbers(t.text):
614
+ if leaked(m.group(0), True):
615
+ hits.append((line + t.text.count("\n", 0, m.start()), m.group(0)))
616
+ runs = _number_runs(toks)
617
+ for arr in arrays:
618
+ n = min(len(arr), 4)
619
+ probe = arr[:n]
620
+ if n < 3:
621
+ continue
622
+ for run in runs:
623
+ vals = [v for v, _ in run]
624
+ i = next((i for i in range(len(vals) - n + 1) if vals[i:i + n] == probe), None)
625
+ if i is not None:
626
+ hits.append((run[i][1], "table " + ", ".join(f"{x:g}" for x in probe) + ", ..."))
627
+ break
628
+ else:
629
+ for lineno, line in enumerate(text.splitlines(), 1):
630
+ for m in text_numbers(line):
631
+ if leaked(m.group(0), True):
632
+ hits.append((lineno, m.group(0)))
633
+ return hits
634
+
635
+
636
+ def _number_runs(toks) -> list[list[tuple[float, int]]]:
637
+ """Numbers written as a list (separated only by commas and signs): where a table would show up."""
638
+ runs, cur = [], []
639
+ for t, _, line in toks:
640
+ if t.kind == lexer.NUMBER:
641
+ cur.append((num_value(t.text), line))
642
+ elif t.kind in (lexer.WS, lexer.NEWLINE, lexer.COMMENT) or t.text in (",", "-", "+"):
643
+ continue
644
+ else:
645
+ if len(cur) >= 3:
646
+ runs.append(cur)
647
+ cur = []
648
+ if len(cur) >= 3:
649
+ runs.append(cur)
650
+ return runs
651
+
652
+
653
+ def array_values(text: str, lang: str) -> list[float]:
654
+ return [v for t, _, _ in _tokens_with_offsets(text, lang) if t.kind == lexer.NUMBER
655
+ for v in [num_value(t.text)] if v is not None]
656
+
657
+
658
+ # ---------------------------------------------------------------------------------------------- plan
659
+ class Plan:
660
+ """The secrets of one export: which literal goes to which alias, per file. Aliases are stable: a
661
+ site (file | function | literal | n) keeps its alias across exports; the vault keeps the literal."""
662
+
663
+ def __init__(self, vault, forbidden: set[str]):
664
+ self.vault = vault
665
+ self.forbidden = forbidden
666
+ self.store: dict[str, dict] = vault.data.setdefault("secrets", {})
667
+ # this export's sites only (a site removed from the code drops out); the last export's map keeps
668
+ # the aliases stable
669
+ self._old_sites: dict[str, str] = dict(vault.data.get("secret_sites", {}))
670
+ self.by_site: dict[str, str] = {}
671
+ vault.data["secret_sites"] = self.by_site
672
+ self.by_text: dict[str, str] = vault.data.setdefault("secret_texts", {})
673
+ self.files: dict[str, dict[int, tuple[int, str]]] = {}
674
+ self.imports: dict[str, tuple[int, list[str]]] = {}
675
+ self.dummies: dict[str, dict[str, str]] = {} # language -> alias -> dummy expression
676
+ self.scalars: set[tuple[float, bool]] = set() # num_key of every marked scalar
677
+ self.arrays: list[list[float]] = []
678
+ self.literal_of: dict[str, str] = {} # alias -> literal, for this export
679
+ self.table_values: set[float] = set() # elements of secret tables (text matches by value)
680
+ self.import_lines: dict[str, int] = {} # Python file -> line after which the import goes
681
+ # file -> [(body start, body end, small table elements hidden in that function's text)]
682
+ self.local_small: dict[str, list[tuple[int, int, set[float]]]] = {}
683
+
684
+ @property
685
+ def active(self) -> bool:
686
+ return bool(self.files)
687
+
688
+ def _alias_for(self, key: str, text: str, meta: dict) -> str:
689
+ alias = self.by_site.get(key) or self._old_sites.get(key)
690
+ if alias is None or self.store.get(alias, {}).get("literal") != text:
691
+ alias = self.vault.new_name(SECRET_PREFIX, self.forbidden)
692
+ self.by_site[key] = alias
693
+ self.store[alias] = {"literal": text, **meta}
694
+ return alias
695
+
696
+ def add_python(self, rel: str, fs: FileSecrets) -> None:
697
+ self.add(rel, fs, "python")
698
+
699
+ def add(self, rel: str, fs: FileSecrets, lang: str) -> None:
700
+ self.import_lines[rel] = fs.insert_after_line
701
+ if not fs.sites:
702
+ return
703
+ family = "python" if lang == "python" else "c"
704
+ mapping: dict[int, tuple[int, str]] = {}
705
+ for s in fs.sites:
706
+ meta = {"type": "array" if s.kind == "array" else ("float" if s.is_float else "int"),
707
+ "file": rel, "line": s.line, "lang": family}
708
+ if s.kind == "array":
709
+ meta["count"] = s.count
710
+ alias = self._alias_for(s.key, s.text, meta)
711
+ mapping[s.start] = (s.end, alias)
712
+ self.literal_of[alias] = s.text
713
+ self.dummies.setdefault(family, {})[alias] = python_dummy(s) if family == "python" else c_dummy(s)
714
+ if s.kind == "array":
715
+ self.arrays.append(array_values(s.text, lang))
716
+ else:
717
+ k = num_key(s.text)
718
+ if k is not None and k[0] not in COMMON:
719
+ self.scalars.add(k)
720
+ self.files[rel] = mapping
721
+ self.imports[rel] = (fs.insert_after_line, sorted({a for _, a in mapping.values()}))
722
+
723
+ def text_alias(self, text: str, code: bool = False) -> str | None:
724
+ """A number inside a comment / string / text file that equals a secret value -> its alias.
725
+ ``code``: the number is code inside an f-string field, so the alias also gets a dummy value."""
726
+ k = num_key(text)
727
+ if k is None or not (key_hit(k, self.scalars) or k[0] in self.table_values):
728
+ return None
729
+ alias = self._text_alias(text)
730
+ if code:
731
+ site = Site(0, 0, text, "scalar", 0, is_float=is_float_text(text))
732
+ self.dummies.setdefault("python", {}).setdefault(alias, python_dummy(site))
733
+ meta = self.store[alias]
734
+ if meta.get("type") == "text": # only used in text so far: now it is code too
735
+ meta.update(type="float" if site.is_float else "int", lang="python")
736
+ self.by_site[f"f-string|{text}"] = alias # part of this export's dummy file
737
+ return alias
738
+
739
+ def _text_alias(self, text: str) -> str:
740
+ alias = self.by_text.get(text)
741
+ if alias is None or self.store.get(alias, {}).get("literal") != text:
742
+ alias = next((a for a, lit in sorted(self.literal_of.items()) if lit == text), None)
743
+ if alias is None:
744
+ alias = self.vault.new_name(SECRET_PREFIX, self.forbidden)
745
+ self.store[alias] = {"literal": text, "type": "text"}
746
+ self.by_text[text] = alias
747
+ self.literal_of.setdefault(alias, text)
748
+ return alias
749
+
750
+
751
+ # ---------------------------------------------------------------------------------------------- C / C++
752
+ C_HEADER = "doppel_secrets.h"
753
+ LEGACY_C_HEADER = "cobf_secrets.h"
754
+ C_INCLUDE_RE = re.compile(r'^#include "(?:\.\./)*(?:doppel|cobf)_secrets\.h" /\* (?:doppel|cobf) \*/[ \t]*\r?\n',
755
+ re.M)
756
+ _C_INIT_OK = {",", "-", "+", "{", "}"}
757
+
758
+
759
+ def c_secrets(src: str, rel: str, lang: str, symbols: set[str], values: set[tuple[float, bool]],
760
+ propagate: bool = True) -> FileSecrets:
761
+ toks = _tokens_with_offsets(src, lang)
762
+ sig = [(t, pos, line) for t, pos, line in toks if t.kind not in (lexer.WS, lexer.NEWLINE, lexer.COMMENT)]
763
+ texts = [t.text for t, _, _ in sig]
764
+ tagged = {line for t, _, line in toks if t.kind == lexer.COMMENT and (TAG in t.text or LEGACY_TAG in t.text)}
765
+ # numbers that may be replaced: code and #define values (not #if / #line / #pragma)
766
+ number_idx = [i for i, (t, _, _) in enumerate(sig)
767
+ if t.kind == lexer.NUMBER and t.directive in (None, "define")]
768
+ first_include = next((line for t, _, line in toks if t.kind == lexer.DIRECTIVE and t.text == "include"), 0)
769
+
770
+ def match(i: int, open_: str, close: str) -> int:
771
+ depth = 0
772
+ for j in range(i, len(sig)):
773
+ depth += texts[j] == open_
774
+ depth -= texts[j] == close
775
+ if depth == 0:
776
+ return j
777
+ return len(sig) - 1
778
+
779
+ def numeric_brace(i: int) -> tuple[int, int] | None:
780
+ """sig[i] is '{': (index of the matching '}', number count) if it holds only numbers."""
781
+ j = match(i, "{", "}")
782
+ inner = sig[i:j + 1]
783
+ if all(t.kind == lexer.NUMBER or t.text in _C_INIT_OK for t, _, _ in inner):
784
+ n = sum(t.kind == lexer.NUMBER for t, _, _ in inner)
785
+ return (j, n) if n >= 2 else None
786
+ return None
787
+
788
+ def init_span(i: int) -> range:
789
+ """Indexes of the initializer after the '=' at sig[i] (up to ',' ';' or a closing bracket)."""
790
+ depth, j = 0, i + 1
791
+ while j < len(sig):
792
+ if texts[j] in "([{":
793
+ depth += 1
794
+ elif texts[j] in ")]}":
795
+ if depth == 0:
796
+ break
797
+ depth -= 1
798
+ elif texts[j] in ",;" and depth == 0:
799
+ break
800
+ j += 1
801
+ return range(i + 1, j)
802
+
803
+ scalars: dict[int, Site] = {}
804
+ arrays: list[Site] = []
805
+
806
+ def add_scalar(i: int) -> None:
807
+ t, pos, line = sig[i]
808
+ if t.kind == lexer.NUMBER and t.directive in (None, "define"):
809
+ scalars[pos] = Site(pos, pos + len(t.text), t.text, "scalar", line, is_float=is_float_text(t.text))
810
+
811
+ def add_array(i: int) -> bool:
812
+ hit = numeric_brace(i)
813
+ if not hit:
814
+ return False
815
+ j, n = hit
816
+ start, end = sig[i][1], sig[j][1] + 1
817
+ arrays.append(Site(start, end, src[start:end], "array", sig[i][2], count=n))
818
+ return True
819
+
820
+ def add_init(i_eq: int) -> None:
821
+ span = init_span(i_eq)
822
+ if span and texts[span.start] == "{" and add_array(span.start):
823
+ return
824
+ for k in span:
825
+ add_scalar(k)
826
+
827
+ for i, (t, _, line) in enumerate(sig):
828
+ if t.kind == lexer.IDENT and t.text in symbols:
829
+ if t.directive == "define" and i and sig[i - 1][0].kind == lexer.DIRECTIVE:
830
+ k = i + 1
831
+ while k < len(sig) and sig[k][2] == line and sig[k][0].directive == "define":
832
+ add_scalar(k)
833
+ k += 1
834
+ continue
835
+ k = i + 1
836
+ while k < len(sig) and texts[k] == "[":
837
+ k = match(k, "[", "]") + 1
838
+ if k < len(sig) and texts[k] == "=" and (k + 1 >= len(sig) or texts[k + 1] != "="):
839
+ add_init(k)
840
+ if line in tagged:
841
+ if texts[i] == "=" and i + 1 < len(sig) and texts[i + 1] == "{" and add_array(i + 1):
842
+ continue
843
+ add_scalar(i)
844
+ arrays = _dedupe_arrays(arrays)
845
+ scalars = {o: s for o, s in scalars.items() if not any(a.start <= o < a.end for a in arrays)}
846
+ marked = ({num_key(s.text) for s in scalars.values()} if propagate else set()) | values
847
+ marked = {k for k in marked if k is not None and k[0] not in COMMON}
848
+ for i in number_idx:
849
+ t, pos, _ = sig[i]
850
+ if pos not in scalars and not any(a.start <= pos < a.end for a in arrays) and key_hit(num_key(t.text), marked):
851
+ add_scalar(i)
852
+
853
+ # stable keys: the enclosing function (or file scope) + literal + n
854
+ func_at: dict[int, str] = {}
855
+ depth, cand, current = 0, "", ""
856
+ for i, (t, pos, _) in enumerate(sig):
857
+ if depth == 0 and t.kind == lexer.IDENT and i + 1 < len(sig) and texts[i + 1] == "(":
858
+ cand = t.text
859
+ if texts[i] == "{":
860
+ if depth == 0 and i and texts[i - 1] == ")":
861
+ current = cand
862
+ depth += 1
863
+ elif texts[i] == "}":
864
+ depth = max(0, depth - 1)
865
+ if depth == 0:
866
+ current = ""
867
+ func_at[pos] = current
868
+ sites = sorted(list(scalars.values()) + arrays, key=lambda s: s.start)
869
+ seen: dict[tuple[str, str], int] = {}
870
+ for s in sites:
871
+ qual = func_at.get(s.start, "")
872
+ ident = (qual, s.text if s.kind == "scalar" else "array")
873
+ n = seen.get(ident, 0)
874
+ seen[ident] = n + 1
875
+ s.key = f"{rel}|{qual}|{ident[1]}|{n}"
876
+ return FileSecrets(sites, first_include)
877
+
878
+
879
+ def c_dummy(site: Site) -> str:
880
+ if site.kind == "array":
881
+ return "{0}" if site.text.count("{") > 1 else "{" + ", ".join(["0"] * site.count) + "}"
882
+ if site.is_float:
883
+ return "(1.0f)" if site.text.endswith(("f", "F")) else "(1.0)"
884
+ return "(1)"
885
+
886
+
887
+ def c_twin_header(entries: dict[str, str]) -> str:
888
+ lines = [f"/* {TWIN_NOTE} */", "#ifndef DOPPEL_SECRETS_H", "#define DOPPEL_SECRETS_H"]
889
+ lines += [f"#define {a} {d}" for a, d in sorted(entries.items())]
890
+ return "\n".join(lines + ["#endif", ""])
891
+
892
+
893
+ def c_include_line(twin_rel: str) -> str:
894
+ up = "../" * twin_rel.count("/")
895
+ return f'#include "{up}{C_HEADER}" /* doppel */\n'
896
+
897
+
898
+ def strip_c_include(text: str) -> str:
899
+ return C_INCLUDE_RE.sub("", text, count=1)