forked from keepkey/python-keepkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-test-report.py
More file actions
2260 lines (2181 loc) · 131 KB
/
Copy pathgenerate-test-report.py
File metadata and controls
2260 lines (2181 loc) · 131 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)
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
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."""
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'
# Extract module from classname: tests.test_msg_foo.TestBar → test_msg_foo
mod = ''
if cls:
parts = cls.split('.')
for p in parts:
if p.startswith('test_msg_') or p.startswith('test_sign_') or p.startswith('test_verify_'):
mod = p
break
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 = {
('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 = [
('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 entropy',
'Reads random bytes from the hardware RNG. Used to verify the entropy source is functional.',
[]),
('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']),
]),
('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.',
[]),
('B9', 'test_msg_signtx', 'test_one_one_fee',
'Sign basic BTC transaction',
'Simplest case: one input, one output. Device displays "Send X BTC to [address]" with '
'the full recipient address (no truncation), then shows the fee. Verifies the signed '
'transaction is valid.',
['Send amount + address', 'Fee confirmation']),
('B10', 'test_msg_signtx', 'test_one_two_fee',
'Sign BTC tx with change',
'One input, two outputs (payment + change). Device must identify the change output '
'(same xpub tree) and only display the payment output to the user.',
['Output confirmation']),
('B11', 'test_msg_signtx', 'test_two_two',
'Sign multi-input BTC tx',
'Two inputs, two outputs. Verifies correct fee calculation across multiple inputs.',
[]),
('B12', 'test_msg_signtx', 'test_spend_coinbase',
'Sign coinbase spend',
'Spending a coinbase (mining reward) output. Coinbase outputs have special maturity rules.',
[]),
('B13', 'test_msg_signtx', 'test_lots_of_outputs',
'Sign tx with many outputs',
'Stress test with many recipients. Each output is displayed individually on the OLED.',
[]),
('B14', 'test_msg_signtx', 'test_fee_too_high',
'Reject excessive fee',
'If the fee exceeds a safety threshold, the device shows a prominent warning. Protects '
'against fat-finger errors or malicious fee manipulation.',
['High fee warning']),
('B15', 'test_msg_signtx', 'test_not_enough_funds',
'Reject insufficient funds',
'If inputs don\'t cover outputs + fee, the device refuses to sign.',
[]),
('B16', 'test_msg_signtx', 'test_p2sh',
'Sign P2SH transaction',
'Pay-to-Script-Hash output. Used for multisig and complex scripts.',
[]),
('B17', 'test_msg_signtx', 'test_attack_change_outputs',
'Detect output substitution',
'Security test: the host attempts to substitute the change output address between '
'the first and second signing pass. Device must detect the mismatch and refuse.',
[]),
('B18', 'test_msg_signtx_segwit', 'test_send_p2sh',
'Sign SegWit P2SH tx',
'SegWit transaction with P2SH-wrapped inputs. Different signing algorithm (BIP-143).',
[]),
('B19', 'test_msg_signtx_segwit', 'test_send_mixed',
'Sign mixed legacy+SegWit tx',
'Transaction with both legacy and SegWit inputs in the same transaction.',
[]),
('B20', 'test_msg_signtx_p2tr', 'test_send_p2tr_only',
'Create a Taproot P2TR output',
'Pays from SegWit inputs to a P2TR output. This exercises P2TR output parsing and '
'display, but does not exercise a Schnorr key-path spend.',
['Taproot output confirmation']),
('B21', 'test_msg_signtx_taproot', 'test_send_p2tr',
'Sign a Taproot key-path spend',
'Spends a BIP-86 P2TR input using BIP-341 SIGHASH_DEFAULT and a BIP-340 Schnorr '
'signature. The 64-byte witness is compared byte-for-byte with an independently '
'computed reference value.',
['P2TR recipient confirmation', 'Fee confirmation']),
('B22', 'test_msg_signtx_taproot', 'test_send_p2tr_with_change',
'Sign P2TR with device-derived change',
'Derives m/86\'/0\'/0\'/1/0 on-device, emits a P2TR change output, and verifies '
'the Schnorr witness against an independent BIP-340/341 reference.',
['P2TR recipient confirmation', 'Fee confirmation']),
('B23', 'test_msg_signtx_taproot', 'test_send_mixed_p2tr_and_legacy',
'Sign mixed Taproot and legacy inputs',
'Commits the P2TR signature to both inputs, including the legacy prevout amount and '
'scriptPubKey, while independently verifying the resulting Schnorr witness.',
[]),
('B24', 'test_msg_signtx_taproot',
'test_mixed_p2tr_requires_every_input_amount',
'Reject incomplete mixed Taproot commitments',
'Fails closed when any input amount is absent, preventing the device from producing '
'a valid Schnorr signature over an incomplete BIP-341 commitment.',
[]),
('B25', 'test_msg_signtx_taproot',
'test_mixed_p2tr_rejects_wrong_legacy_amount',
'Reject a tampered legacy prevout amount',
'Fetches the actual legacy prevout and rejects a host-provided amount that differs by '
'one satoshi, preventing a false BIP-341 commitment in a mixed-input transaction.',
[]),
('B26', 'test_msg_getaddress_taproot', 'test_show_taproot_address',
'Show BIP-86 address on OLED',
'Displays the complete bech32m Taproot receive address and QR code on the trusted '
'device screen for host-independent verification.',
['Taproot address + QR code']),
('B27', 'test_msg_signmessage', 'test_sign',
'Sign message with BTC key',
'Signs arbitrary text with a BTC address key. Used for proof-of-ownership and login.',
['Sign message on OLED']),
('B28', 'test_msg_signmessage_segwit', 'test_sign',
'Sign message with SegWit key', 'Message signing with P2SH-SegWit address key.', []),
('B29', 'test_msg_signmessage_segwit_native', 'test_sign',
'Sign message with bech32 key', 'Message signing with native SegWit address key.', []),
('B30', 'test_msg_verifymessage', 'test_message_verify',
'Verify signed message', 'Device verifies a message signature against a BTC address.', []),
('B31', 'test_msg_signtx_bgold', 'test_send_bitcoin_gold_nochange',
'Sign Bitcoin Gold tx', 'BTG fork uses same signing code with different chain parameters.', []),
('B32', 'test_msg_signtx_dash', 'test_send_dash',
'Sign Dash transaction', 'Dash special transaction types (InstantSend-compatible).', []),
('B33', 'test_msg_signtx_grs', 'test_one_one_fee',
'Sign Groestlcoin tx', 'GRS uses Groestl hash instead of SHA-256d for tx hashing.', []),
# Zcash transparent signing moved to its own section Y (Zcash Transparent).
]),
('E', 'Ethereum', '7.0.0',
'Ethereum covers native ETH transfers, ERC-20 tokens, EIP-1559 gas, personal message signing '
'(EIP-191), and contract interactions. The device displays checksummed addresses (EIP-55) and '
'gas parameters. Amount UNIT rule: values below 1 gwei (1e9 wei) show as raw "Wei" (there is '
'no smaller human unit to scale to); values at or above 1 gwei show 18-decimal-scaled ETH (or '
'the chain-native ticker on other EVM chains). Some tests below use small conformance-vector '
'amounts (e.g. 10 wei) for deterministic-signature pinning — their OLED frames legitimately '
'show raw "Wei", not a display bug.',
[
'ETH TRANSFER: Show "Send X ETH to 0x..." -> show gas -> confirm -> sign with secp256k1',
'ERC-20: Decode transfer(to,amount) from contract data -> show token name + amount',
'EIP-1559: Show maxFeePerGas + maxPriorityFeePerGas (not legacy gasPrice)',
'MESSAGE: EIP-191 prefix -> show text on OLED -> sign with ETH key',
],
[
('E1', 'test_msg_ethereum_getaddress', 'test_ethereum_getaddress',
'Derive ETH address', 'Standard m/44\'/60\'/0\'/0/0 derivation. EIP-55 checksum address.', ['ETH address']),
('E2', 'test_msg_ethereum_signtx', 'test_ethereum_signtx_nodata',
'Sign ETH transfer',
'Simple value transfer with no contract data. Device shows recipient + amount + gas.',
['ETH send confirmation']),
('E3', 'test_msg_ethereum_signtx', 'test_ethereum_signtx_data',
'Sign ETH tx with contract data',
'Transaction with data field (contract call). Device shows data as hex since it cannot '
'decode arbitrary ABI without metadata.',
['Contract data hex']),
('E4', 'test_msg_ethereum_signtx', 'test_ethereum_signtx_nodata_eip155',
'Sign ETH with EIP-155 replay protection',
'Chain ID embedded in signature v value to prevent cross-chain replay attacks.', []),
('E5', 'test_msg_ethereum_signtx', 'test_ethereum_eip_1559',
'Sign EIP-1559 transaction',
'Type 2 transaction with base fee + priority fee. Device shows both gas parameters.',
['EIP-1559 gas display']),
('E5b', 'test_msg_ethereum_signtx_chunked_data_eip1559',
'test_eip1559_chunked_data_signature_recovers_to_device_address',
'Sign EIP-1559 with data > 1024 B (chunked transmission)',
'Regression for an access-list ordering bug in firmware/ethereum.c — when data exceeded '
'the 1024-byte single-chunk threshold, the empty access-list byte (0xC0) was hashed '
'between data chunks instead of after them, producing a non-canonical pre-image. The '
'signature recovered to a wrong-but-deterministic address and the broadcast tx was '
'dropped from the mempool. Fixed in 7.14.1.',
[]),
('E6', 'test_msg_ethereum_signtx', 'test_ethereum_signtx_knownerc20_eip_1559',
'Sign known ERC-20 (EIP-1559)',
'Known token (in firmware token list) via EIP-1559. Shows human-readable token name + amount.',
['Token transfer display']),
('E7', 'test_msg_ethereum_message', 'test_ethereum_sign_message',
'Sign personal message',
'EIP-191 personal_sign. Device shows the message text on OLED for user to verify before signing.',
['Sign message screen']),
('E8', 'test_msg_ethereum_message', 'test_ethereum_sign_bytes',
'Sign raw bytes', 'Signs arbitrary bytes (displayed as hex on OLED).', []),
('E9', 'test_msg_ethereum_message', 'test_ethereum_verify_message',
'Verify ETH signed message', 'Device-side verification of EIP-191 signed messages.', []),
('E10', 'test_msg_signtx_ethereum_erc20', 'test_approve_some',
'ERC-20 approve specific amount',
'Token approval for a specific amount. Device shows spender address + approved amount.',
['Approval screen']),
('E11', 'test_msg_signtx_ethereum_erc20', 'test_approve_all',
'ERC-20 approve unlimited',
'MAX_UINT256 approval. Device shows "UNLIMITED" warning since this grants infinite spending.',
['Unlimited approval warning']),
('E12', 'test_msg_ethereum_makerdao', 'test_generate',
'MakerDAO generate DAI', 'Complex DeFi contract interaction (MakerDAO CDP).', []),
('E13', 'test_msg_ethereum_sablier', 'test_sign_salarywithdrawal',
'Sablier salary withdrawal', 'Streaming payment protocol contract call.', []),
('E14', 'test_msg_ethereum_erc20_0x_signtx', 'test_sign_0x_swap_ETH_to_ERC20',
'0x swap ETH to ERC-20', 'DEX aggregator swap via 0x protocol.', []),
('E15', 'test_msg_ethereum_cfunc', 'test_sign_execTx',
'Contract function call', 'Generic contract call signing.', []),
('E16', 'test_sign_typed_data', 'test_ethereum_sign_typed_data_hash',
'EIP-712 typed-data hash signing (legacy, no on-device display)',
'The legacy endpoint receives two host-computed 32-byte hashes, so firmware keeps it '
'behind AdvancedMode and cannot show readable WHO/WHAT. Structured formats such as '
'x402 EIP-3009 use the separate device-parsed path proven by E16b.',
[]),
('E16b', 'test_sign_typed_data', 'test_ethereum_sign_x402_eip3009',
'x402 EVM EIP-3009 payment clear-signs structured data',
'The device computes the EIP-712 hashes itself and displays the Base Sepolia USDC '
'domain plus every TransferWithAuthorization field: payer, recipient, exact value, '
'validity window and nonce. AdvancedMode stays OFF; the facilitator pays gas but '
'cannot alter the signed destination or amount.',
['USDC domain fields', 'TransferWithAuthorization fields']),
('E17', 'test_msg_ethereum_erc20_uniswap_liquidity', 'test_sign_uni_approve_liquidity_ETH',
'Uniswap V2 add-liquidity approve (pending)',
'PENDING, disclosed: known emulator limitation — an approve to an unknown (non-registry) '
'token contract cannot complete against the kkemu emulator (matches the sibling '
'add/remove-liquidity skips below); the device-firmware path is not in question, only '
'CI emulator coverage. Real-device testing is unaffected.',
[]),
('E18', 'test_msg_ethereum_erc20_uniswap_liquidity', 'test_sign_uni_add_liquidity_ETH',
'Uniswap V2 add liquidity ETH+token (pending)',
'PENDING, disclosed: same emulator limitation as E17 — a daily-driver LP-deposit flow '
'with no PDF proof on this build; tracked for real-device verification.',
[]),
('E19', 'test_msg_ethereum_erc20_uniswap_liquidity', 'test_sign_uni_remove_liquidity_ETH',
'Uniswap V2 remove liquidity ETH+token (pending)',
'PENDING, disclosed: same emulator limitation as E17.',
[]),
('E20', 'test_msg_ethereum_thorchain_deposit', 'test_deposit_legacy_selector',
'THORChain router deposit() (legacy selector)',
'Cross-chain swap via the THORChain router contract — a daily-driver EVM<->THORChain '
'swap path, natively decoded (asset/amount/memo) without clear-sign metadata. The '
'native amount shown is the signed msg.value (the ABI amount word is a router-ignored '
'hint and is never displayed as the send amount).',
['Deposit amount (msg.value)', 'Full memo']),
('E21', 'test_msg_ethereum_thorchain_deposit', 'test_deposit_with_expiry_selector',
'THORChain router depositWithExpiry()',
'Newer router selector variant with an expiry field; same native decode path. The ABI '
'memo length word is read from the calldata (not assumed 64 bytes) and the padded memo '
'must end exactly at the calldata end.',
['Deposit amount (msg.value)', 'Full memo']),
('E22', 'test_msg_ethereum_thorchain_deposit',
'test_deposit_with_expiry_non_thor_address_blind_sign_blocked',
'THORChain router call to a non-pinned address is blind-sign gated',
'WHY it can be trusted: the router CONTRACT ADDRESS is pinned; a call shaped like a '
'THORChain deposit but sent to an unpinned address is refused native decoding and falls '
'through to the ordinary blind-sign gate instead of being silently native-decoded — the '
'fix for the router-spoofing / blind-sign-bypass class of attack.',
['Blind sign disabled (Blocked)']),
('E23', 'test_msg_ethereum_thorchain_deposit',
'test_deposit_with_expiry_avalanche_router',
'THORChain deposit on Avalanche clear-signs (per-chain router pin)',
'THORChain deploys its router at a DIFFERENT address on every EVM chain, so the pin is '
'(chain_id, address) together. Before the chain scope, only mainnet deposits ever '
'matched and an AVAX->ETH swap fell into the blind-sign gate. The Avalanche C-Chain '
'router (00dc61..f1d4) is verified live against THORChain /inbound_addresses; the '
'native amount screen shows msg.value with the CHAIN\'s ticker (AVAX), and the '
'signature is ECDSA-recovered against the host-built pre-image over chainId 43114.',
['Thorchain router screen', 'AVAX amount', 'Full memo']),
('E24', 'test_msg_ethereum_thorchain_deposit',
'test_deposit_unpinned_chain_blind_sign_blocked',
'Deposit on an unpinned chain is blind-sign gated',
'The mainnet router ADDRESS on a chain with no pinned router (BSC) must not inherit '
'the deposit UX — the same address on another chain may hold unrelated attacker code. '
'Falls to the AdvancedMode gate; rejection is pre-UI (no frame).',
[]),
]),
('R', 'Ripple (XRP)', '7.0.0',
'XRP Ledger support for the third-largest cryptocurrency by market cap. XRP uses a unique '
'account-based model (not UTXO) with 20 XRP minimum reserve. Amounts are denominated in '
'drops (1 XRP = 1,000,000 drops). Destination tags are required for exchange deposits to '
'route funds to the correct account. The device displays the full rAddress (34 chars starting '
'with r) and converts drop amounts to human-readable XRP values.',
[
'ADDRESS: Derive from m/44\'/144\'/0\'/0/0 -> display full rAddress + QR on OLED',
'SIGN: Host sends Payment tx (destination, amount, fee, destination_tag) -> device shows XRP amount + recipient',
'FEE: XRP requires a minimum fee (currently 10 drops). Device validates fee is within bounds.',
],
[
('R1', 'test_msg_ripple_get_address', 'test_ripple_get_address',
'Derive XRP address', 'Standard m/44\'/144\'/0\'/0/0 derivation.', ['XRP address']),
('R2', 'test_msg_ripple_sign_tx', 'test_sign',
'Sign XRP payment', 'Payment with amount in drops (1 XRP = 1,000,000 drops).', ['XRP send']),
('R3', 'test_msg_ripple_sign_tx', 'test_ripple_sign_invalid_fee',
'Reject invalid fee', 'Fee outside acceptable range is rejected.', []),
]),
('A', 'Cosmos (ATOM)', '7.0.0',
'Cosmos Hub is the anchor chain for the Cosmos IBC ecosystem. Transactions use amino encoding '
'(legacy Cosmos SDK format). The device supports MsgSend (transfers), MsgDelegate (staking to '
'validators), and MsgWithdrawDelegatorReward (claiming staking rewards). Addresses use bech32 '
'encoding with the cosmos1 prefix. Memo field is critical for exchange deposits and IBC transfers - '
'the device displays it in full on the OLED for user verification.',
[
'ADDRESS: Derive from m/44\'/118\'/0\'/0/0 -> display cosmos1... bech32 address',
'SEND: Show recipient address + ATOM amount + memo on OLED -> user confirms',
'MEMO: Displayed in full - required for exchange deposits (e.g. numeric account ID)',
],
[
('A1', 'test_msg_cosmos_getaddress', 'test_standard',
'Derive Cosmos address', 'Bech32 cosmos1... address from m/44\'/118\'/0\'/0/0.',
[]), # show_display=True + set_expected_responses breaks with screenshot mode
('A2', 'test_msg_cosmos_signtx', 'test_cosmos_sign_tx',