What changed, and why it matters
This commit adds a new internal storage service called WARD to the Trezor firmware. It lets apps store small pieces of data tied to a specific passphrase wallet. The change is a feature implementation, not a fix for a known security bug. There is no evidence in the commit or supplied references that this is a security patch or that it addresses a disclosed vulnerability.
No immediate security action required. Treat as a normal feature commit. If reviewing for security, focus on the native `trezorward` module (not shown in this diff), the SLIP-21 derivation path, and whether storage isolation guarantees hold in the underlying C implementation.
Security signals we found
New feature implementation, not a security fix
Uses SLIP-21 derivation from passphrase-dependent seed for wallet ID
Storage isolation between apps, wallets, and subscopes
Debug-only check to detect concurrent modification during iteration
No changelog entry, but commit message explains feature rationale
Evidence from the diff
The commit implements the WARD (Wallet Application Record Directory) service. It adds Python wrappers around a native trezorward module, derives a per-passphrase wallet ID using SLIP-21, and provides namespaced key-value storage with subscopes. The code replaces previous NotImplementedError stubs with actual implementations. It includes isolation between apps, wallets, and subscopes, debug-only detection of modifications during iteration, and unit tests covering basic operations, isolation, and error handling.
Changed components
core/src/apps/ward/__init__.pycore/src/apps/ward/keys.pycore/src/apps/ward/store.pycore/embed/upymod/qstrdefsport.hcore/tests/test_apps.ward.pyInspect captured patch +250 / −8
### core/embed/upymod/qstrdefsport.h
@@ -172,6 +172,7 @@ Q(apps.nostr.sign_event)
Q(apps.telemetry)
Q(apps.telemetry.get_telemetry)
Q(apps.ward)
+Q(apps.ward.keys)
Q(apps.ward.store)
Q(apps.workflow_handlers)
Q(authenticate_device)
@@ -250,6 +251,7 @@ Q(helpers)
Q(homescreen)
Q(index_management)
Q(keychain)
+Q(keys)
Q(layout)
Q(layouts)
Q(list_names)
### core/src/apps/ward/__init__.py
@@ -25,7 +25,10 @@ class WardApp(IntEnum):
async def open_ward(app: WardApp) -> WardStore:
"""Open the WARD store of `app` in the current passphrase wallet."""
- raise NotImplementedError
+ from .keys import derive_wallet_id
+ from .store import WardStore
+
+ return WardStore(await derive_wallet_id(), bytes([app]))
def with_ward(app: WardApp) -> Callable[[HandlerWithWard[T]], HandlerWithWard[T]]:
### core/src/apps/ward/keys.py
@@ -0,0 +1,14 @@
+_WARD_KEY_PATH_PREFIX = [b"TREZOR", b"WARD"]
+
+
+async def derive_wallet_id() -> bytes:
+ """Identify the current passphrase wallet.
+
+ Derived from the passphrase-dependent seed, so every passphrase wallet has
+ its own id.
+ """
+ from apps.common.seed import Slip21Node, get_seed
+
+ node = Slip21Node(await get_seed())
+ node.derive_path(_WARD_KEY_PATH_PREFIX + [b"Wallet ID"])
+ return node.key()
### core/src/apps/ward/store.py
@@ -1,5 +1,11 @@
+import trezorward
from trezorward import WardError # noqa: F401
+if __debug__:
+ # Number of modifications of any store, lets debug builds detect
+ # modifications during iteration.
+ _modifications = 0
+
class WardStore:
"""Records of one app in one passphrase wallet.
@@ -25,11 +31,15 @@ def subscope(self, name: bytes) -> "WardStore":
A subscope is a separate namespace, records of a store and of its
subscopes are never visible to each other.
"""
- raise NotImplementedError
+ # length-prefixed, so that different subscopes never share an identifier
+ app = self._app + bytes([len(name)]) + name
+ if len(app) > 0xFF:
+ raise ValueError("Subscope name too long")
+ return WardStore(self._wallet_id, app)
async def get(self, key: bytes) -> bytes | None:
"""Return the value stored under `key`, or None if there is none."""
- raise NotImplementedError
+ return trezorward.get(self._wallet_id, self._app, key)
def entries(self) -> "WardIterator":
"""Iterate over all `(key, value)` records with `async for`, one at a time.
@@ -39,15 +49,21 @@ def entries(self) -> "WardIterator":
results (in debug builds, the iteration fails with RuntimeError).
Once exhausted, the iterator stays exhausted.
"""
- raise NotImplementedError
+ return WardIterator(self._wallet_id, self._app)
async def set(self, key: bytes, value: bytes) -> None:
"""Store `value` under `key`, replacing the current value, if any."""
- raise NotImplementedError
+ if __debug__:
+ global _modifications
+ _modifications += 1
+ trezorward.set(self._wallet_id, self._app, key, value)
async def delete(self, key: bytes) -> bool:
"""Delete the record stored under `key`, return whether there was one."""
- raise NotImplementedError
+ if __debug__:
+ global _modifications
+ _modifications += 1
+ return trezorward.delete(self._wallet_id, self._app, key)
class WardIterator:
@@ -56,10 +72,22 @@ class WardIterator:
def __init__(self, wallet_id: bytes, app: bytes) -> None:
self._wallet_id = wallet_id
self._app = app
- self._cursor = 0
+ self._cursor: int | None = 0 # None once exhausted
+ if __debug__:
+ self._modifications = _modifications
def __aiter__(self) -> "WardIterator":
return self
async def __anext__(self) -> tuple[bytes, bytes]:
- raise NotImplementedError
+ if self._cursor is None:
+ raise StopAsyncIteration
+ if __debug__:
+ if self._modifications != _modifications:
+ raise RuntimeError("WARD modified during iteration")
+ entry = trezorward.next_entry(self._wallet_id, self._app, self._cursor)
+ if entry is None:
+ self._cursor = None
+ raise StopAsyncIteration
+ self._cursor, key, value = entry
+ return key, value
### core/tests/test_apps.ward.py
@@ -0,0 +1,195 @@
+# flake8: noqa: F403,F405
+from common import * # isort:skip
+
+from storage import cache, cache_common
+from trezor import config, wire
+from trezor.crypto import bip39
+from trezor.wire import context
+
+from apps.common.keychain import with_slip44_keychain
+from apps.common.paths import PATTERN_SEP5
+
+if utils.USE_WARD:
+ from apps.ward import WardApp, open_ward, with_ward
+ from apps.ward.keys import derive_wallet_id
+ from apps.ward.store import WardError, WardStore
+
+if not utils.USE_THP:
+ from storage import cache_codec
+
+MNEMONIC = " ".join(["all"] * 12)
+SEED = bip39.seed(MNEMONIC, "")
+SEED_PASSPHRASE = bip39.seed(MNEMONIC, "TREZOR")
+OTHER_APP = 2
+
+
+@unittest.skipUnless(utils.USE_WARD, "WARD is not enabled")
+class TestWard(TestCaseWithContext):
+ def setUp(self):
+ config.init()
+ config.wipe()
+ if not utils.USE_THP:
+ cache_codec.start_session()
+ self.set_seed(SEED)
+
+ def tearDown(self):
+ cache.clear_all()
+
+ def set_seed(self, seed):
+ """Switch the current passphrase wallet."""
+ context.cache_set(cache_common.APP_COMMON_SEED, seed)
+
+ def open(self, app=None):
+ return await_result(open_ward(WardApp.BITCOIN if app is None else app))
+
+ def entries(self, ward):
+ async def collect():
+ result = []
+ async for entry in ward.entries():
+ result.append(entry)
+ return result
+
+ return await_result(collect())
+
+ def test_derive_wallet_id(self):
+ # SLIP21(seed, [b"TREZOR", b"WARD", b"Wallet ID"]).key()
+ self.assertEqual(
+ await_result(derive_wallet_id()),
+ bytes.fromhex(
+ "513e17b7e2bd487aa07cedbe6bda05c609235f9d69e9d47201bdc1c603d96d11"
+ ),
+ )
+ self.set_seed(SEED_PASSPHRASE)
+ self.assertEqual(
+ await_result(derive_wallet_id()),
+ bytes.fromhex(
+ "b6be487329524e4691ebd517236746dddbaa1af1e947dd12f1aa02edfae173ba"
+ ),
+ )
+
+ def test_set(self):
+ ward = self.open()
+ self.assertIsNone(await_result(ward.get(b"key")))
+ await_result(ward.set(b"key", b"value"))
+ self.assertEqual(await_result(ward.get(b"key")), b"value")
+ await_result(ward.set(b"key", b"other"))
+ self.assertEqual(await_result(ward.get(b"key")), b"other")
+
+ def test_delete(self):
+ ward = self.open()
+ self.assertFalse(await_result(ward.delete(b"key")))
+ await_result(ward.set(b"key", b"value"))
+ self.assertTrue(await_result(ward.delete(b"key")))
+ self.assertIsNone(await_result(ward.get(b"key")))
+ self.assertFalse(await_result(ward.delete(b"key")))
+
+ def test_entries(self):
+ ward = self.open()
+ other = self.open(OTHER_APP)
+ self.assertEqual(self.entries(ward), [])
+
+ await_result(ward.set(b"a", b"1"))
+ await_result(other.set(b"x", b""))
+ await_result(ward.set(b"b", b"2"))
+ self.assertEqual(self.entries(ward), [(b"a", b"1"), (b"b", b"2")])
+ self.assertEqual(self.entries(other), [(b"x", b"")])
+
+ def test_entries_exhausted(self):
+ ward = self.open()
+ entries = ward.entries()
+ with self.assertRaises(StopAsyncIteration):
+ await_result(entries.__anext__())
+ await_result(ward.set(b"a", b"1"))
+ with self.assertRaises(StopAsyncIteration):
+ await_result(entries.__anext__())
+
+ @unittest.skipUnless(__debug__, "debug builds only")
+ def test_entries_modified(self):
+ ward = self.open()
+ await_result(ward.set(b"a", b"1"))
+ await_result(ward.set(b"b", b"2"))
+
+ async def read():
+ async for key, _ in ward.entries():
+ await ward.get(key)
+
+ async def modify(modification):
+ async for _ in ward.entries():
+ await modification
+
+ # reading during iteration is allowed
+ await_result(read())
+
+ # modifying any store is not
+ for store in (ward, ward.subscope(b"sub"), self.open(OTHER_APP)):
+ with self.assertRaises(RuntimeError):
+ await_result(modify(store.set(b"c", b"3")))
+ with self.assertRaises(RuntimeError):
+ await_result(modify(ward.delete(b"a")))
+
+ def test_isolation(self):
+ wards = [self.open(), self.open(OTHER_APP)]
+ self.set_seed(SEED_PASSPHRASE)
+ wards.append(self.open())
+ for i, ward in enumerate(wards):
+ await_result(ward.set(b"key", bytes([i])))
+ for i, ward in enumerate(wards):
+ self.assertEqual(await_result(ward.get(b"key")), bytes([i]))
+ self.assertEqual(self.entries(ward), [(b"key", bytes([i]))])
+
+ def test_subscope(self):
+ ward = self.open()
+ wards = [
+ ward,
+ ward.subscope(b"Testnet"),
+ ward.subscope(b"Testnet").subscope(b"Regtest"),
+ # subscope names are length-prefixed, so these do not collide
+ ward.subscope(b"ab").subscope(b"c"),
+ ward.subscope(b"a").subscope(b"bc"),
+ ward.subscope(b""),
+ ]
+ for i, w in enumerate(wards):
+ await_result(w.set(b"key", bytes([i])))
+ for i, w in enumerate(wards):
+ self.assertEqual(await_result(w.get(b"key")), bytes([i]))
+ self.assertEqual(self.entries(w), [(b"key", bytes([i]))])
+
+ # the same subscope of another app is separate as well
+ other = self.open(OTHER_APP).subscope(b"Testnet")
+ self.assertIsNone(await_result(other.get(b"key")))
+
+ with self.assertRaises(ValueError):
+ ward.subscope(bytes(256))
+
+ def test_errors(self):
+ ward = self.open()
+ with self.assertRaises(WardError):
+ await_result(ward.set(b"key", bytes(3000)))
+
+ await_result(ward.set(b"key", b"value"))
+ config.lock()
+ with self.assertRaises(WardError):
+ await_result(ward.get(b"key"))
+
+ def test_with_ward(self):
+ @with_slip44_keychain(PATTERN_SEP5, slip44_id=42)
+ @with_ward(WardApp.BITCOIN)
+ async def handler(msg, keychain, *, ward):
+ return msg, ward
+
+ msg, ward = await_result(handler("msg"))
+ self.assertEqual(msg, "msg")
+ self.assertTrue(isinstance(ward, WardStore))
+ self.assertEqual(ward._wallet_id, self.open()._wallet_id)
+
+ def test_with_ward_error(self):
+ @with_ward(WardApp.BITCOIN)
+ async def handler(msg, *, ward):
+ await ward.set(b"key", bytes(3000))
+
+ with self.assertRaises(wire.ProcessError):
+ await_result(handler("msg"))
+
+
+if __name__ == "__main__":
+ unittest.main()Why this scored 28/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.