hermes-agent/tests/wallet/test_persistence.py
Shannon Sands 253c7abbe9 fix(wallet): harden keystore fallback, persist policy/history, wire gateway injection
Addresses review findings:
- Remove insecure automatic encrypted-file credential-store fallback.
   now only uses real OS/keyctl-backed stores,
  or remains unavailable. Headless users must use explicit
  HERMES_KEYSTORE_PASSPHRASE if desired.
- Add shared wallet runtime so tools/CLI/approval use the same configured
  providers and persisted policy state.
- Inject keystore-backed secrets into gateway/headless startup too, so
  migrated .env stubs don't break messaging deployments.
- Persist wallet policy state (freeze, daily totals, rate-limit timestamps,
  cooldown timestamps) across invocations.
- Persist transaction history to disk across invocations.
- Make owner-approved sends execute through the same runtime/policy path and
  record policy state after successful approved sends.
- Fix wallet export by allowing explicit CLI export reads of sealed keys via
  dedicated requester path () instead of generic CLI reads.
- Make CLI wallet sends evaluate policy before execution and honor freeze.
- Align docs with actual crypto primitive (XSalsa20-Poly1305 via SecretBox)
  and current policy-config scope.

Validation:
- 129 tests passing
- freeze persistence verified manually
- wallet export verified manually
2026-03-29 08:38:29 +10:00

114 lines
3.8 KiB
Python

"""Tests for wallet persistence: tx log, policy freeze, export path."""
import json
from decimal import Decimal
import pytest
nacl = pytest.importorskip("nacl")
argon2 = pytest.importorskip("argon2")
from keystore.client import KeystoreClient
from wallet.manager import WalletManager
from wallet.policy import PolicyEngine, TxRequest, PolicyVerdict
from wallet.chains import ChainProvider, Balance, TransactionResult, GasEstimate, ChainConfig
class FakeProvider(ChainProvider):
def __init__(self):
super().__init__(ChainConfig(
chain_id="test-chain",
display_name="Test Chain",
symbol="TEST",
decimals=18,
rpc_url="http://localhost:8545",
explorer_url="https://testscan.io",
is_testnet=True,
))
def get_balance(self, address: str) -> Balance:
return Balance("test-chain", address, Decimal("10"), 10, "TEST", 18)
def send_transaction(self, from_private_key, to_address, amount) -> TransactionResult:
return TransactionResult(
tx_hash="0xabc",
chain="test-chain",
status="submitted",
explorer_url="https://testscan.io/tx/0xabc",
)
def estimate_fee(self, from_address, to_address, amount) -> GasEstimate:
return GasEstimate("test-chain", Decimal("0.001"), 1, "TEST")
def validate_address(self, address: str) -> bool:
return True
def generate_keypair(self):
return ("0x" + "A" * 40, "deadbeef" * 8)
@staticmethod
def address_from_key(private_key: str) -> str:
return "0x" + "B" * 40
@pytest.fixture
def ks(tmp_path):
db = tmp_path / "keystore" / "secrets.db"
client = KeystoreClient(db)
client.initialize("test-pass")
return client
def test_export_private_key_for_cli_export_requester(ks, tmp_path):
mgr = WalletManager(ks, state_dir=tmp_path / "wallet")
mgr.register_provider("test-chain", FakeProvider())
w = mgr.create_wallet(chain="test-chain", label="Exportable")
exported = mgr.export_private_key(w.wallet_id)
assert exported
assert isinstance(exported, str)
def test_tx_history_persists_across_manager_instances(ks, tmp_path):
state_dir = tmp_path / "wallet"
mgr1 = WalletManager(ks, state_dir=state_dir)
mgr1.register_provider("test-chain", FakeProvider())
w = mgr1.create_wallet(chain="test-chain")
mgr1.send(w.wallet_id, "0xreceiver", Decimal("1.0"), decided_by="owner_cli", policy_result='{}')
mgr2 = WalletManager(ks, state_dir=state_dir)
mgr2.register_provider("test-chain", FakeProvider())
hist = mgr2.get_tx_history(w.wallet_id)
assert len(hist) == 1
assert hist[0].tx_hash == "0xabc"
def test_policy_freeze_persists_across_instances(tmp_path):
state = tmp_path / "wallet" / "policy_state.json"
p1 = PolicyEngine(state_path=state)
p1.freeze()
p2 = PolicyEngine(state_path=state)
tx = TxRequest(
wallet_id="w1", wallet_type="agent", chain="test-chain",
to_address="0xreceiver", amount=Decimal("0.1"), symbol="TEST",
)
result = p2.evaluate(tx)
assert result.verdict == PolicyVerdict.BLOCK
assert "frozen" in result.reason.lower()
def test_policy_record_transaction_persists(tmp_path):
state = tmp_path / "wallet" / "policy_state.json"
p1 = PolicyEngine(state_path=state)
tx = TxRequest(
wallet_id="w1", wallet_type="agent", chain="test-chain",
to_address="0xreceiver", amount=Decimal("0.5"), symbol="TEST",
)
p1.record_transaction(tx)
p2 = PolicyEngine(state_path=state)
# same transaction should now trip cooldown default if configured explicitly
p2._policies = {"cooldown": {"min_seconds": 99999}}
result = p2.evaluate(tx)
assert result.verdict == PolicyVerdict.BLOCK
assert result.failed == "cooldown"