mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-10-20 05:15:31 +00:00
Phase 2 of the wallet architecture — crypto wallet functionality built on top of the keystore. Core components: - wallet/manager.py: Wallet CRUD, balance checks, transaction execution. Private keys stored as sealed keystore secrets — only the manager reads them, and only to pass to chain providers for signing. - wallet/policy.py: Transaction policy engine with spending limits, daily limits, rate limits, cooldown, recipient allow/blocklists, approval thresholds, and a kill switch (freeze/unfreeze). - wallet/chains/: Abstract ChainProvider interface + EVM and Solana impls. EVM supports Ethereum, Base, Polygon, Arbitrum, Optimism + testnets. Solana supports mainnet + devnet. Agent integration: - tools/wallet_tool.py: 5 agent-facing tools (wallet_list, wallet_balance, wallet_send, wallet_history, wallet_estimate_gas). All return JSON, none expose private keys. wallet_send goes through the policy engine. - toolsets.py: New 'wallet' toolset - model_tools.py: wallet_tool added to discovery list CLI: - wallet/cli.py: Full CLI — create, create-agent, import, list, balance, send (with interactive confirmation), fund, history, freeze, unfreeze, status - hermes_cli/main.py: 'hermes wallet' subcommand registered Policy defaults: - Agent wallets: 1.0 native/tx max, 5.0/day, 5 txns/hour, 30s cooldown, approval required above 0.5 native - User wallets: owner approval required for all transactions Tests: 100 passing (28 wallet + 72 keystore)
239 lines
8.3 KiB
Python
239 lines
8.3 KiB
Python
"""Policy engine — evaluates transactions against configurable rules.
|
|
|
|
Policies are checked in order. The first ``block`` or ``require_approval``
|
|
result wins. If all policies pass, the transaction is auto-approved.
|
|
|
|
For v1, policies are in-memory (loaded from config.yaml). A future
|
|
version will persist per-wallet policies in the keystore.
|
|
"""
|
|
|
|
import logging
|
|
import time
|
|
from collections import defaultdict
|
|
from dataclasses import dataclass, field
|
|
from decimal import Decimal
|
|
from enum import Enum
|
|
from typing import Dict, List, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class PolicyVerdict(str, Enum):
|
|
ALLOW = "allow"
|
|
REQUIRE_APPROVAL = "require_approval"
|
|
BLOCK = "block"
|
|
|
|
|
|
@dataclass
|
|
class PolicyResult:
|
|
"""Result of evaluating all policies for a transaction."""
|
|
verdict: PolicyVerdict
|
|
reason: str = ""
|
|
checked: List[str] = field(default_factory=list) # Policy names that passed
|
|
failed: str = "" # Policy name that blocked/required approval
|
|
|
|
|
|
@dataclass
|
|
class TxRequest:
|
|
"""A pending transaction to evaluate."""
|
|
wallet_id: str
|
|
wallet_type: str # "user" | "agent"
|
|
chain: str
|
|
to_address: str
|
|
amount: Decimal
|
|
symbol: str
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Individual policy checks
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _check_spending_limit(tx: TxRequest, config: dict) -> Optional[PolicyVerdict]:
|
|
"""Block if single transaction exceeds max amount."""
|
|
max_amount = Decimal(str(config.get("max_native", "0")))
|
|
if max_amount > 0 and tx.amount > max_amount:
|
|
return PolicyVerdict.BLOCK
|
|
return None
|
|
|
|
|
|
def _check_daily_limit(tx: TxRequest, config: dict, daily_totals: Dict[str, Decimal]) -> Optional[PolicyVerdict]:
|
|
"""Block if daily aggregate exceeds limit."""
|
|
max_daily = Decimal(str(config.get("max_native", "0")))
|
|
if max_daily <= 0:
|
|
return None
|
|
today_key = f"{tx.wallet_id}:{time.strftime('%Y-%m-%d')}"
|
|
current_total = daily_totals.get(today_key, Decimal("0"))
|
|
if current_total + tx.amount > max_daily:
|
|
return PolicyVerdict.BLOCK
|
|
return None
|
|
|
|
|
|
def _check_rate_limit(tx: TxRequest, config: dict, tx_timestamps: Dict[str, list]) -> Optional[PolicyVerdict]:
|
|
"""Block if too many transactions in the time window."""
|
|
max_txns = config.get("max_txns", 0)
|
|
window = config.get("window_seconds", 3600)
|
|
if max_txns <= 0:
|
|
return None
|
|
|
|
key = tx.wallet_id
|
|
now = time.time()
|
|
timestamps = tx_timestamps.get(key, [])
|
|
# Prune old timestamps
|
|
timestamps = [t for t in timestamps if now - t < window]
|
|
tx_timestamps[key] = timestamps
|
|
|
|
if len(timestamps) >= max_txns:
|
|
return PolicyVerdict.BLOCK
|
|
return None
|
|
|
|
|
|
def _check_cooldown(tx: TxRequest, config: dict, last_tx_time: Dict[str, float]) -> Optional[PolicyVerdict]:
|
|
"""Block if not enough time since last transaction."""
|
|
min_seconds = config.get("min_seconds", 0)
|
|
if min_seconds <= 0:
|
|
return None
|
|
key = tx.wallet_id
|
|
last = last_tx_time.get(key, 0)
|
|
if time.time() - last < min_seconds:
|
|
return PolicyVerdict.BLOCK
|
|
return None
|
|
|
|
|
|
def _check_allowed_recipients(tx: TxRequest, config: dict) -> Optional[PolicyVerdict]:
|
|
"""Block if recipient not in allowlist (when configured)."""
|
|
addresses = config.get("addresses", [])
|
|
if not addresses:
|
|
return None # No allowlist = allow all
|
|
if tx.to_address.lower() not in [a.lower() for a in addresses]:
|
|
return PolicyVerdict.BLOCK
|
|
return None
|
|
|
|
|
|
def _check_blocked_recipients(tx: TxRequest, config: dict) -> Optional[PolicyVerdict]:
|
|
"""Block if recipient is in blocklist."""
|
|
addresses = config.get("addresses", [])
|
|
if tx.to_address.lower() in [a.lower() for a in addresses]:
|
|
return PolicyVerdict.BLOCK
|
|
return None
|
|
|
|
|
|
def _check_require_approval(tx: TxRequest, config: dict) -> Optional[PolicyVerdict]:
|
|
"""Require owner approval if amount exceeds threshold."""
|
|
above = Decimal(str(config.get("above_native", "-1")))
|
|
if above < 0:
|
|
return None # Not configured
|
|
if tx.amount > above:
|
|
return PolicyVerdict.REQUIRE_APPROVAL
|
|
return None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Policy engine
|
|
# ---------------------------------------------------------------------------
|
|
|
|
# Default policies for agent wallets (can be tightened, not loosened)
|
|
AGENT_WALLET_DEFAULTS = {
|
|
"spending_limit": {"max_native": "1.0"}, # Max per tx (in native token)
|
|
"daily_limit": {"max_native": "5.0"}, # Max per day
|
|
"rate_limit": {"max_txns": 5, "window_seconds": 3600},
|
|
"cooldown": {"min_seconds": 30},
|
|
"require_approval": {"above_native": "0.5"}, # Require approval above this
|
|
}
|
|
|
|
# User wallets always require approval by default
|
|
USER_WALLET_DEFAULTS = {
|
|
"require_approval": {"above_native": "0"}, # Always require approval
|
|
}
|
|
|
|
|
|
class PolicyEngine:
|
|
"""Evaluates transactions against a set of policies."""
|
|
|
|
def __init__(self, policies: Optional[Dict[str, dict]] = None):
|
|
self._policies = policies or {}
|
|
# Tracking state for rate-based policies
|
|
self._daily_totals: Dict[str, Decimal] = defaultdict(Decimal)
|
|
self._tx_timestamps: Dict[str, list] = defaultdict(list)
|
|
self._last_tx_time: Dict[str, float] = {}
|
|
self._frozen = False
|
|
|
|
@property
|
|
def is_frozen(self) -> bool:
|
|
return self._frozen
|
|
|
|
def freeze(self) -> None:
|
|
"""Kill switch — block all transactions."""
|
|
self._frozen = True
|
|
logger.warning("Wallet FROZEN — all transactions blocked")
|
|
|
|
def unfreeze(self) -> None:
|
|
"""Unfreeze — resume normal operation."""
|
|
self._frozen = False
|
|
logger.info("Wallet unfrozen")
|
|
|
|
def evaluate(self, tx: TxRequest) -> PolicyResult:
|
|
"""Evaluate a transaction against all policies.
|
|
|
|
Returns PolicyResult with the final verdict.
|
|
"""
|
|
if self._frozen:
|
|
return PolicyResult(
|
|
verdict=PolicyVerdict.BLOCK,
|
|
reason="Wallet is frozen (kill switch active)",
|
|
failed="freeze",
|
|
)
|
|
|
|
# Select policy set based on wallet type
|
|
if tx.wallet_type == "agent":
|
|
policies = {**AGENT_WALLET_DEFAULTS, **self._policies}
|
|
else:
|
|
policies = {**USER_WALLET_DEFAULTS, **self._policies}
|
|
|
|
checked = []
|
|
|
|
# Check each policy
|
|
_CHECKS = {
|
|
"spending_limit": lambda cfg: _check_spending_limit(tx, cfg),
|
|
"daily_limit": lambda cfg: _check_daily_limit(tx, cfg, self._daily_totals),
|
|
"rate_limit": lambda cfg: _check_rate_limit(tx, cfg, self._tx_timestamps),
|
|
"cooldown": lambda cfg: _check_cooldown(tx, cfg, self._last_tx_time),
|
|
"allowed_recipients": lambda cfg: _check_allowed_recipients(tx, cfg),
|
|
"blocked_recipients": lambda cfg: _check_blocked_recipients(tx, cfg),
|
|
"require_approval": lambda cfg: _check_require_approval(tx, cfg),
|
|
}
|
|
|
|
for policy_name, config in policies.items():
|
|
check_fn = _CHECKS.get(policy_name)
|
|
if not check_fn:
|
|
continue
|
|
|
|
result = check_fn(config)
|
|
if result == PolicyVerdict.BLOCK:
|
|
return PolicyResult(
|
|
verdict=PolicyVerdict.BLOCK,
|
|
reason=f"Blocked by {policy_name} policy",
|
|
checked=checked,
|
|
failed=policy_name,
|
|
)
|
|
elif result == PolicyVerdict.REQUIRE_APPROVAL:
|
|
return PolicyResult(
|
|
verdict=PolicyVerdict.REQUIRE_APPROVAL,
|
|
reason=f"Requires approval ({policy_name} policy)",
|
|
checked=checked,
|
|
failed=policy_name,
|
|
)
|
|
checked.append(policy_name)
|
|
|
|
return PolicyResult(
|
|
verdict=PolicyVerdict.ALLOW,
|
|
reason="All policies passed",
|
|
checked=checked,
|
|
)
|
|
|
|
def record_transaction(self, tx: TxRequest) -> None:
|
|
"""Update tracking state after a successful transaction."""
|
|
today_key = f"{tx.wallet_id}:{time.strftime('%Y-%m-%d')}"
|
|
self._daily_totals[today_key] += tx.amount
|
|
|
|
self._tx_timestamps[tx.wallet_id].append(time.time())
|
|
self._last_tx_time[tx.wallet_id] = time.time()
|