From 175db636e6aa0ce3b921364c7ec77cd7fc70801b Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 22 Aug 2026 07:11:27 -0500 Subject: [PATCH 01/12] Hash-lock the remaining requirements pins Cover requirements.txt, tests/requirements.txt, and requirements-raspi.txt like the l10n pins: every entry now carries the sha256 of every published file for its release, so pip refuses any unverified artifact. Hash-checking mode can't verify git checkouts, so the pyzbar and urtypes deps become commit-pinned GitHub archive tarballs. The mode also demands pins for everything in the invocation, so pytest's transitive deps are pinned too, and coverage is pinned as coverage[toml]: older pips (e.g. the docker dev image's) won't accept a plain pin as satisfying pytest-cov's extra-qualified dependency. --- .github/workflows/tests.yml | 11 ++- requirements-raspi.txt | 56 +++++++++++++-- requirements.txt | 105 ++++++++++++++++++++++++++-- tests/requirements.txt | 132 +++++++++++++++++++++++++++++++++++- 4 files changed, 285 insertions(+), 19 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 821e1a226..93c4b240c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -53,13 +53,10 @@ jobs: run: | sudo apt-get install libzbar0 python -m pip install --upgrade pip - pip install -r requirements.txt -r tests/requirements.txt - # requirements-l10n.txt is hash-locked (SeedSigner OS installs it - # during image builds). It needs its own pip invocation: one hashed - # requirement makes pip demand hashes for everything else in the - # same invocation, which the unhashed files above and `-e .` below - # can't satisfy. - pip install -r l10n/requirements-l10n.txt + # hash-locked requirements files + pip install -r requirements.txt -r tests/requirements.txt l10n/requirements-l10n.txt + # An editable install can't satisfy hash-checking, so `-e .` can't + # share an invocation with the hash-locked files above. pip install -e . - name: Compile translations run: python setup.py compile_catalog diff --git a/requirements-raspi.txt b/requirements-raspi.txt index b767562ba..eb5a9f2b9 100644 --- a/requirements-raspi.txt +++ b/requirements-raspi.txt @@ -1,5 +1,53 @@ -picamera==1.13 +# Raspberry Pi hardware dependencies (installed on the Pi itself; see +# docs/raspberry_pi_os_build_instructions.md). Entries are pinned and +# hash-locked: pip refuses any artifact that does not match a hash below. +# Hashes cover every published file of each release (wheels + sdist). +# +# To update a pin: change the version, then refresh its hashes from +# https://pypi.org/pypi///json (or pip download + pip hash). +# +# NOTE: piwheels rebuilds wheels, so its artifacts will not match these PyPI +# hashes. pip skips the mismatched piwheels candidates and builds from the +# PyPI sdists instead (the from-source build the install doc already assumes); +# very old pips may error on the mismatch instead of skipping — upgrade pip. +picamera==1.13 \ + --hash=sha256:890815aa01e4d855a6a95dd3ad0953b872a6b954982106407df0c5a31a163e50 # numpy = transitive picamera dependency -numpy==1.25.0 -RPi.GPIO==0.7.1 -spidev==3.6 +numpy==1.25.0 \ + --hash=sha256:0ac6edfb35d2a99aaf102b509c8e9319c499ebd4978df4971b94419a116d0790 \ + --hash=sha256:26815c6c8498dc49d81faa76d61078c4f9f0859ce7817919021b9eba72b425e3 \ + --hash=sha256:4aedd08f15d3045a4e9c648f1e04daca2ab1044256959f1f95aafeeb3d794c16 \ + --hash=sha256:4c69fe5f05eea336b7a740e114dec995e2f927003c30702d896892403df6dbf0 \ + --hash=sha256:5177310ac2e63d6603f659fadc1e7bab33dd5a8db4e0596df34214eeab0fee3b \ + --hash=sha256:5aa48bebfb41f93043a796128854b84407d4df730d3fb6e5dc36402f5cd594c0 \ + --hash=sha256:5b1b90860bf7d8a8c313b372d4f27343a54f415b20fb69dd601b7efe1029c91e \ + --hash=sha256:6c284907e37f5e04d2412950960894b143a648dea3f79290757eb878b91acbd1 \ + --hash=sha256:6d183b5c58513f74225c376643234c369468e02947b47942eacbb23c1671f25d \ + --hash=sha256:7412125b4f18aeddca2ecd7219ea2d2708f697943e6f624be41aa5f8a9852cc4 \ + --hash=sha256:7cd981ccc0afe49b9883f14761bb57c964df71124dcd155b0cba2b591f0d64b9 \ + --hash=sha256:85cdae87d8c136fd4da4dad1e48064d700f63e923d5af6c8c782ac0df8044542 \ + --hash=sha256:8aa130c3042052d656751df5e81f6d61edff3e289b5994edcf77f54118a8d9f4 \ + --hash=sha256:95367ccd88c07af21b379be1725b5322362bb83679d36691f124a16357390153 \ + --hash=sha256:9c7211d7920b97aeca7b3773a6783492b5b93baba39e7c36054f6e749fc7490c \ + --hash=sha256:9e3f2b96e3b63c978bc29daaa3700c028fe3f049ea3031b58aa33fe2a5809d24 \ + --hash=sha256:b76aa836a952059d70a2788a2d98cb2a533ccd46222558b6970348939e55fc24 \ + --hash=sha256:b792164e539d99d93e4e5e09ae10f8cbe5466de7d759fc155e075237e0c274e4 \ + --hash=sha256:c0dc071017bc00abb7d7201bac06fa80333c6314477b3d10b52b58fa6a6e38f6 \ + --hash=sha256:cc3fda2b36482891db1060f00f881c77f9423eead4c3579629940a3e12095fe8 \ + --hash=sha256:d6b267f349a99d3908b56645eebf340cb58f01bd1e773b4eea1a905b3f0e4208 \ + --hash=sha256:d76a84998c51b8b68b40448ddd02bd1081bb33abcdc28beee6cd284fe11036c6 \ + --hash=sha256:e559c6afbca484072a98a51b6fa466aae785cfe89b69e8b856c3191bc8872a82 \ + --hash=sha256:ecc68f11404930e9c7ecfc937aa423e1e50158317bf67ca91736a9864eae0232 \ + --hash=sha256:f1accae9a28dc3cda46a91de86acf69de0d1b5f4edd44a9b0c3ceb8036dfff19 +RPi.GPIO==0.7.1 \ + --hash=sha256:15311d3b063b71dee738cd26570effc9985a952454d162937c34e08c0fc99902 \ + --hash=sha256:26b2ade4bb353bbe5417a64e40b45cdf00a82f27c2d320c0dd46c59751959d77 \ + --hash=sha256:29226823da8b5ccb9001d795a944f2e00924eeae583490f0bc7317581172c624 \ + --hash=sha256:57b6c044ef5375a78c8dda27cdfadf329e76aa6943cd6cffbbbd345a9adf9ca5 \ + --hash=sha256:77afb817b81331ce3049a4b8f94a85e41b7c404d8e56b61ac0f1eb75c3120868 \ + --hash=sha256:96ea7e5bf6bf592828487bfa7d3d1d0e432d5d1682e9e33b4dab398914628fcd \ + --hash=sha256:b86b66dc02faa5461b443a1e1f0c1d209d64ab5229696f32fb3b0215e0600c8c \ + --hash=sha256:cd61c4b03c37b62bba4a5acfea9862749c33c618e0295e7e90aa4713fb373b70 +spidev==3.6 \ + --hash=sha256:14dbc37594a4aaef85403ab617985d3c3ef464d62bc9b769ef552db53701115b \ + --hash=sha256:280abc00a1ef7780ef62c3f294f52a2527b6c47d8c269fea98664970bcaf6da5 diff --git a/requirements.txt b/requirements.txt index 7961b3426..80469ae30 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,100 @@ -embit==0.8.0 -Pillow==10.3.0 -pyzbar @ git+https://github.com/seedsigner/pyzbar.git@c3c237821c6a20b17953efe59b90df0b514a1c03 -qrcode==8.0 -urtypes @ git+https://github.com/selfcustody/urtypes.git@7fb280eab3b3563dfc57d2733b0bf5cbc0a96a6a +# Runtime dependencies. Entries are pinned and hash-locked: pip refuses any +# artifact that does not match a hash below. Hashes cover every published file +# of each release (wheels + sdist). +# +# To update a pin: change the version, then refresh its hashes from +# https://pypi.org/pypi///json (or pip download + pip hash). +# +# pyzbar and urtypes point at commit-pinned GitHub source archives instead of +# git+ URLs: pip's hash-checking mode cannot verify a git checkout, but it can +# verify the archive tarball built from the same commit. +# +# NOTE: a hash-locked file may share a `pip install` invocation only with other +# fully hashed files (e.g. `-r requirements.txt -r tests/requirements.txt`). +# Combining it with unhashed requirements (or `-e .`) in one invocation fails, +# because any hash in an invocation makes pip require hashes for everything +# in it. +embit==0.8.0 \ + --hash=sha256:8bf4b10073c67400370ce523fb16f035fe759f6fdd987c579bdcc268d75ed770 +Pillow==10.3.0 \ + --hash=sha256:048ad577748b9fa4a99a0548c64f2cb8d672d5bf2e643a739ac8faff1164238c \ + --hash=sha256:048eeade4c33fdf7e08da40ef402e748df113fd0b4584e32c4af74fe78baaeb2 \ + --hash=sha256:0ba26351b137ca4e0db0342d5d00d2e355eb29372c05afd544ebf47c0956ffeb \ + --hash=sha256:0ea2a783a2bdf2a561808fe4a7a12e9aa3799b701ba305de596bc48b8bdfce9d \ + --hash=sha256:1530e8f3a4b965eb6a7785cf17a426c779333eb62c9a7d1bbcf3ffd5bf77a4aa \ + --hash=sha256:16563993329b79513f59142a6b02055e10514c1a8e86dca8b48a893e33cf91e3 \ + --hash=sha256:19aeb96d43902f0a783946a0a87dbdad5c84c936025b8419da0a0cd7724356b1 \ + --hash=sha256:1a1d1915db1a4fdb2754b9de292642a39a7fb28f1736699527bb649484fb966a \ + --hash=sha256:1b87bd9d81d179bd8ab871603bd80d8645729939f90b71e62914e816a76fc6bd \ + --hash=sha256:1dfc94946bc60ea375cc39cff0b8da6c7e5f8fcdc1d946beb8da5c216156ddd8 \ + --hash=sha256:2034f6759a722da3a3dbd91a81148cf884e91d1b747992ca288ab88c1de15999 \ + --hash=sha256:261ddb7ca91fcf71757979534fb4c128448b5b4c55cb6152d280312062f69599 \ + --hash=sha256:2ed854e716a89b1afcedea551cd85f2eb2a807613752ab997b9974aaa0d56936 \ + --hash=sha256:3102045a10945173d38336f6e71a8dc71bcaeed55c3123ad4af82c52807b9375 \ + --hash=sha256:339894035d0ede518b16073bdc2feef4c991ee991a29774b33e515f1d308e08d \ + --hash=sha256:412444afb8c4c7a6cc11a47dade32982439925537e483be7c0ae0cf96c4f6a0b \ + --hash=sha256:4203efca580f0dd6f882ca211f923168548f7ba334c189e9eab1178ab840bf60 \ + --hash=sha256:45ebc7b45406febf07fef35d856f0293a92e7417ae7933207e90bf9090b70572 \ + --hash=sha256:4b5ec25d8b17217d635f8935dbc1b9aa5907962fae29dff220f2659487891cd3 \ + --hash=sha256:4c8e73e99da7db1b4cad7f8d682cf6abad7844da39834c288fbfa394a47bbced \ + --hash=sha256:4e6f7d1c414191c1199f8996d3f2282b9ebea0945693fb67392c75a3a320941f \ + --hash=sha256:4eaa22f0d22b1a7e93ff0a596d57fdede2e550aecffb5a1ef1106aaece48e96b \ + --hash=sha256:50b8eae8f7334ec826d6eeffaeeb00e36b5e24aa0b9df322c247539714c6df19 \ + --hash=sha256:50fd3f6b26e3441ae07b7c979309638b72abc1a25da31a81a7fbd9495713ef4f \ + --hash=sha256:51243f1ed5161b9945011a7360e997729776f6e5d7005ba0c6879267d4c5139d \ + --hash=sha256:5d512aafa1d32efa014fa041d38868fda85028e3f930a96f85d49c7d8ddc0383 \ + --hash=sha256:5f77cf66e96ae734717d341c145c5949c63180842a545c47a0ce7ae52ca83795 \ + --hash=sha256:6b02471b72526ab8a18c39cb7967b72d194ec53c1fd0a70b050565a0f366d355 \ + --hash=sha256:6fb1b30043271ec92dc65f6d9f0b7a830c210b8a96423074b15c7bc999975f57 \ + --hash=sha256:7161ec49ef0800947dc5570f86568a7bb36fa97dd09e9827dc02b718c5643f09 \ + --hash=sha256:72d622d262e463dfb7595202d229f5f3ab4b852289a1cd09650362db23b9eb0b \ + --hash=sha256:74d28c17412d9caa1066f7a31df8403ec23d5268ba46cd0ad2c50fb82ae40462 \ + --hash=sha256:78618cdbccaa74d3f88d0ad6cb8ac3007f1a6fa5c6f19af64b55ca170bfa1edf \ + --hash=sha256:793b4e24db2e8742ca6423d3fde8396db336698c55cd34b660663ee9e45ed37f \ + --hash=sha256:798232c92e7665fe82ac085f9d8e8ca98826f8e27859d9a96b41d519ecd2e49a \ + --hash=sha256:81d09caa7b27ef4e61cb7d8fbf1714f5aec1c6b6c5270ee53504981e6e9121ad \ + --hash=sha256:8ab74c06ffdab957d7670c2a5a6e1a70181cd10b727cd788c4dd9005b6a8acd9 \ + --hash=sha256:8eb0908e954d093b02a543dc963984d6e99ad2b5e36503d8a0aaf040505f747d \ + --hash=sha256:90b9e29824800e90c84e4022dd5cc16eb2d9605ee13f05d47641eb183cd73d45 \ + --hash=sha256:9797a6c8fe16f25749b371c02e2ade0efb51155e767a971c61734b1bf6293994 \ + --hash=sha256:9d2455fbf44c914840c793e89aa82d0e1763a14253a000743719ae5946814b2d \ + --hash=sha256:9d3bea1c75f8c53ee4d505c3e67d8c158ad4df0d83170605b50b64025917f338 \ + --hash=sha256:9e2ec1e921fd07c7cda7962bad283acc2f2a9ccc1b971ee4b216b75fad6f0463 \ + --hash=sha256:9e91179a242bbc99be65e139e30690e081fe6cb91a8e77faf4c409653de39451 \ + --hash=sha256:a0eaa93d054751ee9964afa21c06247779b90440ca41d184aeb5d410f20ff591 \ + --hash=sha256:a2c405445c79c3f5a124573a051062300936b0281fee57637e706453e452746c \ + --hash=sha256:aa7e402ce11f0885305bfb6afb3434b3cd8f53b563ac065452d9d5654c7b86fd \ + --hash=sha256:aff76a55a8aa8364d25400a210a65ff59d0168e0b4285ba6bf2bd83cf675ba32 \ + --hash=sha256:b09b86b27a064c9624d0a6c54da01c1beaf5b6cadfa609cf63789b1d08a797b9 \ + --hash=sha256:b14f16f94cbc61215115b9b1236f9c18403c15dd3c52cf629072afa9d54c1cbf \ + --hash=sha256:b50811d664d392f02f7761621303eba9d1b056fb1868c8cdf4231279645c25f5 \ + --hash=sha256:b7bc2176354defba3edc2b9a777744462da2f8e921fbaf61e52acb95bafa9828 \ + --hash=sha256:c78e1b00a87ce43bb37642c0812315b411e856a905d58d597750eb79802aaaa3 \ + --hash=sha256:c83341b89884e2b2e55886e8fbbf37c3fa5efd6c8907124aeb72f285ae5696e5 \ + --hash=sha256:ca2870d5d10d8726a27396d3ca4cf7976cec0f3cb706debe88e3a5bd4610f7d2 \ + --hash=sha256:ccce24b7ad89adb5a1e34a6ba96ac2530046763912806ad4c247356a8f33a67b \ + --hash=sha256:cd5e14fbf22a87321b24c88669aad3a51ec052eb145315b3da3b7e3cc105b9a2 \ + --hash=sha256:ce49c67f4ea0609933d01c0731b34b8695a7a748d6c8d186f95e7d085d2fe475 \ + --hash=sha256:d33891be6df59d93df4d846640f0e46f1a807339f09e79a8040bc887bdcd7ed3 \ + --hash=sha256:d3b2348a78bc939b4fed6552abfd2e7988e0f81443ef3911a4b8498ca084f6eb \ + --hash=sha256:d886f5d353333b4771d21267c7ecc75b710f1a73d72d03ca06df49b09015a9ef \ + --hash=sha256:d93480005693d247f8346bc8ee28c72a2191bdf1f6b5db469c096c0c867ac015 \ + --hash=sha256:dc1a390a82755a8c26c9964d457d4c9cbec5405896cba94cf51f36ea0d855002 \ + --hash=sha256:dd78700f5788ae180b5ee8902c6aea5a5726bac7c364b202b4b3e3ba2d293170 \ + --hash=sha256:e46f38133e5a060d46bd630faa4d9fa0202377495df1f068a8299fd78c84de84 \ + --hash=sha256:e4b878386c4bf293578b48fc570b84ecfe477d3b77ba39a6e87150af77f40c57 \ + --hash=sha256:f0d0591a0aeaefdaf9a5e545e7485f89910c977087e7de2b6c388aec32011e9f \ + --hash=sha256:fdcbb4068117dfd9ce0138d068ac512843c52295ed996ae6dd1faf537b6dbc27 \ + --hash=sha256:ff61bfd9253c3915e6d41c651d5f962da23eda633cf02262990094a18a55371a +pyzbar @ https://github.com/seedsigner/pyzbar/archive/c3c237821c6a20b17953efe59b90df0b514a1c03.tar.gz \ + --hash=sha256:b8589bfea4a2b5d439b5dde63bd545f595ec9115ec1dcb49dd55c86cf6fcdc74 +qrcode==8.0 \ + --hash=sha256:025ce2b150f7fe4296d116ee9bad455a6643ab4f6e7dce541613a4758cbce347 \ + --hash=sha256:9fc05f03305ad27a709eb742cf3097fa19e6f6f93bb9e2f039c0979190f6f1b1 +urtypes @ https://github.com/selfcustody/urtypes/archive/7fb280eab3b3563dfc57d2733b0bf5cbc0a96a6a.tar.gz \ + --hash=sha256:bab06f952d9c93c8756068e2252751840b3c7ba102cdb273c4325c57e991bd2e + +# colorama = transitive qrcode (and pytest) dependency, Windows-only +colorama==0.4.6 ; sys_platform == "win32" \ + --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ + --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 diff --git a/tests/requirements.txt b/tests/requirements.txt index 51e26f396..00fa446e4 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -1,3 +1,129 @@ -coverage==7.6.12 -pytest==7.4.2 -pytest-cov==4.1.0 +# Test-run dependencies. Entries are pinned and hash-locked: pip refuses any +# artifact that does not match a hash below. Hashes cover every published file +# of each release (wheel + sdist). +# +# To update a pin: change the version, then refresh its hashes from +# https://pypi.org/pypi///json (or pip download + pip hash). +# +# Hash-checking extends to everything pip installs in the invocation, so +# pytest's transitive dependencies must be pinned and hashed here too. +# The [toml] extra matches how pytest-cov declares its coverage dependency; without +# it, older pips refuse to accept this pin as satisfying coverage[toml]. +coverage[toml]==7.6.12 \ + --hash=sha256:00b2086892cf06c7c2d74983c9595dc511acca00665480b3ddff749ec4fb2a95 \ + --hash=sha256:0533adc29adf6a69c1baa88c3d7dbcaadcffa21afbed3ca7a225a440e4744bf9 \ + --hash=sha256:06097c7abfa611c91edb9e6920264e5be1d6ceb374efb4986f38b09eed4cb2fe \ + --hash=sha256:07e92ae5a289a4bc4c0aae710c0948d3c7892e20fd3588224ebe242039573bf0 \ + --hash=sha256:0a9d8be07fb0832636a0f72b80d2a652fe665e80e720301fb22b191c3434d924 \ + --hash=sha256:0e549f54ac5f301e8e04c569dfdb907f7be71b06b88b5063ce9d6953d2d58574 \ + --hash=sha256:0ef01d70198431719af0b1f5dcbefc557d44a190e749004042927b2a3fed0702 \ + --hash=sha256:0f16f44025c06792e0fb09571ae454bcc7a3ec75eeb3c36b025eccf501b1a4c3 \ + --hash=sha256:14d47376a4f445e9743f6c83291e60adb1b127607a3618e3185bbc8091f0467b \ + --hash=sha256:1a936309a65cc5ca80fa9f20a442ff9e2d06927ec9a4f54bcba9c14c066323f2 \ + --hash=sha256:1ceeb90c3eda1f2d8c4c578c14167dbd8c674ecd7d38e45647543f19839dd6ea \ + --hash=sha256:1f7ffa05da41754e20512202c866d0ebfc440bba3b0ed15133070e20bf5aeb5f \ + --hash=sha256:200e10beb6ddd7c3ded322a4186313d5ca9e63e33d8fab4faa67ef46d3460af3 \ + --hash=sha256:220fa6c0ad7d9caef57f2c8771918324563ef0d8272c94974717c3909664e674 \ + --hash=sha256:2251fabcfee0a55a8578a9d29cecfee5f2de02f11530e7d5c5a05859aa85aee9 \ + --hash=sha256:2458f275944db8129f95d91aee32c828a408481ecde3b30af31d552c2ce284a0 \ + --hash=sha256:299cf973a7abff87a30609879c10df0b3bfc33d021e1adabc29138a48888841e \ + --hash=sha256:2b996819ced9f7dbb812c701485d58f261bef08f9b85304d41219b1496b591ef \ + --hash=sha256:3688b99604a24492bcfe1c106278c45586eb819bf66a654d8a9a1433022fb2eb \ + --hash=sha256:3a1e465f398c713f1b212400b4e79a09829cd42aebd360362cd89c5bdc44eb87 \ + --hash=sha256:488c27b3db0ebee97a830e6b5a3ea930c4a6e2c07f27a5e67e1b3532e76b9ef1 \ + --hash=sha256:48cfc4641d95d34766ad41d9573cc0f22a48aa88d22657a1fe01dca0dbae4de2 \ + --hash=sha256:4b467a8c56974bf06e543e69ad803c6865249d7a5ccf6980457ed2bc50312703 \ + --hash=sha256:53c56358d470fa507a2b6e67a68fd002364d23c83741dbc4c2e0680d80ca227e \ + --hash=sha256:5d1095bbee1851269f79fd8e0c9b5544e4c00c0c24965e66d8cba2eb5bb535fd \ + --hash=sha256:641dfe0ab73deb7069fb972d4d9725bf11c239c309ce694dd50b1473c0f641c3 \ + --hash=sha256:64cbb1a3027c79ca6310bf101014614f6e6e18c226474606cf725238cf5bc2d4 \ + --hash=sha256:66fe626fd7aa5982cdebad23e49e78ef7dbb3e3c2a5960a2b53632f1f703ea45 \ + --hash=sha256:676f92141e3c5492d2a1596d52287d0d963df21bf5e55c8b03075a60e1ddf8aa \ + --hash=sha256:69e62c5034291c845fc4df7f8155e8544178b6c774f97a99e2734b05eb5bed31 \ + --hash=sha256:704c8c8c6ce6569286ae9622e534b4f5b9759b6f2cd643f1c1a61f666d534fe8 \ + --hash=sha256:78f5243bb6b1060aed6213d5107744c19f9571ec76d54c99cc15938eb69e0e86 \ + --hash=sha256:79cac3390bfa9836bb795be377395f28410811c9066bc4eefd8015258a7578c6 \ + --hash=sha256:7ae6eabf519bc7871ce117fb18bf14e0e343eeb96c377667e3e5dd12095e0288 \ + --hash=sha256:7e39e845c4d764208e7b8f6a21c541ade741e2c41afabdfa1caa28687a3c98cf \ + --hash=sha256:8161d9fbc7e9fe2326de89cd0abb9f3599bccc1287db0aba285cb68d204ce929 \ + --hash=sha256:8bec2ac5da793c2685ce5319ca9bcf4eee683b8a1679051f8e6ec04c4f2fd7dc \ + --hash=sha256:959244a17184515f8c52dcb65fb662808767c0bd233c1d8a166e7cf74c9ea985 \ + --hash=sha256:9b148068e881faa26d878ff63e79650e208e95cf1c22bd3f77c3ca7b1d9821a3 \ + --hash=sha256:aa6f302a3a0b5f240ee201297fff0bbfe2fa0d415a94aeb257d8b461032389bd \ + --hash=sha256:ace9048de91293e467b44bce0f0381345078389814ff6e18dbac8fdbf896360e \ + --hash=sha256:ad7525bf0241e5502168ae9c643a2f6c219fa0a283001cee4cf23a9b7da75879 \ + --hash=sha256:b01a840ecc25dce235ae4c1b6a0daefb2a203dba0e6e980637ee9c2f6ee0df57 \ + --hash=sha256:b076e625396e787448d27a411aefff867db2bffac8ed04e8f7056b07024eed5a \ + --hash=sha256:b172f8e030e8ef247b3104902cc671e20df80163b60a203653150d2fc204d1ad \ + --hash=sha256:b1f097878d74fe51e1ddd1be62d8e3682748875b461232cf4b52ddc6e6db0bba \ + --hash=sha256:b95574d06aa9d2bd6e5cc35a5bbe35696342c96760b69dc4287dbd5abd4ad51d \ + --hash=sha256:bda1c5f347550c359f841d6614fb8ca42ae5cb0b74d39f8a1e204815ebe25750 \ + --hash=sha256:cec6b9ce3bd2b7853d4a4563801292bfee40b030c05a3d29555fd2a8ee9bd68c \ + --hash=sha256:d1a987778b9c71da2fc8948e6f2656da6ef68f59298b7e9786849634c35d2c3c \ + --hash=sha256:d74c08e9aaef995f8c4ef6d202dbd219c318450fe2a76da624f2ebb9c8ec5d9f \ + --hash=sha256:e18aafdfb3e9ec0d261c942d35bd7c28d031c5855dadb491d2723ba54f4c3015 \ + --hash=sha256:e216c5c45f89ef8971373fd1c5d8d1164b81f7f5f06bbf23c37e7908d19e8558 \ + --hash=sha256:e695df2c58ce526eeab11a2e915448d3eb76f75dffe338ea613c1201b33bab2f \ + --hash=sha256:e7575ab65ca8399c8c4f9a7d61bbd2d204c8b8e447aab9d355682205c9dd948d \ + --hash=sha256:e995b3b76ccedc27fe4f477b349b7d64597e53a43fc2961db9d3fbace085d69d \ + --hash=sha256:ea31689f05043d520113e0552f039603c4dd71fa4c287b64cb3606140c66f425 \ + --hash=sha256:eb5507795caabd9b2ae3f1adc95f67b1104971c22c624bb354232d65c4fc90b3 \ + --hash=sha256:eb8668cfbc279a536c633137deeb9435d2962caec279c3f8cf8b91fff6ff8953 \ + --hash=sha256:ecea0c38c9079570163d663c0433a9af4094a60aafdca491c6a3d248c7432827 \ + --hash=sha256:f25d8b92a4e31ff1bd873654ec367ae811b3a943583e05432ea29264782dc32c \ + --hash=sha256:f60a297c3987c6c02ffb29effc70eadcbb412fe76947d394a1091a3615948e2f \ + --hash=sha256:f973643ef532d4f9be71dd88cf7588936685fdb576d93a79fe9f65bc337d9d73 +pytest==7.4.2 \ + --hash=sha256:1d881c6124e08ff0a1bb75ba3ec0bfd8b5354a01c194ddd5a0a870a48d99b002 \ + --hash=sha256:a766259cfab564a2ad52cb1aae1b881a75c3eb7e34ca3779697c23ed47c47069 +pytest-cov==4.1.0 \ + --hash=sha256:3904b13dfbfec47f003b8e77fd5b589cd11904a21ddf1ab38a64f204d6a10ef6 \ + --hash=sha256:6ba70b9e97e69fcc3fb45bfeab2d0a138fb65c4d0d6a41ef33983ad114be8c3a + +# Transitive pytest dependencies (pytest's Windows-only colorama dependency is +# pinned in the top-level requirements.txt) +exceptiongroup==1.2.2 ; python_version < "3.11" \ + --hash=sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b \ + --hash=sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc +iniconfig==2.3.0 \ + --hash=sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730 \ + --hash=sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12 +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c +pluggy==1.6.0 \ + --hash=sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3 \ + --hash=sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746 +tomli==2.2.1 ; python_version < "3.11" \ + --hash=sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6 \ + --hash=sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd \ + --hash=sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c \ + --hash=sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b \ + --hash=sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8 \ + --hash=sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6 \ + --hash=sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77 \ + --hash=sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff \ + --hash=sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea \ + --hash=sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192 \ + --hash=sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249 \ + --hash=sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee \ + --hash=sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4 \ + --hash=sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98 \ + --hash=sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8 \ + --hash=sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4 \ + --hash=sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281 \ + --hash=sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744 \ + --hash=sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69 \ + --hash=sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13 \ + --hash=sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140 \ + --hash=sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e \ + --hash=sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e \ + --hash=sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc \ + --hash=sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff \ + --hash=sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec \ + --hash=sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2 \ + --hash=sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222 \ + --hash=sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106 \ + --hash=sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272 \ + --hash=sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a \ + --hash=sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7 From 8c89739d388f1a88c03a48d51a386cb046318090 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 22 Aug 2026 07:46:30 -0500 Subject: [PATCH 02/12] Revert requirements-raspi.txt to dev; drop hash-lock and pin-alignment changes --- requirements-raspi.txt | 56 +++--------------------------------------- 1 file changed, 4 insertions(+), 52 deletions(-) diff --git a/requirements-raspi.txt b/requirements-raspi.txt index eb5a9f2b9..d86e93d22 100644 --- a/requirements-raspi.txt +++ b/requirements-raspi.txt @@ -1,53 +1,5 @@ -# Raspberry Pi hardware dependencies (installed on the Pi itself; see -# docs/raspberry_pi_os_build_instructions.md). Entries are pinned and -# hash-locked: pip refuses any artifact that does not match a hash below. -# Hashes cover every published file of each release (wheels + sdist). -# -# To update a pin: change the version, then refresh its hashes from -# https://pypi.org/pypi///json (or pip download + pip hash). -# -# NOTE: piwheels rebuilds wheels, so its artifacts will not match these PyPI -# hashes. pip skips the mismatched piwheels candidates and builds from the -# PyPI sdists instead (the from-source build the install doc already assumes); -# very old pips may error on the mismatch instead of skipping — upgrade pip. -picamera==1.13 \ - --hash=sha256:890815aa01e4d855a6a95dd3ad0953b872a6b954982106407df0c5a31a163e50 +picamera==1.13 # numpy = transitive picamera dependency -numpy==1.25.0 \ - --hash=sha256:0ac6edfb35d2a99aaf102b509c8e9319c499ebd4978df4971b94419a116d0790 \ - --hash=sha256:26815c6c8498dc49d81faa76d61078c4f9f0859ce7817919021b9eba72b425e3 \ - --hash=sha256:4aedd08f15d3045a4e9c648f1e04daca2ab1044256959f1f95aafeeb3d794c16 \ - --hash=sha256:4c69fe5f05eea336b7a740e114dec995e2f927003c30702d896892403df6dbf0 \ - --hash=sha256:5177310ac2e63d6603f659fadc1e7bab33dd5a8db4e0596df34214eeab0fee3b \ - --hash=sha256:5aa48bebfb41f93043a796128854b84407d4df730d3fb6e5dc36402f5cd594c0 \ - --hash=sha256:5b1b90860bf7d8a8c313b372d4f27343a54f415b20fb69dd601b7efe1029c91e \ - --hash=sha256:6c284907e37f5e04d2412950960894b143a648dea3f79290757eb878b91acbd1 \ - --hash=sha256:6d183b5c58513f74225c376643234c369468e02947b47942eacbb23c1671f25d \ - --hash=sha256:7412125b4f18aeddca2ecd7219ea2d2708f697943e6f624be41aa5f8a9852cc4 \ - --hash=sha256:7cd981ccc0afe49b9883f14761bb57c964df71124dcd155b0cba2b591f0d64b9 \ - --hash=sha256:85cdae87d8c136fd4da4dad1e48064d700f63e923d5af6c8c782ac0df8044542 \ - --hash=sha256:8aa130c3042052d656751df5e81f6d61edff3e289b5994edcf77f54118a8d9f4 \ - --hash=sha256:95367ccd88c07af21b379be1725b5322362bb83679d36691f124a16357390153 \ - --hash=sha256:9c7211d7920b97aeca7b3773a6783492b5b93baba39e7c36054f6e749fc7490c \ - --hash=sha256:9e3f2b96e3b63c978bc29daaa3700c028fe3f049ea3031b58aa33fe2a5809d24 \ - --hash=sha256:b76aa836a952059d70a2788a2d98cb2a533ccd46222558b6970348939e55fc24 \ - --hash=sha256:b792164e539d99d93e4e5e09ae10f8cbe5466de7d759fc155e075237e0c274e4 \ - --hash=sha256:c0dc071017bc00abb7d7201bac06fa80333c6314477b3d10b52b58fa6a6e38f6 \ - --hash=sha256:cc3fda2b36482891db1060f00f881c77f9423eead4c3579629940a3e12095fe8 \ - --hash=sha256:d6b267f349a99d3908b56645eebf340cb58f01bd1e773b4eea1a905b3f0e4208 \ - --hash=sha256:d76a84998c51b8b68b40448ddd02bd1081bb33abcdc28beee6cd284fe11036c6 \ - --hash=sha256:e559c6afbca484072a98a51b6fa466aae785cfe89b69e8b856c3191bc8872a82 \ - --hash=sha256:ecc68f11404930e9c7ecfc937aa423e1e50158317bf67ca91736a9864eae0232 \ - --hash=sha256:f1accae9a28dc3cda46a91de86acf69de0d1b5f4edd44a9b0c3ceb8036dfff19 -RPi.GPIO==0.7.1 \ - --hash=sha256:15311d3b063b71dee738cd26570effc9985a952454d162937c34e08c0fc99902 \ - --hash=sha256:26b2ade4bb353bbe5417a64e40b45cdf00a82f27c2d320c0dd46c59751959d77 \ - --hash=sha256:29226823da8b5ccb9001d795a944f2e00924eeae583490f0bc7317581172c624 \ - --hash=sha256:57b6c044ef5375a78c8dda27cdfadf329e76aa6943cd6cffbbbd345a9adf9ca5 \ - --hash=sha256:77afb817b81331ce3049a4b8f94a85e41b7c404d8e56b61ac0f1eb75c3120868 \ - --hash=sha256:96ea7e5bf6bf592828487bfa7d3d1d0e432d5d1682e9e33b4dab398914628fcd \ - --hash=sha256:b86b66dc02faa5461b443a1e1f0c1d209d64ab5229696f32fb3b0215e0600c8c \ - --hash=sha256:cd61c4b03c37b62bba4a5acfea9862749c33c618e0295e7e90aa4713fb373b70 -spidev==3.6 \ - --hash=sha256:14dbc37594a4aaef85403ab617985d3c3ef464d62bc9b769ef552db53701115b \ - --hash=sha256:280abc00a1ef7780ef62c3f294f52a2527b6c47d8c269fea98664970bcaf6da5 +numpy==1.25.2 +RPi.GPIO==0.7.0 +spidev==3.5 \ No newline at end of file From 364add8c4d755a313ad15c64b983d56182ef07a2 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 22 Aug 2026 07:51:07 -0500 Subject: [PATCH 03/12] pip install CI bugfix --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 93c4b240c..4ebb94396 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -54,7 +54,7 @@ jobs: sudo apt-get install libzbar0 python -m pip install --upgrade pip # hash-locked requirements files - pip install -r requirements.txt -r tests/requirements.txt l10n/requirements-l10n.txt + pip install -r requirements.txt -r tests/requirements.txt -r l10n/requirements-l10n.txt # An editable install can't satisfy hash-checking, so `-e .` can't # share an invocation with the hash-locked files above. pip install -e . From c3e8077f15cf4f0a93c0107d839aeba4d30bc28b Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 22 Aug 2026 07:53:43 -0500 Subject: [PATCH 04/12] Correct raspi deps to clear diffs --- requirements-raspi.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-raspi.txt b/requirements-raspi.txt index d86e93d22..52ad1818a 100644 --- a/requirements-raspi.txt +++ b/requirements-raspi.txt @@ -1,5 +1,5 @@ picamera==1.13 # numpy = transitive picamera dependency -numpy==1.25.2 -RPi.GPIO==0.7.0 -spidev==3.5 \ No newline at end of file +numpy==1.25.0 +RPi.GPIO==0.7.1 +spidev==3.6 \ No newline at end of file From cbfeac1d8f231053a18fb90be0542ec30693e52e Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 22 Aug 2026 07:58:10 -0500 Subject: [PATCH 05/12] raspi requirements line break to fully revert changes --- requirements-raspi.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-raspi.txt b/requirements-raspi.txt index 52ad1818a..b767562ba 100644 --- a/requirements-raspi.txt +++ b/requirements-raspi.txt @@ -2,4 +2,4 @@ picamera==1.13 # numpy = transitive picamera dependency numpy==1.25.0 RPi.GPIO==0.7.1 -spidev==3.6 \ No newline at end of file +spidev==3.6 From 6268589db006f2f30fa784481259a2fd82f1e77c Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Fri, 21 Aug 2026 15:29:37 -0500 Subject: [PATCH 06/12] Reject psbts that falsely claim this seed's ownership Every derivation entry naming the signing seed's fingerprint is now verified during parse() by re-deriving the key from the seed itself. A claim that does not hold up aborts the parse before any transaction detail is shown: a false claim on an output is classified as an attack (fake change) and routed to a dire warning, while a false claim on an input is reported as inconsistent data with a plain warning. A psbt whose inputs this seed cannot sign at all is turned away to seed selection. The per-scope verification results are recorded in verified_input_derivation_paths / verified_output_derivation_paths, the ownership record later stages consume. --- src/seedsigner/models/psbt_parser.py | 245 +++++++++++++- src/seedsigner/views/psbt_views.py | 139 +++++++- tests/psbt_testing_util.py | 54 ++- tests/screenshot_generator/generator.py | 3 + tests/test_flows_psbt.py | 90 +++++ tests/test_psbt_parser.py | 423 +++++++++++++++++++++++- 6 files changed, 928 insertions(+), 26 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 8a4a436a7..1b087e2ae 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -19,6 +19,62 @@ class OPCODES: +class PSBTVerificationError(Exception): + """ + Base for the checks that reject a psbt outright while it is being parsed. + + A psbt that trips one of these is never shown to the user. The view layer should catch + these exceptions and route to a warning (the severity of which and the allowed next + steps are determined by the specific subclass error encountered). + """ + pass + + +class PSBTOutputOwnershipClaimError(PSBTVerificationError): + """ + An output scope claims this seed's fingerprint on a key the seed does not derive. + + This is not a psbt that merely fails to be ours. A fingerprint is + coordinator-supplied metadata, so this is a psbt asserting that a key belongs to this + seed when it does not. On an output that assertion is how a fake change output is + dressed up as the user's own, so it should be treated as an attack. + """ + pass + + +class PSBTInputOwnershipClaimError(PSBTVerificationError): + """ + An input scope claims this seed's fingerprint on a key the seed does not derive. + + The same false claim as PSBTOutputOwnershipClaimError, but on an input the threat + picture inverts. A forged input claim has no path to losing funds: it cannot produce a + signature (embit re-derives the real key and refuses on a mismatch), and it cannot + alter the amounts, the fee, or how outputs are classified. The likely causes are + instead a psbt assembled for a different wallet, a corrupted entry, or a collaborative + spend that happens to include a key whose 4-byte fingerprint collides with ours (1 in + 2^32 chance). + + The psbt still fails, deliberately, following embit's lead: sign_with raises on this + same condition and abandons the entire signing pass, so tolerating the entry here + would only defer the failure to a worse spot. Changing this behavior, if desired, + should happen in embit first. Until then the trade-off is accepted: a + collaborative-spend counterparty could grief such a transaction into unsignability. + """ + pass + + +class PSBTSeedCannotSignError(PSBTVerificationError): + """ + The selected seed holds no key that could sign any input. + + This is a mismatch rather than an attack: the usual cause is the user picking the + wrong seed. It is raised so the flow can say so up front, instead of walking the user + through reviewing and approving a transaction that would then produce no signatures. + """ + pass + + + class PSBTParser(): """ Reads a psbt on behalf of one seed and works out everything the signing flow shows the @@ -26,7 +82,8 @@ class PSBTParser(): cosigners for multisig), the amount coming in, what is being spent, what comes back as change, the fee, where the spend is going, and any OP_RETURN payload. - Constructing it with a seed parses immediately. + Constructing it with a seed parses immediately; see parse() for what that establishes + in what order and which psbts it turns away. The parse fully processes the psbt, validates what it can, then stores the organized results in the instance attributes (spend_amount, fee_amount, destination_addresses, @@ -76,6 +133,12 @@ def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET self.destination_amounts = [] self.op_return_data: bytes = None + # Indexed alongside psbt.inputs / psbt.outputs. Each entry is the derivation path + # the seed genuinely owns in each scope or None where it owns nothing. Determined + # in _scan_seed_ownership. + self.verified_input_derivation_paths: List[List[int] | None] = [] + self.verified_output_derivation_paths: List[List[int] | None] = [] + self.root = None if self.seed is not None: @@ -111,6 +174,37 @@ def _set_root(self): def parse(self): """ + Establishes, in order: + + 1. _fill_missing_fingerprints: backfills all-zero fingerprints, but only for + scopes the seed provably derives. + + 2. _scan_seed_ownership: records, per scope, the derivation path the seed + genuinely owns or None. Raises an Input/Output OwnershipClaimError if any + scope claims this seed's fingerprint on a key the seed does not control. + + 3. _reject_if_seed_cannot_sign: raises PSBTSeedCannotSignError if none of the + inputs can be signed by the seed. A mismatch rather than an attack, caught + here so the flow can say so before showing a transaction. + + 4. _parse_inputs: every input must resolve to the same policy otherwise a + RuntimeError is raised. TODO: make this a PSBTVerificationError subclass so + the view can deliberately catch this scenario and route accordingly. + + A policy is one of: + - single-sig: the script type alone. Says nothing about keys. + - multisig, cosigners resolved: script type, m-of-n, and the cosigner + xpubs that every key in the script was traced back to. + - multisig, cosigners unresolved: script type and m-of-n only. + _get_policy doesn't propagate cosigner errors, so two such policies match + without anything having tied them to the same keys. TODO: don't let a + policy with no cosigner information pass as a match. + + 5. _parse_outputs: works out which outputs come back to this seed. For + single-sig this proves the output script derives from the seed at the + claimed path. TODO: reject outputs at a path the user's wallet would never + scan. + Parsing traverses a derivation path down to an individual address one level at a time, over and over, and where that traversal begins depends on the wallet. @@ -118,7 +212,7 @@ def parse(self): the PSBT claims is ours. Multisig instead traverses just the last two levels down from each cosigner's - account xpub — once per cosigner, on every INPUT and on every OUTPUT carrying the + account xpub, once per cosigner, on every INPUT and on every OUTPUT carrying the multisig script. Deriving each level costs a hash and an elliptic curve operation, and these @@ -145,6 +239,11 @@ def parse(self): # Try to fix missing fingerprints before parsing self._fill_missing_fingerprints(child_key_derivation_cache) + # Work out what this seed actually owns before anything below reads the psbt's + # claims about it. + self._scan_seed_ownership(child_key_derivation_cache) + self._reject_if_seed_cannot_sign() + rt = self._parse_inputs(child_key_derivation_cache) if rt == False: return False @@ -232,9 +331,6 @@ def _parse_outputs(self, child_key_derivation_cache: dict): elif self.policy["type"] == "p2wpkh" and my_pubkey is not None: sc = script.p2wpkh(my_pubkey) - if sc.data == vout[i].script_pubkey.data: - is_change = True - elif "p2tr" in self.policy["type"]: my_pubkey = None # should have one or zero derivations for single-key addresses @@ -245,9 +341,6 @@ def _parse_outputs(self, child_key_derivation_cache: dict): my_pubkey = PSBTParser._derive_with_cache(self.root, der, child_key_derivation_cache) sc = script.p2tr(my_pubkey) - if sc.data == vout[i].script_pubkey.data: - is_change = True - if sc.data == vout[i].script_pubkey.data: is_change = True @@ -353,6 +446,12 @@ def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | N cosigners = PSBTParser._get_cosigners(pubkeys, scope.bip32_derivations, xpubs, child_key_derivation_cache) policy.update({"m": m, "n": n, "cosigners": cosigners}) except: + # TODO: stop swallowing everything here. This also catches bugs in the + # cosigner check itself, and cannot tell those apart from the psbt + # simply not supplying xpubs to check against, which is valid and must + # not be rejected outright. The fallback policy carries no cosigner + # information at all, and two of those compare equal on script type + # and m-of-n alone. Fix pending with the multisig verification work. policy.update({"m": m, "n": n}) return policy @@ -398,7 +497,7 @@ def _derive_with_cache(parent_key: bip32.HDKey, derivation_path: List[int], chil cache, so a later derivation running through that level picks it up instead of deriving it a second time. - Entries are keyed on (id(parent_key), derivation_path_so_far) — the path traversed + Entries are keyed on (id(parent_key), derivation_path_so_far), the path traversed down from that parent to reach this point. id() is the Python built-in for an object's identity; the parent belongs in the key because a multisig parse runs these same derivations below each cosigner's xpub in turn. @@ -531,6 +630,134 @@ def check_fingerprint_match(public_key: PublicKey, derivation_path_obj: Derivati return False + @staticmethod + def seed_owns_pubkey(root: bip32.HDKey, claimed_derivation_path: List[int], public_key: PublicKey, child_key_derivation_cache: dict | None, is_taproot: bool = False) -> bool: + """ + Returns True if the signing seed (root) really does derive public_key at + claimed_derivation_path. + + This is the canonical ownership check. The fingerprint a psbt or a descriptor + carries alongside a key is metadata that whoever wrote the file chose, so it can + say anything. Ownership is established here and only here, by deriving the key + again from the seed and comparing the actual key material. + """ + derived_public_key = PSBTParser._derive_with_cache(root, claimed_derivation_path, child_key_derivation_cache).get_public_key() + + if is_taproot: + # Taproot keys are x-only + return derived_public_key.xonly() == public_key.xonly() + + # For ecdsa the parity byte IS part of the identity, so compare the full key. + # This is deliberately stricter than embit, whose sign_with compares x-only even + # for ecdsa. embit would sign a psbt whose entry names the parity-flipped twin of + # our real key. The flipped key is still one this seed does NOT derive, and the + # signature embit produces under it is one no standard finalizer can use. So this + # extra strictness only rejects transactions that could never actually complete. + return derived_public_key == public_key + + + @staticmethod + def _get_seed_derivation_path(scope: InputScope | OutputScope, root: bip32.HDKey, child_key_derivation_cache: dict) -> List[int] | None: + """ + Scans the derivation path(s) in the provided input or output scope to determine + which, if any, are provably derived from the signing seed (for multisig a path is + provided per key; if the seed is part of the multisig, one of the n paths will + match). Returns the verified derivation path (as a list of ints) or None. + + Every key in the scope that claims this seed's fingerprint is re-derived and + checked. A claim that does not hold up raises + PSBT[Output|Input]OwnershipClaimError. This includes fingerprint collisions (two + different keys with the same 4-byte fingerprint): + * On the output side, a collision is considered an attack. + * On the input side it is merely disallowed because it is unsignable by embit. + + One edge case: + * A multisig could use this seed in more than one cosigner slot, each + at its own derivation path. The scope then carries several entries that all + verify against this seed; we return the first but still check the rest. + + The path itself is still whatever the psbt supplied: it can be any length or + shape, since any path that derives from the seed will pass. Whether the path is + one the user's wallet would ever look at is a separate question, answered + elsewhere. + """ + seed_fingerprint = root.my_fingerprint + verified_derivation_path = None + + def _check_claim(public_key: PublicKey, derivation_path_obj: DerivationPath, is_taproot: bool): + nonlocal verified_derivation_path + + if derivation_path_obj.fingerprint != seed_fingerprint: + # Claims to belong to some other key. Nothing to prove or disprove here. + return + + if not PSBTParser.seed_owns_pubkey(root, derivation_path_obj.derivation, public_key, child_key_derivation_cache, is_taproot=is_taproot): + error_class = (PSBTInputOwnershipClaimError if isinstance(scope, InputScope) else PSBTOutputOwnershipClaimError) + raise error_class(f"Key at {bip32.path_to_str(derivation_path_obj.derivation)} claims this seed's fingerprint but does not derive from it") + + # Store only the first verified path + if verified_derivation_path is None: + verified_derivation_path = derivation_path_obj.derivation + + # Note that both loops check EVERY claim + for public_key, derivation_path_obj in scope.bip32_derivations.items(): + _check_claim(public_key, derivation_path_obj, is_taproot=False) + + for public_key, (leaf_hashes, derivation_path_obj) in scope.taproot_bip32_derivations.items(): + # TODO: Support keys in taptree leaves + _check_claim(public_key, derivation_path_obj, is_taproot=True) + + return verified_derivation_path + + + def _scan_seed_ownership(self, child_key_derivation_cache: dict): + """ + Verifies the input/output derivation paths the signing seed provably owns and + stores them in verified_[input|output]_derivation_paths. These member vars are the + definitive ownership record from this point forward in the psbt parse. + + The coordinator-supplied fingerprints cannot be trusted as-is. We must derive and + verify the ownership of each one that claims to belong to this seed. + + Outputs are scanned before inputs; a false claim on an output (e.g. fake-change + forgery) is likely an attack whereas a false claim on an input is merely + unsignable. + + Raises PSBT[Output|Input]OwnershipClaimError on the first false claim detected. + """ + self.verified_output_derivation_paths = [ + PSBTParser._get_seed_derivation_path(out, self.root, child_key_derivation_cache) + for out in self.psbt.outputs + ] + + self.verified_input_derivation_paths = [ + PSBTParser._get_seed_derivation_path(inp, self.root, child_key_derivation_cache) + for inp in self.psbt.inputs + ] + + + def _reject_if_seed_cannot_sign(self): + """ + Rejects the psbt when none of its inputs rely on a key derived by this seed. + + We detect it here, early, so the psbt can be rejected without sending the user + through the full verification flow only for signing to fail at the end anyway. + + (embit's sign_with is marginally more permissive: it also signs an input whose + script names the master key directly, with no derivation. That runs against how HD + wallets are built. The master key is a derivation root, not a spending key, so no + standard wallet produces such a psbt. We deliberately ignore this case.) + """ + # An input names a key at a derivation path and _scan_seed_ownership proved the + # seed derives it (single-sig: one such key; multisig: one per cosigner, ours + # among them). One verified input path is enough for the psbt to be signable. + if any(path is not None for path in self.verified_input_derivation_paths): + return + + # There's nothing for this seed to sign + raise PSBTSeedCannotSignError() + + def verify_multisig_output(self, descriptor: Descriptor, change_num: int) -> bool: change_data = self.get_change_data(change_num) i = change_data["output_index"] diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 2b214b00e..926e54d7d 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -1,9 +1,10 @@ from gettext import gettext as _ -from seedsigner.models.psbt_parser import PSBTParser +from seedsigner.models.psbt_parser import (PSBTInputOwnershipClaimError, + PSBTOutputOwnershipClaimError, PSBTParser, PSBTSeedCannotSignError) from seedsigner.models.settings import SettingsConstants -from seedsigner.gui.components import FontAwesomeIconConstants, SeedSignerIconConstants -from seedsigner.gui.screens.screen import (RET_CODE__BACK_BUTTON, ButtonListScreen, ButtonOption, WarningScreen, DireWarningScreen, QRDisplayScreen) +from seedsigner.gui.components import FontAwesomeIconConstants, GUIConstants, SeedSignerIconConstants +from seedsigner.gui.screens.screen import (RET_CODE__BACK_BUTTON, ButtonListScreen, ButtonOption, LargeIconStatusScreen, WarningScreen, DireWarningScreen, QRDisplayScreen) from seedsigner.views.view import BackStackView, MainMenuView, NotYetImplementedView, View, Destination @@ -101,9 +102,27 @@ def __init__(self): seed=self.controller.psbt_seed, network=self.settings.get_value(SettingsConstants.SETTING__NETWORK) ) - except Exception as e: + + except PSBTInputOwnershipClaimError: + # Set clear_history to disable returning via BACK button + self.set_redirect(Destination(PSBTInputOwnershipClaimFailedView, clear_history=True)) + return + + except PSBTOutputOwnershipClaimError: + # Set clear_history to disable returning via BACK button + self.set_redirect(Destination(PSBTOutputOwnershipClaimFailedView, clear_history=True)) + return + + except PSBTSeedCannotSignError: + # Not a suspicious psbt, just the wrong seed for it. Send the user back to + # pick another rather than clearing the flow. + self.controller.psbt_parser = None + self.controller.psbt_seed = None + self.set_redirect(Destination(PSBTSeedCannotSignView)) + return + + finally: self.loading_screen.stop() - raise e def run(self): @@ -129,10 +148,6 @@ def run(self): else: num_self_transfer_outputs += 1 - # Everything is set. Stop the loading screen - if self.loading_screen: - self.loading_screen.stop() - # Run the overview screen selected_menu_num = self.run_screen( PSBTOverviewScreen, @@ -449,14 +464,111 @@ def run(self): from seedsigner.views.seed_views import LoadMultisigWalletDescriptorView self.controller.resume_main_flow = Controller.FLOW__PSBT return Destination(LoadMultisigWalletDescriptorView) - + + + +class PSBTSeedCannotSignView(View): + """ + Reached when parsing found this seed can't sign any of the psbt's inputs (see + PSBTSeedCannotSignError). Routes back to seed selection so the user can pick another. + """ + SELECT_DIFFERENT_SEED = ButtonOption("Select a different seed") + + def run(self): + # This is an informational mismatch, not a warning, so it uses the neutral info + # icon and color rather than WarningScreen's alarming yellow edges. + # TODO: give this its own InfoScreen (LargeIconStatusScreen with the INFO icon and + # color baked in) rather than customizing the base screen at each call site. + self.run_screen( + LargeIconStatusScreen, + title=_("Seed Can't Sign"), + status_icon_name=SeedSignerIconConstants.INFO, + status_color=GUIConstants.INFO_COLOR, + text=_("None of the inputs in this psbt are controlled by this seed."), + button_data=[self.SELECT_DIFFERENT_SEED], + show_back_button=False, + ) + + # Set clear_history to disable returning via BACK button. + return Destination(PSBTSelectSeedView, clear_history=True) + + + +class PSBTOutputOwnershipClaimFailedView(View): + """ + Reached when a false ownership claim on an output rejects the psbt (see + PSBTOutputOwnershipClaimError). Shows a dire warning and discards the psbt to the main + menu. Claims on inputs route to PSBTInputOwnershipClaimFailedView instead. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + DireWarningScreen, + title=_("Suspicious Transaction"), + status_headline=_("Likely an Attack!"), + text=_("The transaction's change/self-transfer outputs are not going back to your wallet."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all ephemeral + # data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + +class PSBTInputOwnershipClaimFailedView(View): + """ + Reached when a false ownership claim on an input rejects the psbt (see + PSBTInputOwnershipClaimError). Shows a plain (not dire) warning and discards the psbt + to the main menu. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + WarningScreen, + title=_("Transaction Problem"), + status_headline=None, + text=_("This transaction incorrectly claims that its input(s) belong to this seed."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all ephemeral + # data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + class PSBTAddressVerificationFailedView(View): - def __init__(self, is_change: bool = True, is_multisig: bool = False): + """ + Reached when a change or self-transfer output fails address verification. Shows a dire + warning and discards the psbt to the main menu. + """ + # Names for why verification failed, fixed here so that the checks which will reach + # this view settle on them once rather than one at a time. + # TODO: These aren't being used yet. Pass `reason` from each call site and then adjust + # the user-facing message in run() accordingly. + + # The output derives from the seed, but at a path the wallet would never scan + REASON__UNEXPECTED_DERIVATION_PATH = "unexpected_derivation_path" + + # The multisig descriptor could not be verified, or does not contain this seed + REASON__DESCRIPTOR_MISMATCH = "descriptor_mismatch" + + # The claimed derivation path is malformed or too short to be a wallet path + REASON__MALFORMED_DERIVATION_PATH = "malformed_derivation_path" + + + def __init__(self, is_change: bool = True, is_multisig: bool = False, reason: str = None): super().__init__() self.is_change = is_change self.is_multisig = is_multisig + self.reason = reason def run(self): @@ -476,8 +588,9 @@ def run(self): show_back_button=False, ) - # We're done with this PSBT. Route back to MainMenuView which always - # clears all ephemeral data (except in-memory seeds). + # We're done with this PSBT. Route back to MainMenuView, which clears all ephemeral + # data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. return Destination(MainMenuView, clear_history=True) diff --git a/tests/psbt_testing_util.py b/tests/psbt_testing_util.py index f47d49ecc..00ea93d28 100644 --- a/tests/psbt_testing_util.py +++ b/tests/psbt_testing_util.py @@ -1,8 +1,10 @@ from binascii import a2b_base64, unhexlify from io import BytesIO +from embit import bip32 +from embit.ec import PublicKey from embit.networks import NETWORKS -from embit.psbt import PSBT, OutputScope +from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope from seedsigner.models.seed import Seed @@ -60,6 +62,13 @@ class PSBTTestData: MULTISIG_LEGACY_P2SH_CHANGE = "0100695221031ce6ddb7a26336264b132c1b45c3e631e8502bc155226d46fc38d73d57f9e4ff21031d9e6e094413dc3a508518f729af23a35b3943ca79bafbc55afab631595e5ccf2103c3a6cb2786d860aa1ccff81fae79c1a973bc8a79938af6ff3c75fc4f54333d7353ae220203c3a6cb2786d860aa1ccff81fae79c1a973bc8a79938af6ff3c75fc4f54333d73100fb882ff2d00008001000000000000002202031d9e6e094413dc3a508518f729af23a35b3943ca79bafbc55afab631595e5ccf1003cd0a2b2d00008001000000000000002202031ce6ddb7a26336264b132c1b45c3e631e8502bc155226d46fc38d73d57f9e4ff100f8890442d0000800100000000000000010308000ff20500000000010417a91402e6f3cb4a98d88fbedf0e43869ce9e1a01e8d9f8700" MULTISIG_LEGACY_P2SH_SELF_TRANSFER = "01006952210283a03b8fa4cce258e536514416f448cf20aca8ef42492413c149a329029adb4e210346b5d12c00554bce6920e60d647893db6555e0844b8583747bc0ca1ecaba3e1c2103bfc0f7151411ace2d2eef986efca7873dabdc0f6f1bbea7bd3c863be1f2e00de53ae220203bfc0f7151411ace2d2eef986efca7873dabdc0f6f1bbea7bd3c863be1f2e00de100fb882ff2d000080000000000100000022020346b5d12c00554bce6920e60d647893db6555e0844b8583747bc0ca1ecaba3e1c1003cd0a2b2d000080000000000100000022020283a03b8fa4cce258e536514416f448cf20aca8ef42492413c149a329029adb4e100f8890442d000080000000000100000001030890d0030000000000010417a914505efc1adc72f354e827da94b49dec46d80717068700" + # Fingerprint-collision pair: two unrelated seeds whose master fingerprints collide, + # for tests of the honest-collision case (a genuine foreign key that names our + # fingerprint without any forgery involved). Any two seeds collide with probability 1 + # in 2^32. + collision_seed_a = Seed("trend local ecology client torch face wink soup right craft nerve bread".split()) + collision_seed_b = Seed("oval stadium chimney tone deny catch idea gasp absorb short vibrant tribe".split()) + # External receive outputs recipient_seed = Seed("shove album flame dad equal cook spike cheap hollow exit great forest".split()) recipient_multisig_key_2 = Seed("grow curve arrive reflect alarm water black funny comfort match attend tired".split()) @@ -126,3 +135,46 @@ def create_output(output_hex: str, value: int = None) -> OutputScope: if value is not None: output.value = value return output + + +def root_for_seed(seed: Seed) -> bip32.HDKey: + """ + A seed's master key, built the way PSBTParser builds it. + + The network only picks the version bytes, and neither the fingerprint nor any of the + key material compared below depends on those, so the fixtures' regtest is used + throughout. + """ + return bip32.HDKey.from_seed(seed.seed_bytes, version=NETWORKS["regtest"]["xprv"]) + + +def foreign_public_key(derivation_path: str = "m/84h/1h/0h/0/0", seed: Seed = None) -> PublicKey: + """ + A genuine public key belonging to some seed other than the signing seed, for building + scopes that name a key the signing seed does not control. + """ + if seed is None: + seed = PSBTTestData.recipient_seed + return root_for_seed(seed).derive(derivation_path).get_public_key() + + +def claim_seed_owns_key(scope: InputScope | OutputScope, claimed_derivation_path: str, public_key: PublicKey, seed: Seed = None, is_taproot: bool = False): + """ + Writes a derivation into the scope claiming that seed owns public_key at + claimed_derivation_path. + + Building one of these needs no key material from the seed, because nothing in a psbt + ties a fingerprint to the key written beside it. The fingerprint is all it takes, and + that is published in every psbt the seed has ever been sent. So pass a public_key the + seed does not own and the result is a psbt asserting ownership that does not exist. + """ + if seed is None: + seed = PSBTTestData.seed + + derivation_path = DerivationPath( + root_for_seed(seed).my_fingerprint, bip32.parse_path(claimed_derivation_path)) + + if is_taproot: + scope.taproot_bip32_derivations[public_key] = ([], derivation_path) + else: + scope.bip32_derivations[public_key] = derivation_path diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index 879c4a525..328bf7002 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -453,6 +453,9 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False, is_multisig=False), screenshot_name="PSBTAddressVerificationFailedView_singlesig_selftransfer"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True, is_multisig=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False, is_multisig=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"), + ScreenshotConfig(psbt_views.PSBTOutputOwnershipClaimFailedView), + ScreenshotConfig(psbt_views.PSBTInputOwnershipClaimFailedView), + ScreenshotConfig(psbt_views.PSBTSeedCannotSignView), ScreenshotConfig(psbt_views.PSBTFinalizeView, mock_context_manager=mock_multisig_psbt_loaded), #ScreenshotConfig(PSBTSignedQRDisplayViewScreenshotConfig), ScreenshotConfig(psbt_views.PSBTSigningErrorView, mock_context_manager=mock_multisig_psbt_loaded), diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 1e3067de9..18ba21ef1 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -1,8 +1,15 @@ +from binascii import a2b_base64 + +from embit.psbt import PSBT + from base import FlowTest, FlowStep +from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output, + foreign_public_key) from seedsigner.controller import Controller from seedsigner.views.view import MainMenuView from seedsigner.views import scan_views, seed_views, psbt_views +from seedsigner.models.seed import Seed from seedsigner.models.settings import SettingsConstants @@ -181,3 +188,86 @@ def load_seed_into_decoder(view: scan_views.ScanView): FlowStep(psbt_views.PSBTSignedQRDisplayView), FlowStep(MainMenuView) ]) + + + +class TestPSBTOwnershipClaimRouting(FlowTest): + """ + A psbt carrying an ownership claim that does not hold up is rejected while it is being + parsed, before the user is shown anything about the transaction. These cover the + routing that turns that rejection into a warning screen instead of a crash. + """ + + def _load_psbt_for_signing(self, psbt: PSBT, seed: Seed = None): + """ + Stage the psbt in the Controller and load the signing seed into storage, as if + both had just been scanned. Each test's sequence then starts at seed selection; + the parse itself runs when PSBTOverviewView is instantiated. + """ + self.settings.set_value(SettingsConstants.SETTING__NETWORK, SettingsConstants.REGTEST) + self.controller.psbt = psbt + self.controller.storage.set_pending_seed(seed if seed is not None else PSBTTestData.seed) + self.controller.storage.finalize_pending_seed() + + + def _psbt_with_change(self): + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT)) + psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE, 10_000)) + return psbt + + + def test_forged_output_claim_terminates_signing_flow(self): + """ + A forged ownership claim on an output is framed as a potential attack, so it + routes to a warning that aborts the signing flow. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.outputs[0], "m/84h/1h/0h/1/0", foreign_public_key()) + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTOutputOwnershipClaimFailedView, button_data_selection=psbt_views.PSBTOutputOwnershipClaimFailedView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_forged_input_claim_terminates_signing_flow(self): + """ + A false claim on an input is framed as inconsistent data rather than as an attack, + but also routes to its own information screen that aborts the signing flow. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key()) + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTInputOwnershipClaimFailedView, button_data_selection=psbt_views.PSBTInputOwnershipClaimFailedView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_wrong_seed_routes_back_to_seed_selection_flow(self): + """ + The wrong seed for a psbt redirects before any transaction detail is rendered and + routes back to seed selection with the signing seed cleared so another can be + picked. + """ + self._load_psbt_for_signing(self._psbt_with_change(), seed=PSBTTestData.recipient_seed) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTSeedCannotSignView, button_data_selection=psbt_views.PSBTSeedCannotSignView.SELECT_DIFFERENT_SEED), + FlowStep(psbt_views.PSBTSelectSeedView), + ]) + + assert self.controller.psbt_seed is None + assert self.controller.psbt_parser is None + + # The psbt itself is kept: the user is choosing a different seed for it, not + # starting over + assert self.controller.psbt is not None diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 76d1e70fb..8e464be24 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -4,16 +4,19 @@ from binascii import a2b_base64 from copy import deepcopy from unittest.mock import patch -from embit import bip32 +from embit import bip32, script +from embit.ec import PublicKey from embit.networks import NETWORKS from embit.psbt import PSBT, DerivationPath from embit.descriptor import Descriptor -from seedsigner.models.psbt_parser import PSBTParser +from seedsigner.models.psbt_parser import (PSBTInputOwnershipClaimError, + PSBTOutputOwnershipClaimError, PSBTParser, PSBTSeedCannotSignError) from seedsigner.models.seed import Seed from seedsigner.models.settings_definition import SettingsConstants -from psbt_testing_util import PSBTTestData, create_output +from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output, + foreign_public_key, root_for_seed) @@ -772,3 +775,417 @@ def build_psbt(case: tuple) -> PSBT: assert max(capped_sizes) == cap + +class TestPSBTParserSeedOwnership: + """ + The ownership scan: what the signing seed provably owns in a psbt, and the rejection + of any psbt whose ownership claims do not hold up. + """ + seed = PSBTTestData.seed + + def _root(self) -> bip32.HDKey: + return root_for_seed(self.seed) + + + def _psbt_with_change(self, input_base64: str = None, change_hex: str = None) -> PSBT: + """ + A base psbt plus its own change output. But no external recipient output is added, + so all paths are owned by the seed. + """ + if input_base64 is None: + input_base64 = PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT + if change_hex is None: + change_hex = PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE + + psbt = PSBT.parse(a2b_base64(input_base64)) + psbt.outputs.append(create_output(change_hex, 10_000)) + return psbt + + + def _parse(self, psbt: PSBT) -> PSBTParser: + return PSBTParser(psbt, self.seed, network=SettingsConstants.REGTEST) + + + def test__seed_owns_pubkey__accepts_the_seeds_own_key(self): + """ + seed_owns_pubkey should confirm the simple base case that a pubkey directly + derived from the seed is owned by the seed. + """ + root = self._root() + derivation_path = bip32.parse_path("m/84h/1h/0h/0/0") + public_key = root.derive(derivation_path).get_public_key() + + assert PSBTParser.seed_owns_pubkey(root, derivation_path, public_key, child_key_derivation_cache=None) is True + + + def test__seed_owns_pubkey__rejects_a_key_the_seed_does_not_control(self): + """ + seed_owns_pubkey should reject a pubkey that the seed does not control. + """ + root = self._root() + derivation_path = bip32.parse_path("m/84h/1h/0h/0/0") + + assert PSBTParser.seed_owns_pubkey(root, derivation_path, foreign_public_key(), child_key_derivation_cache=None) is False + + + def test__seed_owns_pubkey__rejects_the_seeds_own_key_at_the_wrong_path(self): + """ + The path is as much a part of the claim as the key is. The seed owns this key, but + not at the path the claim names so it is still a false claim. + """ + root = self._root() + public_key = root.derive(bip32.parse_path("m/84h/1h/0h/0/0")).get_public_key() + + assert PSBTParser.seed_owns_pubkey(root, bip32.parse_path("m/84h/1h/0h/0/1"), public_key, child_key_derivation_cache=None) is False + + + def test__seed_owns_pubkey__compares_taproot_keys_without_parity(self): + """ + Taproot keys are x-only, so a key the seed genuinely owns routinely differs from + the derived key by the parity byte alone. Comparing the full key would read that + as a stranger's key and reject the seed's own output. + """ + root = self._root() + + # Address index 1 is the first whose derived key has odd parity, which is the + # case where a full comparison and an x-only comparison disagree. + derivation_path = bip32.parse_path("m/86h/1h/0h/0/1") + public_key = root.derive(derivation_path).get_public_key() + + # Sanity check: the key's first byte is its parity, 0x02 for even, 0x03 for odd + assert public_key.sec()[0] == 0x03 + + # The psbt carries the key x-only, so reconstruct what it would hold: the same x + # coordinate, with the EVEN-parity prefix. + as_written_in_psbt = PublicKey.parse(b"\x02" + public_key.xonly()) + + # Taproot is x-only so it ignores the now-even parity byte + assert PSBTParser.seed_owns_pubkey(root, derivation_path, as_written_in_psbt, child_key_derivation_cache=None, is_taproot=True) is True + + # Non-taproot compares the full key so it rejects the key with the wrong parity byte + assert PSBTParser.seed_owns_pubkey(root, derivation_path, as_written_in_psbt, child_key_derivation_cache=None) is False + + + def test__parse__populates_verified_derivation_paths(self): + """ + The scan writes one verified_*_derivation_paths entry per input and per output + (regardless of ownership; not-owned paths are recorded as None) in the psbt's own + order. + """ + # The psbt fixture has one input and one output, both of which are owned by the + # seed. + psbt = self._psbt_with_change() + psbt_parser = self._parse(psbt) + + assert len(psbt_parser.verified_input_derivation_paths) == len(psbt.inputs) + assert len(psbt_parser.verified_output_derivation_paths) == len(psbt.outputs) + + # Every recorded path is one the seed really does derive the scope's key at + for scopes, verified_derivation_paths in [ + (psbt.inputs, psbt_parser.verified_input_derivation_paths), + (psbt.outputs, psbt_parser.verified_output_derivation_paths), + ]: + for scope, verified_derivation_path in zip(scopes, verified_derivation_paths): + assert verified_derivation_path is not None + public_key = list(scope.bip32_derivations.keys())[0] + assert PSBTParser.seed_owns_pubkey(psbt_parser.root, verified_derivation_path, public_key, child_key_derivation_cache=None) is True + + + def test__parse__verified_derivation_paths_none_for_not_owned_output(self): + """ + An output paying someone else is not a failure; the seed simply owns nothing + there so the matching verified_output_derivation_paths should be None. + """ + psbt = self._psbt_with_change() + + # Add an external recipient at index 0 + psbt.outputs.insert(0, create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 10_000)) + + psbt_parser = self._parse(psbt) + + assert psbt_parser.verified_output_derivation_paths[0] is None + assert psbt_parser.verified_output_derivation_paths[1] is not None + + + def test__parse__verified_derivation_paths_none_for_not_owned_input(self): + """ + A collaborative spend also includes an input belonging to another party, in two + shapes: a payjoin counterparty's input arrives finalized with no derivation info + at all (BIP-78 requires the sender to verify no keypaths appear anywhere), while + a coordinator managing every party's wallet writes each party's genuine + derivation entry. Neither is a failure; the seed simply owns nothing there. + """ + psbt = self._psbt_with_change() + + # The other party's input: their utxo, carrying no derivation info + foreign_input = deepcopy(psbt.inputs[0]) + foreign_input.bip32_derivations.clear() + foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key()) + psbt.inputs.append(foreign_input) + + # The payjoin shape + psbt_parser = self._parse(psbt) + assert psbt_parser.verified_input_derivation_paths[0] is not None + assert psbt_parser.verified_input_derivation_paths[1] is None + + # The coordinated shape: the derivation entry is truthful, naming the other + # party's fingerprint and a key that party really controls. + claim_seed_owns_key(foreign_input, "m/84h/1h/0h/0/0", foreign_public_key(), seed=PSBTTestData.recipient_seed) + psbt_parser = self._parse(psbt) + assert psbt_parser.verified_input_derivation_paths[0] is not None + assert psbt_parser.verified_input_derivation_paths[1] is None + + + def test__parse__rejects_a_forged_claim_on_an_input(self): + """ + `parse` should raise PSBTInputOwnershipClaimError when a psbt carries a false + claim that the seed owns an input that it does not actually control. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key()) + + with pytest.raises(PSBTInputOwnershipClaimError): + self._parse(psbt) + + + def test__parse__rejects_a_forged_claim_on_an_output(self): + """ + `parse` should raise PSBTOutputOwnershipClaimError when a psbt carries a false + claim that the seed owns an output that it does not actually control. This is + the fake-change attack scenario that is more severe than a forged input claim. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.outputs[0], "m/84h/1h/0h/1/0", foreign_public_key()) + + # The output-scope error specifically: the dire, attack-framed rejection + with pytest.raises(PSBTOutputOwnershipClaimError): + self._parse(psbt) + + + def test__parse__forged_output_claim_outranks_forged_input_claim(self): + """ + The scan stops at the first false claim, so scan order decides which error the + psbt is reported with. A false output claim is the fake-change forgery and must + be the one reported even when the same psbt also carries a false input claim -- + otherwise an attacker could plant a throwaway input claim just to be routed to + the milder input-scope warning. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key()) + claim_seed_owns_key(psbt.outputs[0], "m/84h/1h/0h/1/0", foreign_public_key()) + + # The output error is the more severe issue + with pytest.raises(PSBTOutputOwnershipClaimError): + self._parse(psbt) + + + def test__parse__rejects_a_forged_taproot_claim(self): + """ + A false taproot claim is rejected the same way as an ecdsa one: the input-scope + error on an input, the output-scope (attack) error on an output. Taproot claims + live in their own taproot_bip32_derivations dict, so the scan's coverage of that + dict is pinned on both scope types. + """ + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE) + claim_seed_owns_key(psbt.inputs[0], "m/86h/1h/0h/0/0", foreign_public_key(), is_taproot=True) + + with pytest.raises(PSBTInputOwnershipClaimError): + self._parse(psbt) + + # The same forgery on a taproot output gets the attack classification + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE) + claim_seed_owns_key(psbt.outputs[0], "m/86h/1h/0h/1/0", foreign_public_key(), is_taproot=True) + + with pytest.raises(PSBTOutputOwnershipClaimError): + self._parse(psbt) + + + def test__parse__rejects_a_forged_claim_on_a_multisig_scope(self): + """ + Multisig scopes legitimately carry one derivation entry per cosigner, but a + forged claim naming this seed's fingerprint is rejected there exactly as in + single-sig: the input-scope error on an input, the attack-classified error on + an output. + """ + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + claim_seed_owns_key(psbt.inputs[0], "m/48h/1h/0h/2h/0/9", foreign_public_key()) + + with pytest.raises(PSBTInputOwnershipClaimError): + self._parse(psbt) + + # The same forgery on the multisig change output gets the attack classification + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + claim_seed_owns_key(psbt.outputs[0], "m/48h/1h/0h/2h/1/9", foreign_public_key()) + + with pytest.raises(PSBTOutputOwnershipClaimError): + self._parse(psbt) + + + def test__parse__rejects_a_forged_claim_behind_a_genuine_one(self): + """ + A scope can hold more than one key. Finding the one the seed owns is not a reason + to stop looking. + + No honest coordinator writes extra derivation entries on a single-sig scope; this + shape arrives only from buggy or adversarial software. The scan copes with it + because the same scan serves multisig, where multi-entry scopes are the norm. + """ + psbt = self._psbt_with_change() + + # The scope's own genuine derivation stays exactly where it is... + assert len(psbt.inputs[0].bip32_derivations) == 1 + + # ...but add a false claim to the bip32_derivations dict + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/9", foreign_public_key()) + assert len(psbt.inputs[0].bip32_derivations) == 2 + assert list(psbt.inputs[0].bip32_derivations.keys())[-1] == foreign_public_key() + + with pytest.raises(PSBTInputOwnershipClaimError): + self._parse(psbt) + + + def test__parse__accepts_a_key_belonging_to_someone_else(self): + """ + Only a claim on THIS seed's fingerprint is ever checked. A key openly belonging to + another wallet says nothing about this seed and must not reject the psbt. + + No honest coordinator writes extra derivation entries on a single-sig scope; this + shape arrives only from buggy or adversarial software. The scan copes with it + because the same scan serves multisig, where multi-entry scopes are the norm. + """ + psbt = self._psbt_with_change() + other_seed = PSBTTestData.recipient_seed + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key(), seed=other_seed) + + # Confirm the fixture really does carry someone else's fingerprint + claimed_fingerprint = psbt.inputs[0].bip32_derivations[foreign_public_key()].fingerprint + assert claimed_fingerprint == root_for_seed(other_seed).my_fingerprint + assert claimed_fingerprint != self._root().my_fingerprint + + psbt_parser = self._parse(psbt) + + # The seed still owns its own key in that input, via the scope's genuine + # derivation. + assert psbt_parser.verified_input_derivation_paths[0] is not None + + + def test_genuine_fingerprint_collision_is_rejected_like_a_forgery(self): + """ + 4-byte fingerprints collide. The fixture pair were brute-force generated so that + they share a master fingerprint with no forgery involved, so a foreign party's + honest derivation entry can name our fingerprint on a key we do not control. + + The parser cannot distinguish that from a forged claim -- they are byte-for-byte + the same situation -- and so it deliberately fails the psbt as an input-scope + inconsistency. + """ + foreign_root = root_for_seed(PSBTTestData.collision_seed_b) + + # The collision is real: same fingerprint, different key material + signing_root = root_for_seed(PSBTTestData.collision_seed_a) + assert foreign_root.my_fingerprint == signing_root.my_fingerprint + assert foreign_root.get_public_key() != signing_root.get_public_key() + + # The foreign party's own genuine entry on their own input: their true + # fingerprint beside their true key, no forgery anywhere + psbt = self._psbt_with_change() + foreign_derivation_path = bip32.parse_path("m/84h/1h/0h/0/0") + colliding_public_key = foreign_root.derive(foreign_derivation_path).get_public_key() + psbt.inputs[0].bip32_derivations[colliding_public_key] = DerivationPath(foreign_root.my_fingerprint, foreign_derivation_path) + + with pytest.raises(PSBTInputOwnershipClaimError): + PSBTParser(psbt, PSBTTestData.collision_seed_a, network=SettingsConstants.REGTEST) + + + def test_ownership_scan_derives_through_the_cache(self): + """ + Ownership verification does its own deriving and the later parse phases do theirs, + but all of it flows through one shared cache: across the whole parse, each unique + path level is derived exactly once, no matter how many scopes claim it or how many + phases revisit it. + + Note that even the initial pass benefits from the cache by skipping shared + levels that have already been derived. + """ + psbt = self._psbt_with_change() + + # Boost to 10 inputs from the same wallet, all sharing the one derivation path + for _ in range(9): + psbt.inputs.append(deepcopy(psbt.inputs[0])) + + # How deep does the derivation path go? + num_levels = len(list(psbt.inputs[0].bip32_derivations.values())[0].derivation) + + # Count every level actually derived over the course of the parse + num_derivations = 0 + uncounted_child = bip32.HDKey.child + def counting_child(self, index, hardened=False): + nonlocal num_derivations + num_derivations += 1 + return uncounted_child(self, index, hardened) + + with patch.object(bip32.HDKey, "child", counting_child): + psbt_parser = self._parse(psbt) + + # Sanity check: the scan really did run over all ten inputs and the change output + assert len(psbt_parser.verified_input_derivation_paths) == 10 + assert all(path is not None for path in psbt_parser.verified_input_derivation_paths) + assert psbt_parser.verified_output_derivation_paths[0] is not None + + # The inputs were cloned so they all use the same path with num_levels depth. The + # change output differs only in its last two levels. Verify that each of these + # levels was derived exactly once. + assert num_derivations == num_levels + 2 + + + def test__parse__rejects_a_seed_that_owns_no_input(self): + """ + The wrong seed for a psbt can produce no signature at all, so parsing raises + PSBTSeedCannotSignError rather than letting the flow discover it after the user + has approved. + + And under the same wrong-seed conditions, embit will produce no signature anyway. + """ + psbt = self._psbt_with_change() + + # Intentionally use the wrong seed + with pytest.raises(PSBTSeedCannotSignError): + PSBTParser(psbt, PSBTTestData.recipient_seed, network=SettingsConstants.REGTEST) + + # Try to sign with the wrong seed anyway + root = root_for_seed(PSBTTestData.recipient_seed) + assert psbt.sign_with(root) == 0 + + + def test__parse__accepts_a_cosigner_seed_on_a_multisig(self): + """ + Each cosigner holding a key on the device signs the same psbt in turn, so a seed + that owns an input must pass whether or not it is the first one used. + """ + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + + psbt_parser = PSBTParser(psbt, PSBTTestData.seed, network=SettingsConstants.REGTEST) + assert any(path is not None for path in psbt_parser.verified_input_derivation_paths) + + psbt_parser = PSBTParser(psbt, PSBTTestData.multisig_key_2, network=SettingsConstants.REGTEST) + assert any(path is not None for path in psbt_parser.verified_input_derivation_paths) + + psbt_parser = PSBTParser(psbt, PSBTTestData.multisig_key_3, network=SettingsConstants.REGTEST) + assert any(path is not None for path in psbt_parser.verified_input_derivation_paths) + + + def test_a_psbt_with_no_utxos_is_rejected_rather_than_crashing(self): + """ + A psbt with no inputs is malformed and cannot be signed. `parse` should raise + PSBTSeedCannotSignError. Note that diagnosing the malformation is not this check's + job. + """ + psbt = self._psbt_with_change() + for psbt_input in psbt.inputs: + psbt_input.witness_utxo = None + psbt_input.non_witness_utxo = None + psbt_input._utxo = None + psbt_input.bip32_derivations.clear() + + with pytest.raises(PSBTSeedCannotSignError): + self._parse(psbt) From 5e53bdbd9f742f209c1944137c64b010660aeb08 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 22 Aug 2026 08:21:36 -0500 Subject: [PATCH 07/12] Remote "psbt" in user-facing message Co-authored-by: Chaitanya-Keyal --- src/seedsigner/views/psbt_views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 926e54d7d..ed3e127f3 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -484,7 +484,7 @@ def run(self): title=_("Seed Can't Sign"), status_icon_name=SeedSignerIconConstants.INFO, status_color=GUIConstants.INFO_COLOR, - text=_("None of the inputs in this psbt are controlled by this seed."), + text=_("None of the inputs in this transaction are controlled by this seed."), button_data=[self.SELECT_DIFFERENT_SEED], show_back_button=False, ) From c9fda649942c0bddcbff6a2b75a4cc9137ee82bc Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sun, 23 Aug 2026 08:32:52 -0500 Subject: [PATCH 08/12] Compare taproot keys x-only in missing-fingerprint fallbacks A psbt carries taproot keys as bare x coordinates and embit rebuilds them assuming even parity, so the full-key comparisons in the two zero-fingerprint fallbacks failed whenever the seed's real key derives with odd parity. A taproot psbt from an xpub-only coordinator was then wrongly rejected with PSBTSeedCannotSignError about half the time. Both fallbacks now delegate to seed_owns_pubkey, which already compares taproot keys by their x-only representation. The regression test re-keys the taproot fixture to an odd-parity path; the existing fixture at m/86h/1h/0h/0/0 happens to derive even and passed by luck. --- src/seedsigner/models/psbt_parser.py | 51 +++++++++++++------------- tests/test_psbt_parser.py | 53 ++++++++++++++++++++++++++-- 2 files changed, 77 insertions(+), 27 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 1b087e2ae..e27f9fad6 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -598,33 +598,32 @@ def has_matching_input_fingerprint(psbt: PSBT, seed: Seed, network: str = Settin """ seed_fingerprint = seed.get_fingerprint(network) - def check_fingerprint_match(public_key: PublicKey, derivation_path_obj: DerivationPath): + def check_fingerprint_match(public_key: PublicKey, derivation_path_obj: DerivationPath, is_taproot: bool): """Check fingerprint match with missing fingerprint fallback""" # If exact fingerprint match if hexlify(derivation_path_obj.fingerprint).decode() == seed_fingerprint: return True - + # Missing fingerprint fallback if derivation_path_obj.fingerprint == b"\x00\x00\x00\x00": root = bip32.HDKey.from_seed(seed.seed_bytes, version=NETWORKS[SettingsConstants.map_network_to_embit(network)]["xprv"]) try: - derived_key = root.derive(derivation_path_obj.derivation) - return derived_key.key.sec() == public_key.sec() # Public keys match + return PSBTParser.seed_owns_pubkey(root, derivation_path_obj.derivation, public_key, child_key_derivation_cache=None, is_taproot=is_taproot) except Exception as e: logger.debug("Fingerprint fallback derive failed: %s", e, exc_info=True) return False - + # Check all derivations in all inputs for input in psbt.inputs: # Check regular BIP32 derivations for public_key, derivation_path_obj in input.bip32_derivations.items(): - if check_fingerprint_match(public_key, derivation_path_obj): + if check_fingerprint_match(public_key, derivation_path_obj, is_taproot=False): return True - + # Check Taproot derivations for public_key, (leaf_hashes, derivation_path_obj) in input.taproot_bip32_derivations.items(): - if check_fingerprint_match(public_key, derivation_path_obj): + if check_fingerprint_match(public_key, derivation_path_obj, is_taproot=True): return True return False @@ -644,7 +643,12 @@ def seed_owns_pubkey(root: bip32.HDKey, claimed_derivation_path: List[int], publ derived_public_key = PSBTParser._derive_with_cache(root, claimed_derivation_path, child_key_derivation_cache).get_public_key() if is_taproot: - # Taproot keys are x-only + # A psbt carries a taproot key as its bare 32-byte x coordinate, but embit + # rebuilds a full key from it by just assuming even parity. The key derived + # from the seed carries its real parity, so a naive full-key comparison + # succeeds only when that real parity happens to be even, wrongly rejecting + # roughly half of the keys this seed genuinely owns. Only the x coordinate is + # real information: compare x-only. return derived_public_key.xonly() == public_key.xonly() # For ecdsa the parity byte IS part of the identity, so compare the full key. @@ -785,32 +789,29 @@ def _fill_scope(scope: InputScope | OutputScope): """Helper function to fill missing fingerprints in a scope (input/output)""" # Helper function to check and fix fingerprint - def _get_updated_fingerprint(public_key: PublicKey, derivation_path_obj: DerivationPath) -> DerivationPath | None: + def _get_updated_fingerprint(public_key: PublicKey, derivation_path_obj: DerivationPath, is_taproot: bool) -> DerivationPath | None: if derivation_path_obj.fingerprint != b"\x00\x00\x00\x00": return None - - # Derive the public key from the currently loaded seed using the derivation - # contained in the PSBT. If the derived public key exactly matches - # the PSBT-provided public key, we can be confident that this input/output - # is owned by the signing seed. In that case we populate the missing (zero) - # fingerprint with the signing seed's master fingerprint so downstream - # parsing/signing can treat it as owned by this seed. - derived_key = PSBTParser._derive_with_cache( - self.root, derivation_path_obj.derivation, child_key_derivation_cache) - if derived_key.key.sec() == public_key.sec(): + + # If the signing seed really derives the psbt-provided public key at the + # claimed derivation path, this input/output is owned by the signing seed. + # In that case we populate the missing (zero) fingerprint with the signing + # seed's master fingerprint so downstream parsing/signing can treat it as + # owned by this seed. + if PSBTParser.seed_owns_pubkey(self.root, derivation_path_obj.derivation, public_key, child_key_derivation_cache, is_taproot=is_taproot): return DerivationPath(self.root.my_fingerprint, derivation_path_obj.derivation) return None - + # Handle regular BIP32 derivations for public_key, derivation_path_obj in list(scope.bip32_derivations.items()): - new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj) + new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj, is_taproot=False) if new_derivation: scope.bip32_derivations[public_key] = new_derivation logger.debug(f"Filled missing fingerprint for pubkey {public_key.sec().hex()} derivation {bip32.path_to_str(derivation_path_obj.derivation)}") - - # Handle Taproot derivations + + # Handle Taproot derivations for public_key, (leaf_hashes, derivation_path_obj) in list(scope.taproot_bip32_derivations.items()): - new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj) + new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj, is_taproot=True) if new_derivation: scope.taproot_bip32_derivations[public_key] = (leaf_hashes, new_derivation) logger.debug(f"Filled missing fingerprint for pubkey {public_key.sec().hex()} derivation {bip32.path_to_str(derivation_path_obj.derivation)}") diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 8e464be24..0b770120a 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -212,15 +212,64 @@ def test_missing_fingerprint_handling(self): from binascii import hexlify fingerprint_hex = hexlify(derivation.fingerprint).decode() - # Check if this public key derives from the current seed + # Check if this public key derives from the current seed. A psbt + # carries a taproot key as its bare 32-byte x coordinate, and embit + # rebuilds a full key from it by just assuming even parity. The real + # derived key can be odd-parity, so a full-key compare would wrongly + # report a mismatch. Only the x coordinate is real data: compare + # x-only. derived_key = parser.root.derive(derivation.derivation) - if derived_key.key.sec() == pub.sec(): + if derived_key.xonly() == pub.xonly(): # This pubkey derives from current seed, should have current seed's fingerprint assert fingerprint_hex == seed_fingerprint, f"Expected {seed_fingerprint}, got {fingerprint_hex} for taproot pubkey that derives from current seed" else: # This pubkey doesn't derive from current seed, should remain 00000000 assert fingerprint_hex == "00000000" + # All of the above only proves the even-parity case. A psbt carries taproot keys + # as bare 32-byte x coordinates and embit rebuilds full keys from them by assuming + # even parity; that assumption happens to hold for the fixture's key at + # m/86h/1h/0h/0/0. Re-key the taproot input to a path whose key really derives + # with odd parity to prove the ownership fallback compares x-only rather than + # trusting embit's artificial parity. + root = root_for_seed(PSBTTestData.seed) + odd_parity_derivation_path = "m/86h/1h/0h/0/1" + odd_parity_public_key = root.derive(odd_parity_derivation_path).get_public_key() + assert odd_parity_public_key.sec()[0] == 0x03 # odd parity + + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT)) + taproot_input = psbt.inputs[0] + + # Present the key the way embit's psbt parsing yields it: rebuilt from just the + # x coordinate, carrying the assumed even parity (wrong for this key) + x_only_public_key = PublicKey.from_xonly(odd_parity_public_key.xonly()) + taproot_input.taproot_bip32_derivations.clear() + taproot_input.taproot_bip32_derivations[x_only_public_key] = ([], DerivationPath( + fingerprint=b"\x00\x00\x00\x00", + derivation=bip32.parse_path(odd_parity_derivation_path) + )) + taproot_input.taproot_internal_key = x_only_public_key + taproot_input.witness_utxo.script_pubkey = script.p2tr(x_only_public_key) + + # The zeroed-fingerprint fallback check must recognize this input as the seed's, + # even though embit's internal parity byte for the pubkey is wrong. Taproot + # pubkeys must be compared by their x-only representation. + assert PSBTParser.has_matching_input_fingerprint(psbt, PSBTTestData.seed, SettingsConstants.REGTEST) + + # Comparing x-only looks less strict than the full-key comparison used for + # non-taproot keys, but nothing is actually given up: a psbt never carries a + # parity byte for a taproot key, so the x coordinate is all the key material + # there is to compare. A completely wrong seed will still fail to match. + wrong_seed = Seed(["bacon"] * 24) + assert not PSBTParser.has_matching_input_fingerprint(psbt, wrong_seed, SettingsConstants.REGTEST) + + # Parsing should successfully fill the fingerprint and verify that the input + # belongs to the seed. + parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) + (_, filled_derivation) = parser.psbt.inputs[0].taproot_bip32_derivations[x_only_public_key] + assert filled_derivation.fingerprint == parser.root.my_fingerprint + assert parser.verified_input_derivation_paths == [bip32.parse_path(odd_parity_derivation_path)] + def test_trim_and_sig_count(self): """ From ee1a9f553f9d3cec8cab7d66e75e1de55ef501af Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Mon, 24 Aug 2026 09:06:37 -0500 Subject: [PATCH 09/12] Rename ownership scan to _verify_claimed_derivation_paths The old name read as if the scan established ownership of the scope itself. What it proves is narrower: the seed derives the key a scope names at the claimed path, nothing about that key's role in the scope's script. The new name states exactly that, and the docstrings around it are tightened to match. Also note on _reject_if_seed_cannot_sign that we deliberately skip verifying that a key appears in its input's script: a key absent from the script cannot spend the input, so nothing of this seed's is at risk. --- src/seedsigner/models/psbt_parser.py | 35 +++++++++++++++++----------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index e27f9fad6..aa3237a37 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -135,7 +135,7 @@ def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET # Indexed alongside psbt.inputs / psbt.outputs. Each entry is the derivation path # the seed genuinely owns in each scope or None where it owns nothing. Determined - # in _scan_seed_ownership. + # in _verify_claimed_derivation_paths. self.verified_input_derivation_paths: List[List[int] | None] = [] self.verified_output_derivation_paths: List[List[int] | None] = [] @@ -179,9 +179,9 @@ def parse(self): 1. _fill_missing_fingerprints: backfills all-zero fingerprints, but only for scopes the seed provably derives. - 2. _scan_seed_ownership: records, per scope, the derivation path the seed - genuinely owns or None. Raises an Input/Output OwnershipClaimError if any - scope claims this seed's fingerprint on a key the seed does not control. + 2. _verify_claimed_derivation_paths: each input and output scope that claims to + be controlled by the seed is verified. Raises an Input/Output + OwnershipClaimError if a claimed scope fails verification. 3. _reject_if_seed_cannot_sign: raises PSBTSeedCannotSignError if none of the inputs can be signed by the seed. A mismatch rather than an attack, caught @@ -205,6 +205,7 @@ def parse(self): claimed path. TODO: reject outputs at a path the user's wallet would never scan. + Optimization via child_key_derivation_cache: Parsing traverses a derivation path down to an individual address one level at a time, over and over, and where that traversal begins depends on the wallet. @@ -241,7 +242,7 @@ def parse(self): # Work out what this seed actually owns before anything below reads the psbt's # claims about it. - self._scan_seed_ownership(child_key_derivation_cache) + self._verify_claimed_derivation_paths(child_key_derivation_cache) self._reject_if_seed_cannot_sign() rt = self._parse_inputs(child_key_derivation_cache) @@ -714,16 +715,16 @@ def _check_claim(public_key: PublicKey, derivation_path_obj: DerivationPath, is_ return verified_derivation_path - def _scan_seed_ownership(self, child_key_derivation_cache: dict): + def _verify_claimed_derivation_paths(self, child_key_derivation_cache: dict): """ - Verifies the input/output derivation paths the signing seed provably owns and - stores them in verified_[input|output]_derivation_paths. These member vars are the - definitive ownership record from this point forward in the psbt parse. + Verifies every claimed derivation path that names this seed's fingerprint. The + result, stored in verified_[input|output]_derivation_paths, is either the verified + derivation path or None (the seed was not named) for each input/output scope. The coordinator-supplied fingerprints cannot be trusted as-is. We must derive and verify the ownership of each one that claims to belong to this seed. - Outputs are scanned before inputs; a false claim on an output (e.g. fake-change + Outputs are verified before inputs; a false claim on an output (e.g. fake-change forgery) is likely an attack whereas a false claim on an input is merely unsignable. @@ -750,11 +751,17 @@ def _reject_if_seed_cannot_sign(self): (embit's sign_with is marginally more permissive: it also signs an input whose script names the master key directly, with no derivation. That runs against how HD wallets are built. The master key is a derivation root, not a spending key, so no - standard wallet produces such a psbt. We deliberately ignore this case.) + standard wallet produces such a psbt. We deliberately ignore this case. + + Similarly, it's not worth the effort to verify that each key is included in its + input's script. A psbt that excludes a key in that way would be nonsensical but + harmless: the excluded key cannot spend the input, so nothing of this seed's is + at risk.) """ - # An input names a key at a derivation path and _scan_seed_ownership proved the - # seed derives it (single-sig: one such key; multisig: one per cosigner, ours - # among them). One verified input path is enough for the psbt to be signable. + # An input names a key at a derivation path and _verify_claimed_derivation_paths + # proved the seed derives it (single-sig: one such key; multisig: one per + # cosigner, ours among them). One verified input path is enough for the psbt to + # be signable. if any(path is not None for path in self.verified_input_derivation_paths): return From 6d58d0ac2f53f194cd228b3a57fbcd2fa0d688d5 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Tue, 25 Aug 2026 11:35:46 -0500 Subject: [PATCH 10/12] Drop the unused failure-view reason namespace The three REASON__ constants and the `reason` parameter were fixed up front to settle a shared vocabulary before any consumer existed, on the reasoning that one contributor owned all three prospective call sites. No caller ever passed a reason. Routing each rejection by exception type sends it to its own view, which leaves PSBTAddressVerificationFailedView with two outcomes already decided by is_multisig. Later work should introduce whatever distinctions its own copy needs rather than inherit three unused constants. --- src/seedsigner/views/psbt_views.py | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index ed3e127f3..77dbb3565 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -549,26 +549,10 @@ class PSBTAddressVerificationFailedView(View): Reached when a change or self-transfer output fails address verification. Shows a dire warning and discards the psbt to the main menu. """ - # Names for why verification failed, fixed here so that the checks which will reach - # this view settle on them once rather than one at a time. - # TODO: These aren't being used yet. Pass `reason` from each call site and then adjust - # the user-facing message in run() accordingly. - - # The output derives from the seed, but at a path the wallet would never scan - REASON__UNEXPECTED_DERIVATION_PATH = "unexpected_derivation_path" - - # The multisig descriptor could not be verified, or does not contain this seed - REASON__DESCRIPTOR_MISMATCH = "descriptor_mismatch" - - # The claimed derivation path is malformed or too short to be a wallet path - REASON__MALFORMED_DERIVATION_PATH = "malformed_derivation_path" - - - def __init__(self, is_change: bool = True, is_multisig: bool = False, reason: str = None): + def __init__(self, is_change: bool = True, is_multisig: bool = False): super().__init__() self.is_change = is_change self.is_multisig = is_multisig - self.reason = reason def run(self): From 8ca88578e2812bedf9507252a10f23e3f8249584 Mon Sep 17 00:00:00 2001 From: 3rd Iteration Date: Thu, 3 Sep 2026 23:22:36 -0400 Subject: [PATCH 11/12] tests: fix the card signing fixtures against real hardware Five defects the first run against a live reader and JavaCard exposed. Stale card sessions. Running a flow hands the card to init_satochip, which builds its own connector and parks it on the controller, leaving this class's cached connector holding a session the card has already torn down. The next direct call failed with a bare 0x6985 that named nothing about the real problem. Every direct card access now starts a new session. Installing over a live applet. install_capfile skips load and install for a package already on the card, so each run inherited the previous run's PIN and key state: provisioning short-circuited on setup_done, the expected PIN never matched, and the seed import was refused. _reinstall_blank deletes first, so "install, initialise, test, uninstall" means what it says. Seeding on the provisioning session. Immediately after card_setup, the applet accepts a LOAD KEY on the same session and reports success, but the key does not stick -- the next status read still says no key and every later derivation fails with 0x6985. The import now runs on a session of its own, and the status is re-read afterwards so a silent no-op fails loudly at the fixture instead of surfacing as seven unrelated test failures. The Keycard button was never offered. PSBTSelectSeedView gates each card on its own support setting; Satochip's defaults to enabled and Keycard's does not, so the menu had no Keycard button to select. Ordering collided across classes. pytest-order sorts globally rather than per class, and each applet lifecycle is a class-scoped fixture, so sharing an order number with another class meant one class installing and deleting its applet out from under another's tests. Each class now carries its own order number, keeping its install/initialise/test/uninstall contiguous while tests within it run in definition order. The number lives on the concrete subclass because a marker applied in the shared base binds at definition time and every subclass would inherit the same value. Satochip passes 9/9 in a full-module run against the card, PSBT signing and the pre-existing import-seed flows alike. Co-Authored-By: Claude Opus 5 --- tests/test_flows_smartcard_hardware.py | 127 ++++++++++++++++++++----- 1 file changed, 101 insertions(+), 26 deletions(-) diff --git a/tests/test_flows_smartcard_hardware.py b/tests/test_flows_smartcard_hardware.py index 12c6b65da..62458daeb 100644 --- a/tests/test_flows_smartcard_hardware.py +++ b/tests/test_flows_smartcard_hardware.py @@ -162,6 +162,23 @@ def cap_dir(): return p +def _reinstall_blank(gp, cap_path, aid, **install_kwargs): + """ + Install `cap_path` onto a card carrying no prior copy of `aid`. + + install_capfile skips the load and install steps for a package that is + already on the card, so installing over a previous run leaves that run's PIN + and key material in place. Provisioning then short-circuits on setup_done, + the PIN this run expects never matches, and the seed import is refused with a + bare status word. Deleting first makes "install, initialise, test, uninstall" + mean what it says. + """ + _reauth_and_delete(gp, aid) + result = gp.install_capfile(str(cap_path), **install_kwargs) + gp.close() + return result + + def _reauth_and_delete(gp, aid): """Re-establish GP auth and remove an applet package, tolerating absence.""" try: @@ -665,6 +682,19 @@ class CardPSBTSigningFlowTest(SmartcardFlowTest): CARD_BUTTON = None # a PSBTSelectSeedView ButtonOption; set by the subclass + # Each concrete subclass carries its own `pytestmark = pytest.mark.order(N)`. + # + # pytest-order sorts globally rather than per class, and each applet lifecycle + # is a class-scoped fixture, so two classes sharing an order number interleave + # and one installs or deletes its applet out from under the other's tests. A + # distinct number per class keeps each class's install -> initialise -> tests + # -> uninstall contiguous, and tests within a class keep their definition + # order, which is the order they are written to run in. + # + # The number cannot be set here or derived per-test in this base: a marker + # applied in the base class body binds at definition time, so every subclass + # would inherit the same value and collide. + # -- plumbing ------------------------------------------------------ def prime_for_psbt(self, psbt): @@ -697,19 +727,39 @@ def run_card_selection(self, psbt, expected_view): FlowStep(expected_view), ]) + def reconnect(self): + """ + Drop every open card session and start a new one. + + Running a flow hands the card to init_satochip, which builds its own + connector and parks it on the controller. That leaves this class's cached + connector holding a session the card has already torn down, and the next + direct call fails with a bare status word (0x9C23) that names nothing + about the real problem. So every direct card access starts over rather + than trusting a connector that a flow may have invalidated. + """ + parked = getattr(self.controller, "Satochip_Connector", None) + if parked is not None: + try: + parked.card_disconnect() + except Exception: + pass + self.controller.Satochip_Connector = None + self._disconnect() + return self._connect() + def card_account_xpub(self) -> str: - return self._connect().card_bip32_get_xpub(ACCOUNT_PATH.replace("h", "'"), - "p2wpkh", False) + return self.reconnect().card_bip32_get_xpub(ACCOUNT_PATH.replace("h", "'"), + "p2wpkh", False) def card_master_fingerprint(self) -> bytes: from embit.bip32 import HDKey return HDKey.from_base58( - self._connect().card_bip32_get_xpub("", "p2wpkh", False)).my_fingerprint + self.reconnect().card_bip32_get_xpub("", "p2wpkh", False)).my_fingerprint # -- tests --------------------------------------------------------- - @pytest.mark.order(1) def test_card_holds_the_seed_these_tests_assume(self): """ Everything below compares the card against keys derived from @@ -729,7 +779,6 @@ def test_card_holds_the_seed_these_tests_assume(self): in_test = _regtest_root(BIP39_MNEMONIC).derive(ACCOUNT_PATH).to_public() assert on_card.key.sec() == in_test.key.sec() - @pytest.mark.order(2) def test_parse_runs_in_account_xpub_root_mode(self): """ The card hands the parser an account-level xpub, not a master key. The @@ -763,7 +812,6 @@ def test_parse_runs_in_account_xpub_root_mode(self): assert parser.verified_output_derivation_paths == [ None, bip32.parse_path(CHANGE_PATH)] - @pytest.mark.order(3) def test_card_parse_agrees_with_a_seed_parse(self): """ Same psbt, same wallet, two ways of reaching the keys. Every number the @@ -790,7 +838,6 @@ def test_card_parse_agrees_with_a_seed_parse(self): assert from_card.fee_amount == from_seed.fee_amount assert from_card.destination_addresses == from_seed.destination_addresses - @pytest.mark.order(4) def test_forged_change_claim_is_refused(self): """ The attack the ownership scan exists to stop, run against a real card: an @@ -814,7 +861,6 @@ def test_forged_change_claim_is_refused(self): assert self.controller.psbt_parser is None assert self.controller.psbt_sign_with_satochip is False - @pytest.mark.order(5) def test_forged_input_claim_is_refused(self): """ The same false claim on an input. It cannot cost the user anything -- no @@ -831,7 +877,6 @@ def test_forged_input_claim_is_refused(self): assert self.controller.psbt_parser is None - @pytest.mark.order(6) def test_psbt_for_another_wallet_cannot_be_signed(self): """ A psbt belonging to a different wallet must not verify against this card. @@ -860,7 +905,6 @@ def test_psbt_for_another_wallet_cannot_be_signed(self): ) assert excinfo.value.code == RejectCode.SEED_CANNOT_SIGN - @pytest.mark.order(7) def test_verified_psbt_signs_on_the_card(self): """ End to end: parse in card mode, then let PSBTFinalizeView drive the real @@ -901,19 +945,22 @@ class TestSatochipPSBTSigningFlows(CardPSBTSigningFlowTest): AID = "5361746F43686970" CAP = "SatoChip-0.12-official.cap" + # Above TestSatochipImportSeedFlows' 1-2 so the two Satochip classes do not + # interleave their applet lifecycles. + pytestmark = pytest.mark.order(10) _connector = None @pytest.fixture(scope="class", autouse=True) def applet(self, gp, cap_dir): - result = gp.install_capfile(str(cap_dir / self.CAP)) - logger.info(f"Satochip install result: {result}") - gp.close() - try: - self._provision() - self._seed_card() - except Exception as exc: - pytest.skip(f"Satochip could not be prepared for signing: {exc}") + # install -> initialise -> tests -> uninstall. Preparation failures are + # raised, not skipped: the card is present, so a card that will not + # provision or seed is a real failure and every test below would + # otherwise fail somewhere less informative. + logger.info("Satochip install result: %s", + _reinstall_blank(gp, cap_dir / self.CAP, self.AID)) + self._provision() + self._seed_card() yield self._disconnect() _reauth_and_delete(gp, self.AID) @@ -975,10 +1022,19 @@ def _provision(self): connector.card_verify_PIN() def _seed_card(self): + """ + Put BIP39_MNEMONIC on the card. See the Keycard version below for why the + import runs on a session of its own and why the result is re-read. + """ + self._disconnect() connector = self._connect() (_, _, _, status) = connector.card_get_status() if not status.get("is_seeded"): connector.card_bip32_import_seed(list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) + (_, _, _, status) = connector.card_get_status() + if not status.get("is_seeded"): + raise RuntimeError( + "Satochip accepted the seed import but still reports no key: %s" % status) self._disconnect() @@ -988,6 +1044,7 @@ class TestKeycardPSBTSigningFlows(CardPSBTSigningFlowTest): AID = "A0000008040001" CAP = "Keycard_v3.2.cap" PIN = "123456" + pytestmark = pytest.mark.order(20) _connector = None @@ -998,14 +1055,10 @@ def applet(self, gp, cap_dir): except ImportError: pytest.skip("keycard-py not installed (pip install keycard-py)") - result = gp.install_capfile(str(cap_dir / self.CAP)) - logger.info(f"Keycard install result: {result}") - gp.close() - try: - self._provision() - self._seed_card() - except Exception as exc: - pytest.skip(f"Keycard could not be prepared for signing: {exc}") + logger.info("Keycard install result: %s", + _reinstall_blank(gp, cap_dir / self.CAP, self.AID)) + self._provision() + self._seed_card() yield self._disconnect() _reauth_and_delete(gp, self.AID) @@ -1016,7 +1069,13 @@ def CARD_BUTTON(self): return psbt_views.PSBTSelectSeedView.KEYCARD def prime_for_psbt(self, psbt): + from seedsigner.models.settings import SettingsConstants as SC + super().prime_for_psbt(psbt) + # PSBTSelectSeedView offers each card only when its own support setting is + # on. Satochip's happens to default to enabled, Keycard's does not, so + # without this the menu has no Keycard button to select. + self.settings.set_value(SC.SETTING__KEYCARD_SUPPORT, SC.OPTION__ENABLED) # The Keycard applet has its own PIN, and its own backend: init_satochip # only prompts for a PIN when the controller has none cached, and picks # the connector class from smartcard_backend_preference. @@ -1064,8 +1123,24 @@ def _provision(self): connector.card_verify_PIN() def _seed_card(self): + """ + Put BIP39_MNEMONIC on the card, so the psbts built here are genuinely + this card's to sign. + + The reconnect is load-bearing. Immediately after card_setup, the applet + accepts a LOAD KEY on the same session and reports success, but the key + does not stick: the next status read still says no key, and every later + derivation fails with a bare 0x6985. A fresh session makes the import + take. The status re-read afterwards turns a silent no-op into a loud + failure rather than a run of tests that all fail somewhere else. + """ + self._disconnect() connector = self._connect() (_, _, _, status) = connector.card_get_status() if not (status.get("key_initialized") or status.get("is_seeded")): connector.card_bip32_import_seed(list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) + (_, _, _, status) = connector.card_get_status() + if not (status.get("key_initialized") or status.get("is_seeded")): + raise RuntimeError( + "Keycard accepted the seed import but still reports no key: %s" % status) self._disconnect() From 1565cb957770249aa4704f8f96e5251006c008c2 Mon Sep 17 00:00:00 2001 From: 3rd Iteration Date: Fri, 4 Sep 2026 07:50:42 -0400 Subject: [PATCH 12/12] tests: initialise the card in one session, not two The Keycard applet refused every seed import with 0x6985, and the diagnosis was wrong twice before the status word was actually read. card_bip32_import_seed reports failure in its status word rather than by raising, so the unchecked call looked like a success. The first guess -- that the key "did not stick" and needed a fresh session -- had it exactly backwards: card_setup leaves the session that ran it authenticated, card_get_status there returns the applet's full native record, and LOAD KEY is accepted. A connector built afterwards against the same, now set-up card comes back reduced (status answers with a four-field fallback instead of the native record) and the applet refuses LOAD KEY. Splitting provisioning and seeding across two connectors is what broke it. So provisioning and seeding are now one step, on one session, for both cards, and the import's status word is checked rather than assumed. A refusal names itself instead of surfacing later as an unexplained 0x6985 on every derivation. The whole module now passes against a real reader and JavaCard: 19/19, covering both card signing modes end to end alongside the pre-existing SeedKeeper save and Satochip import flows. Co-Authored-By: Claude Opus 5 --- tests/test_flows_smartcard_hardware.py | 73 ++++++++++++++------------ 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/tests/test_flows_smartcard_hardware.py b/tests/test_flows_smartcard_hardware.py index 62458daeb..191f42f50 100644 --- a/tests/test_flows_smartcard_hardware.py +++ b/tests/test_flows_smartcard_hardware.py @@ -959,8 +959,7 @@ def applet(self, gp, cap_dir): # otherwise fail somewhere less informative. logger.info("Satochip install result: %s", _reinstall_blank(gp, cap_dir / self.CAP, self.AID)) - self._provision() - self._seed_card() + self._initialise() yield self._disconnect() _reauth_and_delete(gp, self.AID) @@ -1003,12 +1002,17 @@ def _disconnect(self): pass TestSatochipPSBTSigningFlows._connector = None - def _provision(self): + def _initialise(self): + """ + Provision the applet and load the seed, on one session. See the Keycard + version for why setup and seeding must not be split across connectors. + """ import os as _os connector = self._connect() - (_, _, _, status) = connector.card_get_status() pin_list = list(CARD_PIN.encode("utf-8")) + + (_, _, _, status) = connector.card_get_status() if not status.get("setup_done"): connector.card_setup( pin_tries0=5, ublk_tries0=1, @@ -1021,20 +1025,14 @@ def _provision(self): connector.set_pin(0, pin_list) connector.card_verify_PIN() - def _seed_card(self): - """ - Put BIP39_MNEMONIC on the card. See the Keycard version below for why the - import runs on a session of its own and why the result is re-read. - """ - self._disconnect() - connector = self._connect() (_, _, _, status) = connector.card_get_status() if not status.get("is_seeded"): connector.card_bip32_import_seed(list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) (_, _, _, status) = connector.card_get_status() if not status.get("is_seeded"): raise RuntimeError( - "Satochip accepted the seed import but still reports no key: %s" % status) + "Satochip accepted the seed import but reports no key: %s" % status) + self._disconnect() @@ -1057,8 +1055,7 @@ def applet(self, gp, cap_dir): logger.info("Keycard install result: %s", _reinstall_blank(gp, cap_dir / self.CAP, self.AID)) - self._provision() - self._seed_card() + self._initialise() yield self._disconnect() _reauth_and_delete(gp, self.AID) @@ -1104,10 +1101,25 @@ def _disconnect(self): pass TestKeycardPSBTSigningFlows._connector = None - def _provision(self): + def _initialise(self): + """ + Provision the applet and load the seed, on one session. + + This is deliberately a single step. card_setup leaves the session that + ran it authenticated -- card_get_status returns the applet's full native + status -- and LOAD KEY is accepted there. A connector built afterwards + against the same, now set-up card comes back in a reduced state (status + answers with a four-field fallback rather than the native record) and the + applet refuses LOAD KEY with 0x6985. So the seed goes on while the card + is still talking to the session that set it up. + + The class fixture installs a blank applet first, so this always runs the + full path rather than resuming a half-initialised card. + """ connector = self._connect() - (_, _, _, status) = connector.card_get_status() pin_list = list(self.PIN.encode("utf-8")) + + (_, _, _, status) = connector.card_get_status() if not status.get("setup_done"): if connector.needs_secure_channel: connector.card_initiate_secure_channel() @@ -1119,28 +1131,21 @@ def _provision(self): secmemsize=0x0000, memsize=0, create_object_ACL=0x01, create_key_ACL=0x01, create_pin_ACL=0x01, ) - connector.set_pin(0, pin_list) - connector.card_verify_PIN() + connector.set_pin(0, pin_list) - def _seed_card(self): - """ - Put BIP39_MNEMONIC on the card, so the psbts built here are genuinely - this card's to sign. - - The reconnect is load-bearing. Immediately after card_setup, the applet - accepts a LOAD KEY on the same session and reports success, but the key - does not stick: the next status read still says no key, and every later - derivation fails with a bare 0x6985. A fresh session makes the import - take. The status re-read afterwards turns a silent no-op into a loud - failure rather than a run of tests that all fail somewhere else. - """ - self._disconnect() - connector = self._connect() (_, _, _, status) = connector.card_get_status() if not (status.get("key_initialized") or status.get("is_seeded")): - connector.card_bip32_import_seed(list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) + (_, sw1, sw2) = connector.card_bip32_import_seed( + list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) + # card_bip32_import_seed reports failure in its status word rather + # than by raising, so an unchecked call looks like a success and only + # shows up later as an unexplained 0x6985 on every derivation. + if (sw1, sw2) != (0x90, 0x00): + raise RuntimeError( + "Keycard refused the seed import: SW=%02X%02X" % (sw1, sw2)) (_, _, _, status) = connector.card_get_status() if not (status.get("key_initialized") or status.get("is_seeded")): raise RuntimeError( - "Keycard accepted the seed import but still reports no key: %s" % status) + "Keycard accepted the seed import but reports no key: %s" % status) + self._disconnect()