-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathgenerate-test-report.py
More file actions
3518 lines (3412 loc) · 218 KB
/
Copy pathgenerate-test-report.py
File metadata and controls
3518 lines (3412 loc) · 218 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
generate-test-report.py - KeepKey Firmware Test Report (PDF)
Auto-detects firmware version, runs or reads test results, generates
a human-readable report with context for every test. stdlib only.
Usage:
python3 scripts/generate-test-report.py --output=test-report.pdf
python3 scripts/generate-test-report.py --fw-version=7.10.0 --junit=junit.xml --output=test-report.pdf
"""
import struct, zlib, os, sys, argparse
from datetime import datetime
# Make keepkeylib importable regardless of invocation cwd (pytest inserts it
# automatically; this script is often run standalone as
# `python3 ../scripts/generate-test-report.py` from tests/, or directly from
# the repo root during local iteration).
for _cand in (os.getcwd(), os.path.join(os.getcwd(), '..'),
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if os.path.isdir(os.path.join(_cand, 'keepkeylib')) and _cand not in sys.path:
sys.path.insert(0, _cand)
del _cand
try:
from keepkeylib.clearsign_catalog import CLEARSIGN_FLOWS
except ImportError:
CLEARSIGN_FLOWS = None # report still renders; V section just won't expand from the catalog
# ---------------------------------------------------------------
# PDF writer + page builder (stdlib only)
# ---------------------------------------------------------------
def _read_png_pixels(path):
"""Read a 256x64 grayscale PNG and return raw pixel bytes (256*64 bytes, 0 or 255)."""
with open(path, 'rb') as f:
data = f.read()
# Minimal PNG parser -- skip signature, find IDAT, decompress
assert data[:8] == b'\x89PNG\r\n\x1a\n'
pos = 8
idat_chunks = []
width = height = 0
while pos < len(data):
length = struct.unpack('>I', data[pos:pos+4])[0]
chunk_type = data[pos+4:pos+8]
chunk_data = data[pos+8:pos+8+length]
if chunk_type == b'IHDR':
width = struct.unpack('>I', chunk_data[0:4])[0]
height = struct.unpack('>I', chunk_data[4:8])[0]
elif chunk_type == b'IDAT':
idat_chunks.append(chunk_data)
pos += 12 + length
raw = zlib.decompress(b''.join(idat_chunks))
# Remove filter bytes (1 byte per row)
pixels = bytearray()
stride = width + 1 # filter byte + pixel data
for y in range(height):
row_start = y * stride + 1 # skip filter byte
pixels.extend(raw[row_start:row_start + width])
return bytes(pixels), width, height
class PDF:
def __init__(self):
self.pages = [] # (ops_str, w, h, [(img_name, img_obj_placeholder)])
self.images = {} # name -> (pixels, width, height)
self._img_counter = 0
def register_image(self, path):
"""Register a PNG image, returns image name for use in pages."""
if path in self.images:
return self.images[path][0]
name = f'Im{self._img_counter}'
self._img_counter += 1
pixels, w, h = _read_png_pixels(path)
self.images[path] = (name, pixels, w, h)
return name
def add_page(self, lines, w=612, h=792):
ops = []
img_refs = [] # image names used on this page
for item in lines:
if item[0] == 'IMG':
# ('IMG', x, y, display_w, display_h, img_name)
_, x, y, dw, dh, img_name = item
ops.append(f'q {dw} 0 0 {dh} {x} {y} cm /{img_name} Do Q')
img_refs.append(img_name)
continue
y, sz, txt = item[0], item[1], item[2]
style = item[3] if len(item) > 3 else False
color = item[4] if len(item) > 4 else None
txt = _ascii(txt).replace('\\','\\\\').replace('(','\\(').replace(')','\\)')
if color:
ops.append(f'{color[0]} {color[1]} {color[2]} rg')
if style == 'ding':
ops.append(f'BT /F3 {sz} Tf 40 {y} Td ({txt}) Tj ET')
else:
f = '/F2' if style else '/F1'
ops.append(f'BT {f} {sz} Tf 40 {y} Td ({txt}) Tj ET')
if color:
ops.append('0 0 0 rg')
self.pages.append(('\n'.join(ops), w, h, img_refs))
def write(self, path):
objs = [
b'1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n',
b'', # pages placeholder
b'3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n',
b'4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>\nendobj\n',
b'5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /ZapfDingbats >>\nendobj\n',
]
nxt = 6
# Add image XObjects
img_obj_ids = {} # img_name -> obj_id
for img_path, (name, pixels, iw, ih) in self.images.items():
compressed = zlib.compress(pixels)
obj = f'{nxt} 0 obj\n<< /Type /XObject /Subtype /Image /Width {iw} /Height {ih} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode /Length {len(compressed)} >>\nstream\n'.encode() + compressed + b'\nendstream\nendobj\n'
objs.append(obj)
img_obj_ids[name] = nxt
nxt += 1
pids = []
for stream, w, h, img_refs in self.pages:
c = zlib.compress(stream.encode('latin-1', 'replace'))
objs.append(f'{nxt} 0 obj\n<< /Length {len(c)} /Filter /FlateDecode >>\nstream\n'.encode() + c + b'\nendstream\nendobj\n')
stream_id = nxt; nxt += 1
# Build XObject dict for this page
xobj_dict = ''
if img_refs:
xobj_entries = ' '.join(f'/{nm} {img_obj_ids[nm]} 0 R' for nm in img_refs if nm in img_obj_ids)
if xobj_entries:
xobj_dict = f' /XObject << {xobj_entries} >>'
objs.append(f'{nxt} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents {stream_id} 0 R /Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R >>{xobj_dict} >> >>\nendobj\n'.encode())
pids.append(nxt); nxt += 1
objs[1] = f'2 0 obj\n<< /Type /Pages /Kids [{" ".join(f"{p} 0 R" for p in pids)}] /Count {len(pids)} >>\nendobj\n'.encode()
with open(path, 'wb') as f:
f.write(b'%PDF-1.4\n')
offs = []
for o in objs: offs.append(f.tell()); f.write(o)
xr = f.tell()
f.write(b'xref\n')
f.write(f'0 {len(objs)+1}\n'.encode())
f.write(b'0000000000 65535 f \n')
for o in offs: f.write(f'{o:010d} 00000 n \n'.encode())
f.write(f'trailer\n<< /Size {len(objs)+1} /Root 1 0 R >>\nstartxref\n{xr}\n%%EOF\n'.encode())
GREEN = (0.13, 0.55, 0.13)
RED = (0.8, 0.1, 0.1)
GRAY = (0.5, 0.5, 0.5)
# ZapfDingbats: \x34 = checkmark, \x38 = cross, \x6c = circle
CHECK = '\x34'
CROSS = '\x38'
# Map non-Latin-1 Unicode punctuation to ASCII so it survives the PDF content
# stream (encoded latin-1); em-dashes etc. were rendering as '?'.
_ASCII_MAP = {
'—': '-', '–': '-', '→': '->', '←': '<-',
'’': "'", '‘': "'", '“': '"', '”': '"',
'…': '...', '•': '*', '₿': 'BTC', '≤': '<=',
'≥': '>=', '±': '+/-',
}
def _ascii(s):
for k, v in _ASCII_MAP.items():
if k in s:
s = s.replace(k, v)
return s
class PB:
def __init__(self, pdf):
self.pdf = pdf; self.lines = []; self.y = 755
def _flush(self):
if self.lines: self.pdf.add_page(self.lines); self.lines = []; self.y = 755
def need(self, h):
if self.y - h < 45: self._flush()
def text(self, sz, txt, bold=False, color=None):
self.need(sz + 2); self.lines.append((self.y, sz, txt, bold, color) if color else (self.y, sz, txt, bold)); self.y -= sz + 2
def check(self, sz, txt_after, passed):
"""Render checkmark/cross + text on same conceptual line"""
self.need(sz + 2)
if passed == 'pass':
self.lines.append((self.y, sz, CHECK, 'ding', GREEN))
self.lines.append((self.y, sz, f' {txt_after}', True, GREEN))
elif passed in ('fail', 'error'):
self.lines.append((self.y, sz, CROSS, 'ding', RED))
self.lines.append((self.y, sz, f' {txt_after}', True, RED))
elif passed == 'skip':
self.lines.append((self.y, sz, f'-- {txt_after}', False, GRAY))
else:
self.lines.append((self.y, sz, f' {txt_after}', False, GRAY))
self.y -= sz + 2
def image(self, png_path, display_w=400, display_h=100):
"""Embed a 256x64 OLED screenshot, scaled to display_w x display_h"""
self.need(display_h + 4)
img_name = self.pdf.register_image(png_path)
# PDF images are placed from bottom-left; y is the bottom of the image
self.lines.append(('IMG', 40, self.y - display_h, display_w, display_h, img_name))
self.y -= display_h + 4
def gap(self, h=4):
self.y -= h
def finish(self):
self._flush()
def _lookup(results, mod, meth):
"""Look up a test result by module::method. Every SECTIONS module is a
test_msg_* module, so parse_junit always emits a 'mod::meth' key -- there is
no bare-method fallback (it let a cross-module method-name collision render a
never-run test as PASS, defeating the --validate-junit release gate)."""
return results.get(f'{mod}::{meth}', '')
def ver_t(s):
# Defensive: tolerate pre-release tags (7.15.0-rc3), 'v' prefixes and short
# versions ('7.15' -> (7,15,0)) so report/filter/validate never crash.
s = str(s).split('-')[0].replace('v', '')
parts = (s.split('.') + ['0', '0', '0'])[:3]
return tuple(int(''.join(ch for ch in p if ch.isdigit()) or '0') for p in parts)
def ver_ge(a, b): return ver_t(a) >= ver_t(b)
# Tests whose newer fail-closed behavior deliberately returns before drawing a
# confirmation screen. Keep their historical catalog text, but do not schedule
# or audit an OLED capture once the refusal behavior is active.
_NO_SCREEN_FROM = {
('test_msg_signtx_ethereum_erc20', 'test_approve_all'): '7.14.2',
}
def _screens_for(fw_version, mod, meth, screens):
floor = _NO_SCREEN_FROM.get((mod, meth))
if floor and ver_ge(fw_version, floor):
return []
return screens
def _w(text, n=95):
words, lines, cur = text.split(), [], ''
for w in words:
if cur and len(cur)+1+len(w) > n: lines.append(cur); cur = w
else: cur = f'{cur} {w}' if cur else w
if cur: lines.append(cur)
return lines
def _frame_lit_ratio(path):
"""Fraction of lit pixels in an OLED PNG, or None if unreadable."""
try:
pixels, w, h = _read_png_pixels(path)
if not w or not h:
return None
return sum(1 for b in pixels if b > 128) / float(w * h)
except Exception:
return None
def _frame_hash(path):
"""Content hash of an OLED PNG with the top-right animation region masked
(the scroll arrow renders in a per-capture animation state, defeating
exact-byte comparison of otherwise identical screens). None if unreadable.
"""
try:
import hashlib
pixels, w, h = _read_png_pixels(path)
if not w or not h:
return None
px = bytearray(pixels)
for y in range(min(16, h)):
row = y * w
for x in range(max(0, w - 64), w):
px[row + x] = 0
return hashlib.md5(bytes(px)).hexdigest()
except Exception:
return None
# hash -> number of distinct test dirs the frame appears in. 1 = the frame is
# unique to its test (its own content); large = generic device chrome shared
# across unrelated tests (load-device prompt, policy toggles, lock screens).
_FRAME_DIR_COUNTS = {}
# Hashes appearing in >= 3 distinct dirs — used to keep chrome out of the
# "extra frames" strip when a test has real content frames of its own.
_GENERIC_FRAME_HASHES = set()
def _build_frame_census(screenshot_dir):
"""Populate the cross-test frame census from every per-test capture dir."""
_FRAME_DIR_COUNTS.clear()
_GENERIC_FRAME_HASHES.clear()
if not screenshot_dir or not os.path.isdir(screenshot_dir):
return
dirs_per_hash = {}
for mod in sorted(os.listdir(screenshot_dir)):
mod_dir = os.path.join(screenshot_dir, mod)
if not os.path.isdir(mod_dir):
continue
for meth in sorted(os.listdir(mod_dir)):
test_dir = os.path.join(mod_dir, meth)
if not os.path.isdir(test_dir):
continue
for f in os.listdir(test_dir):
if not f.startswith('btn'):
continue
h = _frame_hash(os.path.join(test_dir, f))
if h:
dirs_per_hash.setdefault(h, set()).add(test_dir)
_FRAME_DIR_COUNTS.update((h, len(d)) for h, d in dirs_per_hash.items())
_GENERIC_FRAME_HASHES.update(
h for h, dirs in dirs_per_hash.items() if len(dirs) >= 3)
def _pick_best_frame(test_dir, btn_files):
"""Pick the best screenshot for a test.
setUp noise (wipe/load frames) is removed at capture time for the signing
tests (see reset_screenshots / setup_mnemonic_*), so the frames here are
the test's own operation confirms. Defensive layers on top:
- blank/near-blank frames (idle, lock glyph) are NEVER shown — a reject
that fires before any confirm UI gets no image, not a blank one;
- rank by how test-SPECIFIC a frame is (fewest other test dirs showing the
byte-identical screen), so shared chrome (the load-device prompt, policy
toggles) loses to the test's own screens, yet still renders when it IS
the content (gate tests whose every frame is shared chrome);
- density breaks ties (the address/amount screen carries more lit pixels
than a bare "Sign?" prompt); dense out-of-band frames (QR screens) are
a last resort behind in-band ones.
ponytail: specificity census + density, no OCR — capture-time reset is the
real guard, this is the safety net.
"""
if not btn_files:
return None
inband, dense = [], []
for f in btn_files:
p = os.path.join(test_dir, f)
r = _frame_lit_ratio(p)
if r is None or r < 0.02:
continue # unreadable or blank/lock — never show
if r > 0.55:
dense.append((r, f)) # QR/near-full: last resort, real content
continue
h = _frame_hash(p)
inband.append((_FRAME_DIR_COUNTS.get(h, 1), -r, f))
if inband:
inband.sort()
return os.path.join(test_dir, inband[0][2])
if dense:
dense.sort()
return os.path.join(test_dir, dense[-1][1])
return None
def detect_fw():
try:
from keepkeylib.transport_udp import UDPTransport
from keepkeylib.client import KeepKeyDebuglinkClient
from keepkeylib import messages_pb2 as proto
t = UDPTransport(os.environ.get('KK_TRANSPORT_MAIN','127.0.0.1:11044'))
c = KeepKeyDebuglinkClient(t)
r = c.call_raw(proto.Initialize())
v = f'{r.major_version}.{r.minor_version}.{r.patch_version}'; c.close(); return v
except: return None
# Census of everything the merged JUnit actually contained, so the report can
# state how much of the run it covers. Without this the PDF silently implies
# that its catalog IS the test suite -- an RC audit read "no dice in the report"
# as "dice is untested" when the dice reset test had in fact run green.
JUNIT_CENSUS = {'ran': 0, 'skipped': 0, 'native': 0}
def parse_junit(path):
"""Parse junit XML for pass/fail. Returns dict keyed by 'module::method' (precise)
and 'method' (fallback). Module is extracted from classname: tests.test_msg_foo.TestBar → test_msg_foo.
Native gtest suites carry a bare classname ("Dice", "Storage") with no dotted
python module, so they get keyed as 'Suite::Test'. They used to produce no
'mod::meth' key at all, which made every native unit test structurally
impossible to put in SECTIONS -- the firmware-unit XMLs were merged in and
then silently unusable."""
if not path or not os.path.exists(path): return {}
import xml.etree.ElementTree as ET
results = {}
for tc in ET.parse(path).iter('testcase'):
name = tc.get('name', '')
cls = tc.get('classname', '')
if tc.find('failure') is not None: status = 'fail'
elif tc.find('error') is not None: status = 'error'
elif tc.find('skipped') is not None: status = 'skip'
else: status = 'pass'
JUNIT_CENSUS['ran'] += 1
# 'ran' counts every collected testcase, skips included. A version-gated
# feature test that SKIPs on an older emulator is NOT evidence the feature
# works, so the two must never be reported as one number.
if status == 'skip':
JUNIT_CENSUS['skipped'] += 1
# Extract module from classname: tests.test_msg_foo.TestBar → test_msg_foo
mod = ''
if cls:
parts = cls.split('.')
for p in parts:
# Any test module, not just the test_msg_/test_sign_/test_verify_
# families. test_storage_version_gate matched none of those, so
# it produced no 'mod::meth' key and all eight of its results
# were invisible -- the section rendered "Pending (no firmware
# support yet)" while the tests were passing.
if p.startswith('test_'):
mod = p
break
if not mod and '.' not in cls:
mod = cls # native gtest suite
JUNIT_CENSUS['native'] += 1
results[f'{cls}.{name}'] = status
# Key by module::method (disambiguates collisions like test_sign_btc_eth_swap)
if mod:
results[f'{mod}::{name}'] = status
# Bare method fallback -- only set if no collision
if name not in results or status == 'pass':
results[name] = status
return results
# ---------------------------------------------------------------
# Test catalog with full context per test
# ---------------------------------------------------------------
# (id, module, method, title, context, [screenshots])
# context = why this test exists, what it proves, what user sees
# Tests whose whole point is the ordered on-device review sequence — render
# every review screen in order (who/what/why), not a single "best" thumbnail.
FULL_SEQUENCE_TESTS = {
# The additive invariant IS an ordered-sequence claim: the decoded screens
# are additional and the baseline raw review still follows them. Showing a
# best-of-3 sample would hide exactly the thing being proved.
('test_msg_ethereum_clearsign_additive',
'test_successful_decode_still_runs_the_raw_review'),
('test_msg_ethereum_clearsign_additive',
'test_v2_schema_decode_still_runs_the_raw_review'),
('test_msg_ethereum_clearsign_additive',
'test_failed_signature_falls_back_to_the_unverified_review'),
('test_msg_ethereum_clear_signing', 'test_binding_happy_path_signs_and_recovers'),
('test_msg_ethereum_clear_signing', 'test_clearsign_erc20_approve_unlimited'),
('test_msg_ethereum_clear_signing', 'test_clearsign_uniswap_v2_eth_to_token'),
# The newest/highest-stakes tx shapes get the full ordered walkthrough too.
('test_msg_ethereum_clear_signing', 'test_clearsign_eip7702_setcode_authorization'),
('test_msg_ethereum_clear_signing', 'test_clearsign_erc4337_entrypoint_v0_7_handleops'),
('test_msg_ethereum_clear_signing', 'test_clearsign_safe_exectransaction'),
('test_msg_ethereum_clear_signing', 'test_clearsign_permit2_permit_transfer_from'),
('test_msg_ethereum_clear_signing',
'test_v2_calldata_length_mismatch_falls_back_to_raw_review'),
# Native THOR/MAYA memo hardening: the raw memo pager (MEMO 1/N .. N/N,
# complete memo bytes, sole memo gate) IS the security story — show every
# page for every memo variant, not a single best frame.
('test_msg_thorchain_signtx', 'test_thorchain_sign_tx'),
('test_msg_mayachain_signtx', 'test_mayachain_sign_tx_memos'),
('test_msg_osmosis_signtx', 'test_osmosis_swap_max_fields_are_fully_paged'),
}
def _v_catalog_tests(start_id=17):
"""Generate one V-section test entry per CLEARSIGN_FLOWS flow (skipping
'aave-v3-supply', the flagship V9 walkthrough). THE catalog is the
single source of truth — growing it (keepkeylib/clearsign_catalog.py)
needs no changes here, unlike a hand-typed per-flow entry that would
silently go stale (as happened when the old hand-written V17-V23 test
names drifted from the dynamically-generated ones).
Every entry gets a NON-EMPTY screenshots hint: screenshot_filter() below
only includes tests whose hint list is non-empty in the Phase-1 capture
filter, so an empty list here would silently exclude a flow from ever
getting an OLED screenshot.
"""
if not CLEARSIGN_FLOWS:
return []
out = []
i = start_id
for f in CLEARSIGN_FLOWS:
if f['key'] == 'aave-v3-supply':
continue
method = 'test_clearsign_' + f['key'].replace('-', '_').replace('.', '_')
def _arg_shown(a):
# Render what the OLED will actually show for this arg:
# STRING -> the attested label; ADDRESS -> abbreviated 0x…;
# TOKEN_AMOUNT -> decimal-scaled amount + symbol (or UNLIMITED).
v = a['value']
if a['format'] == 4: # ARG_FORMAT_STRING
return v.decode('ascii', 'replace')
if a['format'] == 1: # ARG_FORMAT_ADDRESS
return '0x%s..%s' % (v.hex()[:4], v.hex()[-4:])
if a['format'] == 5: # ARG_FORMAT_TOKEN_AMOUNT
dec, symlen = v[0], v[1]
sym = v[2:2+symlen].decode('ascii', 'replace')
amt = v[2+symlen:]
if len(amt) == 32 and amt == b'\xff' * 32:
return 'UNLIMITED ' + sym
n = int.from_bytes(amt, 'big')
if dec:
scaled = ('%f' % (n / 10 ** dec)).rstrip('0').rstrip('.')
else:
scaled = str(n)
return '%s %s' % (scaled, sym)
return a['name']
shows = '; '.join('%s: %s' % (a['name'], _arg_shown(a))
for a in f['args'][:3])
# Prefer any TOKEN_AMOUNT/ADDRESS/STRING label as the screenshot hint
# so it reads like what the OLED will actually show.
hint_names = [a['name'] for a in f['args'][:2]] or [f['method']]
ctx = ('%s.%s (%s). %s AdvancedMode OFF; the bound metadata is the '
'only reason this contract data may sign. Real tx: to=0x%s..%s, '
'chainId %d. Decode: %s.' % (
f['protocol'], f['method'], f['category'], f.get('why', ''),
f['to'].hex()[:4], f['to'].hex()[-4:], f['chain_id'], shows))
out.append((
'V%d' % i, 'test_msg_ethereum_clear_signing', method,
'%s %s — clear-signed, zero hex' % (f['protocol'], f['method']),
ctx,
hint_names,
))
i += 1
return out
_V_CATALOG_TESTS = _v_catalog_tests(start_id=17)
SECTIONS = [
('J', 'Display Binding - What the Device Signs Is What It Shows', '7.14.2',
'The 7.14.2 security release changed what reaches the OLED on the signing paths. Every '
'defect it fixed was a case of the device hashing bytes it never rendered, or rendering '
'text it could not vouch for. These tests exist to capture those screens: a passing wire '
'assertion proves the device refused or signed, but only the screen proves the user was '
'told the truth about what they approved.',
[
'DISCLOSURE RULE: every byte covered by the signature must be reachable on screen.',
'',
'The defects this section guards against, all shipped at some point:',
'- bytes past an embedded NUL were signed and never drawn ("%s" stops at 0x00)',
'- whitespace padding pushed a tail past the cut with no warning',
'- 456 bytes past the initial chunk were hashed with a clear-sign screen showing',
' confident token amounts for calldata the device had not seen',
'- an unresolved token rendered as the literal "Unknown token value" and signed',
'- a truncated memo dropped its last character (Confirm limit 42 vs 420)',
'',
'A test here with an EMPTY screenshot list is deliberate: refusal paths draw nothing,',
'and their evidence is the Failure on the wire plus the absence of a ButtonRequest.',
],
[
('J1', 'test_msg_ethereum_erc20_0x_signtx', 'test__sign_transformERC20',
'0x transformERC20 raw disclosure',
'A 1480-byte transformERC20 payload exceeds one 1024-byte chunk. The device must NOT '
'clear-sign it as a token swap, because the bytes past the initial chunk are hashed '
'without being decoded. With AdvancedMode on it falls to the raw path, where the byte '
'count shown must be the FULL length (1480), not the chunk length (1024) - a short '
'count would under-report what is being signed.',
['Raw contract data screen showing the full byte count']),
('J2', 'test_msg_ethereum_erc20_0x_signtx', 'test_sign_0x_swap_ERC20_to_ETH',
'0x sellToUniswap names both assets',
'Clear-signing is only honest when BOTH token words resolve to known assets. This '
'payload resolves (USDC -> ETH) and must name both sides with real amounts. The '
'failure this guards is a screen naming a DEX while showing no amount.',
['Swap screen naming both assets and amounts']),
('J3', 'test_msg_ethereum_erc20_0x_signtx', 'test_sign_longdata_swap',
'Long 0x calldata stays disclosed',
'Calldata spanning multiple chunks must not silently lose its tail from the display '
'while remaining inside the signature.',
['Contract data screen']),
('J8', 'test_msg_ethereum_signing_guards',
'test_contract_handler_streamed_calldata_signs_full_data',
'Streamed calldata is fully covered',
'Calldata delivered across several chunks must be hashed in full and disclosed in full. '
'This is the positive control for the chunk-completeness gate. NOTE: every test in '
'test_msg_ethereum_signing_guards currently SKIPS in CI under requires_firmware, so no '
'screen can be captured for it yet - the screenshot list stays empty until the gate '
'opens, rather than declaring an expectation nothing can satisfy.',
[]),
('J9', 'test_msg_ethereum_signing_guards', 'test_eip1559_requires_chain_id',
'Omitted chain_id is refused before any screen',
'Without a chain_id the device cannot name the network, and a signature would be '
'pre-EIP-155 - replayable on every EVM chain. The refusal happens before the first '
'confirm(), so NO screen is drawn and no ButtonRequest is emitted. The empty '
'screenshot list below is the assertion.',
[]),
('J10', 'test_verify_typed_data', 'test_structured_eip712_is_refused',
'Structured EIP-712 is closed by default',
'The legacy JSON parser could not guarantee that every displayed value was the '
'canonical value being hashed, and one screen took its title from the attacker-supplied '
'domain name. The feature is withdrawn rather than shipped with a screen it could not '
'vouch for: zero screens, refusal on the wire.',
[]),
('J11', 'test_msg_binance_sign_tx', 'test_transfer',
'Binance denom renders in full',
'A long denom must render completely and must not overflow the formatting buffer.',
['Transfer screen showing the full denom']),
('J12', 'test_msg_ping', 'test_ping_long_body_is_paged',
'A long body is paged, not clipped',
'A body that will not fit one screen is shown across several, with the page number '
'in the title. Before 7.14.2 the device drew what fitted and stopped - no ellipsis, '
'no warning - and a later warning screen claimed "Hold to view it anyway" while '
're-drawing the same clipped text. These captures are the evidence that the '
'remainder is now actually reachable. The press DURATIONS (click to page, hold to '
'approve) are not assertable in an emulator with no physical button.',
['Numbered page screens covering the whole body']),
('J13', 'test_msg_ping', 'test_ping_short_body_is_not_paged',
'A body that fits is not paged',
'The control for J12. A fitting body must still take exactly one screen with an '
'unnumbered title - otherwise a pager that numbered every confirmation, making '
'ordinary approvals cost extra presses, would pass unnoticed.',
['Single unnumbered confirmation screen']),
]),
('X', 'Device Specifications', '0.0.0',
'The KeepKey is an open-source hardware wallet built on an ARM Cortex-M3 (STM32F205, 120MHz) '
'with a 256x64 monochrome OLED, single confirmation button, and micro-USB interface. The '
'bootloader (v2.x) is flashed at manufacture and never updated - it is the immutable root of '
'trust. On every boot, the bootloader verifies the firmware signature using redundant F3 checks '
'before transferring control.',
[
'BOOT SEQUENCE:',
'1. USB connect -> bootloader executes (always first)',
'2. F3 signature check (redundant dual-path verify)',
'3. Valid -> KeepKey logo -> firmware runs',
'4. Invalid/missing -> "UPDATE FIRMWARE" screen',
'5. Firmware upload -> verify -> flash -> reboot -> re-verify',
'',
'HARDWARE:',
'- MCU: STM32F205RET6, 120MHz, 128KB bootloader + 896KB firmware',
'- Display: 256x64 OLED (SSD1306), monochrome, used for ALL confirmations',
'- Input: single capacitive button (confirm/reject)',
'- USB: micro-B, HID + WebUSB transports, HID fallback',
'- Storage: BIP-39 seed encrypted in isolated flash region',
'- Curves: secp256k1, ed25519, NIST P-256; regular firmware also includes Pallas/Orchard',
'',
'SECURITY MODEL:',
'- All private key operations happen on-device, keys never leave',
'- Every transaction output displayed on OLED for user verification',
'- PIN grid randomized on each prompt (position-based, not digit-based)',
'- BIP-39 passphrase creates hidden wallets (plausible deniability)',
'',
'FIRMWARE VARIANTS (7.15, PR #282):',
'- Full multi-chain (default): all coin families including Zcash Orchard privacy;',
' firmware_variant = model name.',
'- Bitcoin-only (KK_BITCOIN_ONLY): only Bitcoin + Testnet; all altcoin and',
' shielded-Zcash handlers stripped; firmware_variant = KeepKeyBTC (EmulatorBTC',
' on the emulator). Clients gate multi-chain-only tests on this string.',
'- There is no separate Zcash artifact: KK_ZCASH_PRIVACY is ON for the regular',
' product and OFF only for KK_BITCOIN_ONLY.',
'',
'SEED LOCK (7.15, PR #282):',
'- A seed created under bitcoin-only firmware is stamped in a reserved storage-',
' version band. Multi-chain firmware refuses to load it and requires an explicit',
' wipe (wipe-to-exit); the seed is never exposed to stripped-out code. Old',
' multi-chain firmware treats the band as unknown and resets.',
], []),
('C', 'Core - Device Lifecycle', '7.0.0',
'Fundamental device security operations. Every firmware version must pass these tests. '
'A failure here is an absolute release blocker - these protect seed generation, backup, '
'recovery, and access control.',
[
'WIPE: Erases all keys and settings, returns to factory state',
'RESET: Generates cryptographic entropy -> BIP-39 mnemonic displayed on OLED only',
'RECOVERY: Cipher-based entry (scrambled keyboard on OLED) prevents keyloggers',
'PIN: Randomized grid on OLED, user enters position not digit',
'PASSPHRASE: Additional BIP-39 word, empty string = default wallet',
],
[
('C1', 'test_msg_wipedevice', 'test_wipe_device',
'Wipe device',
'Erases all keys, PIN, settings. Device shows "WIPE DEVICE - Do you want to erase your '
'private keys and settings?" on OLED. User must press button to confirm. After wipe, '
'device is uninitialized - no operations work until a new seed is loaded or generated.',
['Wipe confirmation screen']),
('C2', 'test_msg_resetdevice', 'test_reset_device',
'Generate new seed',
'Device generates 256 bits of entropy from hardware RNG, converts to BIP-39 mnemonic, '
'and displays words on OLED one page at a time. Words are NEVER sent to the host. '
'User writes them down as their backup.',
['Seed word display']),
('C3', 'test_msg_resetdevice', 'test_reset_device_pin',
'Generate seed with PIN',
'Same as C2 but also sets a PIN. PIN is entered twice for confirmation via the '
'randomized 3x3 grid on OLED. Verifies PIN is stored and required for subsequent operations.',
['PIN entry grid']),
('C4', 'test_msg_resetdevice', 'test_failed_pin',
'PIN mismatch rejects setup',
'If the user enters different PINs during confirmation, the device rejects the setup. '
'This prevents accidentally setting a PIN the user cannot reproduce.',
['PIN mismatch warning']),
('C5', 'test_msg_resetdevice', 'test_already_initialized',
'Reject reset on initialized device',
'An already-initialized device must refuse reset without a wipe first. Prevents '
'accidental seed replacement which would strand funds on the old seed.',
[]),
('C6', 'test_msg_loaddevice', 'test_load_device_1',
'Load 12-word mnemonic (debug)',
'Debug-only operation: loads a known 12-word mnemonic for testing. In production, '
'seeds can only be generated on-device or recovered via cipher entry.',
[]),
('C7', 'test_msg_loaddevice', 'test_load_device_2',
'Load 18-word mnemonic (debug)',
'Tests 18-word BIP-39 mnemonic support (192 bits of entropy).',
[]),
('C8', 'test_msg_loaddevice', 'test_load_device_3',
'Load 24-word mnemonic (debug)',
'Tests 24-word BIP-39 mnemonic support (256 bits of entropy, maximum security).',
[]),
('C9', 'test_msg_loaddevice', 'test_load_device_utf',
'Load with UTF-8 device label',
'Verifies the device handles non-ASCII characters in labels without corruption.',
[]),
('C10', 'test_msg_recoverydevice_cipher', 'test_nopin_nopassphrase',
'Cipher recovery (no PIN)',
'Recovery via scrambled keyboard on OLED. The letter grid is randomized per-character, '
'so even a compromised host cannot determine which letters the user selected. After all '
'words are entered, device verifies BIP-39 checksum and reconstructs the seed.',
['Cipher grid on OLED']),
('C11', 'test_msg_recoverydevice_cipher', 'test_pin_passphrase',
'Cipher recovery with PIN + passphrase',
'Same recovery flow as C10 but also sets PIN and enables passphrase protection during '
'the recovery process.',
['Cipher + PIN entry']),
('C12', 'test_msg_recoverydevice_cipher', 'test_character_fail',
'Invalid character rejection',
'Verifies the cipher entry rejects characters that cannot form any BIP-39 word prefix.',
[]),
('C13', 'test_msg_recoverydevice_cipher', 'test_backspace',
'Backspace during cipher entry',
'User can correct mistakes during word entry without restarting recovery.',
[]),
('C14', 'test_msg_recoverydevice_cipher', 'test_reset_and_recover',
'Full reset then recover cycle',
'End-to-end test: generate seed -> write down words -> wipe -> recover from words -> '
'verify same addresses are derived. Proves the backup/restore cycle works.',
[]),
('C15', 'test_msg_recoverydevice_cipher', 'test_wrong_number_of_words',
'Wrong word count rejected',
'BIP-39 only allows 12, 18, or 24 words. Other counts are rejected immediately.',
[]),
('C16', 'test_msg_recoverydevice_cipher_dryrun', 'test_correct_same',
'Dry-run recovery matches',
'User can verify their backup without wiping the device. Dry-run recovers the seed '
'in memory and compares to the active seed. If they match, user knows their backup is valid.',
[]),
('C17', 'test_msg_recoverydevice_cipher_dryrun', 'test_correct_notsame',
'Dry-run detects wrong backup',
'If the entered words produce a different seed, the device warns the user. This catches '
'transcription errors in the backup before an emergency.',
[]),
('C18', 'test_msg_recoverydevice_cipher_dryrun', 'test_incorrect',
'Dry-run rejects bad entry',
'Invalid words or checksum failure during dry-run are reported to the user.',
[]),
('C19', 'test_msg_changepin', 'test_set_pin',
'Set new PIN',
'Transitions from no-PIN to PIN-protected. The randomized 3x3 grid prevents screen '
'recording attacks - the attacker sees button presses but not which digit they map to.',
['PIN entry grid']),
('C20', 'test_msg_changepin', 'test_change_pin',
'Change existing PIN',
'Requires entering the current PIN first (proving knowledge), then setting a new one.',
[]),
('C21', 'test_msg_changepin', 'test_remove_pin',
'Remove PIN protection',
'User can disable PIN if physical security is sufficient. Requires current PIN to remove.',
[]),
('C22', 'test_msg_applysettings', 'test_apply_settings',
'Change label and language',
'Device label appears on OLED during confirmation screens. Helps identify devices when '
'a user has multiple KeepKeys.',
['Label change confirm']),
('C23', 'test_msg_applysettings', 'test_apply_settings_passphrase',
'Toggle passphrase protection',
'Enables/disables BIP-39 passphrase. When enabled, every operation prompts for a '
'passphrase. Different passphrases derive completely different wallets from the same seed.',
['Passphrase enable']),
('C24', 'test_msg_clearsession', 'test_clearsession',
'Clear session state',
'Clears cached PIN, passphrase, and session data. Next operation requires re-authentication.',
[]),
('C25', 'test_msg_ping', 'test_ping',
'Ping with button confirmation',
'Basic connectivity test. Verifies the device processes messages and button confirmation works.',
[]),
('C26', 'test_msg_ping', 'test_ping_format_specifier_sanitize',
'Sanitize format specifiers',
'Security test: printf-style format specifiers in ping message must not cause crashes '
'or information leaks. Verifies input sanitization.',
[]),
('C27', 'test_msg_getentropy', 'test_entropy',
'Hardware RNG audit budget and lock policy',
'Proves a fresh initialized, PIN-protected, locked device still requires confirmation; '
'then proves an uninitialized device returns exactly 8 x 8192 bytes (64 KiB) without a '
'press, with exact lengths, unique blocks, and conservative catastrophic-failure health '
'checks. The next request must restore confirmation. These checks detect a stuck or '
'grossly biased source; they are not a statistical certification of the hardware RNG.',
[]),
('C28', 'test_msg_cipherkeyvalue', 'test_encrypt',
'Symmetric key encryption',
'Derives a symmetric key from the HD tree and encrypts data. Used for password manager '
'integrations and encrypted communication.',
[]),
('C29', 'test_msg_cipherkeyvalue', 'test_decrypt',
'Symmetric key decryption',
'Reverse of C28. Verifies encrypt/decrypt round-trips correctly.',
[]),
('C30', 'test_msg_signidentity', 'test_sign',
'Sign identity challenge (SSH/GPG)',
'Signs an identity challenge for SSH login or GPG key derivation. Derives a key from '
'the identity URI and signs the challenge.',
[]),
('C31', 'test_msg_recoverydevice_cipher', 'test_invalid_bip39_word_rejected',
'BIP-39 invalid word rejected during cipher recovery',
'Enter a non-BIP-39 word ("zz") during cipher recovery with enforce_wordlist=True. '
'Firmware must reject immediately with Failure instead of silently accepting.',
['Wordlist rejection warning']),
]),
('K', 'Seed Generation Hardening (7.14.3+)', '7.14.3',
'The 7.15 changes to how a seed comes into existence: user-supplied dice entropy folded in '
'on-device, and the PIN key-derivation rewrap. These ran green from the first 7.15 RC but '
'appeared nowhere in this report, because the catalog could not reference native firmware '
'unit tests at all and nobody had catalogued the two new pyk cases. Absent evidence read as '
'absent coverage during an RC audit, which is exactly the failure this section exists to '
'prevent.',
[
'DICE: user rolls a d6 on-device; short press advances 1-6, long press commits, undo backs out.',
'The roll string is hashed and the digest confirmed on the OLED before it is mixed in.',
'MIX: int_entropy = SHA256(int_entropy || rolls), folded in BEFORE the host EntropyRequest,',
'so the device commits to its own contribution first and the host cannot choose the seed.',
'ABORT: any aborted reset must disarm EntropyAck, or a later host EntropyAck would derive',
'a seed from sha256(0*32 || host_bytes) -- entirely host-chosen. That is K2.',
'PIN KDF: a v16 storage blob must still unlock and then rewrap to v19, or the upgrade bricks.',
],
[
('K1', 'test_msg_resetdevice', 'test_reset_device_dice_mixed_is_verifiable',
'Dice + device entropy, verified offline',
'Host selects MIXED (dice_entropy alone). The device shows the consent screen naming the '
'mode, then its own 32-byte draw as 24 BIP-39 words BEFORE any roll, then collects 99 rolls '
'over DebugLink with undo exercised. The test decodes the 24 words with its own '
'checksum-verified BIP-39 decoder, recomputes '
'seed = SHA256d(tag || draw || SHA256(tag || rolls)) from the published formula -- with the '
'host\'s EntropyAck bytes nowhere in it -- and requires the backup words to match. That is '
'the proof a user can repeat with tools/verify_dice_seed.py: the rolls reached the seed, '
'the device draw was the one it committed to, and the host contributed nothing.',
['Mode consent', 'Dice entry screen', 'Digest confirmation']),
('K1b', 'test_msg_resetdevice', 'test_reset_device_dice_only_is_verifiable',
'Dice only, verified offline',
'Host selects DICE ONLY (dice_entropy + dice_only), 50 rolls for a 12-word seed. No device '
'words are shown -- the rolls are the entire derivation -- and the test requires the backup '
'words to equal BIP39(SHA256(rolls)) while sending a nonzero EntropyAck that must be '
'ignored. Byte-identical to Coldcard\'s Dice-Rolls-Only.',
['Mode consent', 'Dice entry screen', 'Digest confirmation']),
('K1c', 'test_msg_resetdevice', 'test_reset_device_dice_rejects_biased_rolls',
'Loaded die is refused',
'Fifty ones -- one face on 100% of the rolls. Refused with SyntaxError before any digest '
'is drawn, per Coldcard\'s 30%-per-face rule, so a biased die never becomes a wallet.',
[]),
('K1d', 'test_msg_resetdevice', 'test_reset_device_dice_only_requires_dice_entropy',
'dice_only without dice_entropy is refused',
'The rolls-only derivation is a modifier of the dice ceremony, not a ceremony of its own; '
'the request is refused before any screen.',
[]),
('K1e', 'test_msg_resetdevice', 'test_reset_device_dice_refuses_no_backup',
'Dice with no_backup is refused',
'The dice modes exist to be checked against the backup words. A reset that never shows '
'them has nothing to verify and would put seed material on the screen under a WARNING '
'that recovery is impossible; refused before any screen.',
[]),
('K1f', 'test_msg_resetdevice', 'test_reset_device_dice_consent_cancel_aborts',
'Cancel at the consent screen aborts everything',
'The consent screen\'s only "no" is the host\'s Cancel. Asserts ActionCancelled, that a '
'subsequent EntropyAck finds no armed ceremony, and that the device is still uninitialized.',
[]),
('K2', 'test_msg_resetdevice', 'test_reset_reentry_disarms_entropy_ack',
'Aborted reset disarms EntropyAck',
'Regression for a host-chosen-seed hole: reset_init aborts left awaiting_entropy set from '
'an earlier run while zeroing int_entropy, so a following EntropyAck derived the seed '
'from host bytes alone. Arms a reset, re-enters with dice, cancels, and asserts the '
'next EntropyAck is refused with "Not in Reset mode" and the device stays uninitialized.',
[]),
('K3', 'Dice', 'RollsForStrength',
'Roll count per seed strength',
'd6 carries log2(6)=2.585 bits, so 128/192/256-bit seeds need 50/75/99 rolls '
'(the Coldcard convention). A short count would silently weaken the seed.',
[]),
('K4', 'Dice', 'DeriveOnlyIsPlainSha256OfRolls',
'DICE ONLY known-answer vector',
'seed = SHA256("123456") against a digest computed in Python from the published formula, '
'not captured from this code. Pins the derivation to Coldcard\'s Dice-Rolls-Only byte '
'for byte, so a refactor cannot quietly change what a user must recompute offline.',
[]),
('K5', 'Dice', 'DeriveMixedVector',
'MIXED known-answer vector',
'seed = SHA256d("KK\\x01SM" || 0x00..0x1f || SHA256("KK\\x01D" || "654321165243")) against a '
'Python-computed digest. Pins the tag bytes, hash order and double-SHA of the mixed '
'derivation -- the exact formula tools/verify_dice_seed.py implements.',
[]),
('K5b', 'Dice', 'DeriveMixedZeroDeviceVector',
'MIXED known-answer vector (zero device draw)',
'Same construction with an all-zero device draw, pinned to a Python-computed digest.',
[]),
('K5c', 'Dice', 'DeriveMixedAliasesInPlace',
'MIXED derives safely into its own input buffer',
'reset.c derives into the buffer the device draw lives in. In-place and separate-output '
'results must be identical, or the aliasing would corrupt the seed.',
[]),
('K6', 'Dice', 'DeriveMixedDiffersFromUntaggedMix',
'Tagged derivation cannot collide with the old formula',
'The MIXED seed for zero draw and "123456" must differ from SHA256(draw || rolls), the '
'derivation earlier firmware used, so a wallet is never silently re-derived under the '
'wrong formula.',
[]),
('K7', 'Dice', 'DeriveOnlyUsesExactCount',
'Only the counted rolls contribute',
'Bytes past the declared roll count must not affect the result, so uninitialized tail '
'bytes of the roll buffer can never leak into seed material.',
[]),
('K7b', 'Dice', 'BiasGateIsThirtyPercentPerFace',
'Loaded-die gate threshold',
'Coldcard\'s rule: any face over 30% of the rolls is refused. 30/99 fails, 29/99 passes; '
'16/50 fails, 15/50 (exactly 30%) passes.',
[]),
('K7c', 'Dice', 'BiasGateRejectsNonDiceBytes',
'Non-d6 bytes are refused',
'A byte outside \'1\'-\'6\' anywhere inside the counted rolls is refused regardless of the '
'distribution of the rest.',
[]),
('K8', 'Storage', 'PinKdfRewrapsToActiveVersionAfterCorrectPin',
'Correct PIN unlocks and rewraps to the ACTIVE KDF',
'The migration path for the hardened PIN KDF: an existing device must still unlock with '
'its current PIN, and any rewrap must target whatever KDF the build actually has '
'enabled. Renamed from PinKdfV16RewrapsToV19AfterCorrectPin because it is no longer '
'v19-specific -- the test now asserts BOTH sides of the STORAGE_PIN_KDF_V19 gate, so it '
'is meaningful in the shipping build where v19 is off. If this regressed, every '
'upgrading device would be locked out of its own seed.',
[]),
('K8b', 'Storage', 'PinUnlocksAfterRebootUnderV17',
'The PIN still opens the wallet after a reboot',
'The whole round trip in device order: create, set a PIN, serialize the V17 record as '
'storage_commit() does, reload into fresh state as a boot would, unlock, decrypt. Every '
'other storage test stays in RAM, and the wallet lockout this guards against lived '
'exactly on the serialize/reboot boundary -- a wrap the persisted record could not '
'describe, so the next boot derived the wrong KDF and every PIN failed.',
[]),
('K9', 'Storage', 'PinKdfV2FlagIsVersionedInV19',
'KDF version flag is recorded in v19',
'The new KDF is marked in the storage version band, so firmware can tell which derivation '
'a blob was written with instead of guessing.',
[]),
('K10', 'Storage', 'StorageUpgrade_Normal',
'Normal storage upgrade path',
'Baseline upgrade across storage versions with policies and cache preserved.',
[]),
('K11', 'Storage', 'NoopSecMigrate',
'Idempotent security migration',
'Re-running the migration on already-migrated storage must be a no-op rather than a '
'second rewrap.',
[]),
]),
('B', 'Bitcoin', '7.0.0',
'Bitcoin is the primary chain and most extensively tested. Covers legacy P2PKH, P2SH-wrapped '
'SegWit, native SegWit (bech32), and Taproot (P2TR). Transaction signing validates that the '
'device correctly displays every output address and amount, calculates fees, detects change '
'outputs, and resists output substitution attacks. Also covers UTXO forks sharing BTC signing code.',
[
'ADDRESS: Derive key from BIP-32 path -> display on OLED with QR code -> user verifies against host',
'SIGN TX: Device shows each output (full address + amount) -> shows fee -> user confirms -> signs',
'MESSAGE: Show text on OLED -> user confirms -> signs with address-specific key (EIP-191 equivalent)',
],
[
('B1', 'test_msg_getaddress', 'test_btc',
'Derive BTC legacy address',
'Derives a P2PKH (1...) address from standard BIP-44 path m/44\'/0\'/0\'/0/0. '
'Verifies the address matches the expected value from the test mnemonic.',
[]),
('B2', 'test_msg_getaddress', 'test_ltc',
'Derive Litecoin address',
'LTC uses the same derivation as BTC with coin_type=2. Verifies L... address format.',
[]),
('B3', 'test_msg_getaddress', 'test_tbtc',
'Derive testnet address',
'Testnet addresses use different version bytes (m/n prefix). Important for development testing.',
[]),
('B4', 'test_msg_getaddress_show', 'test_show',
'Show BTC address on OLED',
'Address displayed on OLED with QR code for visual verification. User compares the address '
'shown on the trusted device display against the host application. This is the primary defense '
'against address substitution attacks by compromised hosts.',
['BTC address + QR code']),
('B5', 'test_msg_getaddress_show', 'test_show_multisig_3',
'Show 3-of-3 multisig address',
'Multisig addresses require all co-signer xpubs. Device displays the P2SH multisig address '
'derived from all provided public keys.',
['Multisig address']),
('B6', 'test_msg_getaddress_segwit', 'test_show_segwit',
'Show SegWit P2SH address',
'P2SH-wrapped SegWit (3... prefix). Backwards compatible with legacy wallets while '
'getting SegWit fee savings.',
['SegWit address']),
('B7', 'test_msg_getaddress_segwit_native', 'test_show_segwit',
'Show native SegWit bech32',
'Native SegWit (bc1q... prefix). Lowest fees, modern address format. Verifies bech32 encoding.',
['bech32 address']),
('B8', 'test_msg_getpublickey', 'test_btc',
'Get BTC xpub',
'Exports the extended public key for a derivation path. Used by wallet software to '
'derive addresses and monitor balances without the device connected.',