# Expansion Plan — Crypto Puzzle Bot → Security Stack

## 1. Goal
Extend `hermes_bot_miniapp` so the `/puzzle` router learns three hard security domains
plus a CTF/autonomous-agent layer. The target is a **defensive, read-only toolchain** that
classifies a query and routes it to a domain solver, names detectable weaknesses ("vectors"),
and scores "funds aivable to get" (recoverable / currently-unlocked balance) from public on-chain
evidence — **without** ever decoding private keys or executing financial actions.

```
user text  →  /puzzle  →  classifier  →  solver
  ├── cipher / math / mnemonic / oracle / encoder / generic   (existing)
  ├── /puzzle sc  <Solidity file or contract>     →  contract_audit.py      (OWASP SC01-SC10)
  ├── /puzzle rev  <text/address/bytecode>        →  reverse_analyze.py     (EVM + native)
  ├── /puzzle vector <contract/pool/address>      →  vector_funds.py        (funds-availability odor)
  ├── /puzzle ctf <flag/puzzle>                   →  ctf_agent.py           (autonomous pipeline)
  └── /puzzle base44 <file/url>                   →  base44_agent.py        (base44.app post/comment)
```

## 2. Architecture (unchanged surface)
- Single router `classify_puzzle()` picks the domain.
- Each domain is a self-contained module under `tools/`, shell-out ready for the Node bot.
- The Node bot `fjf-token/tools/fjf_telegram_bot.js` gains a `/puzzle` sub-command dispatch to
  `cmdPuzzle()` → optional sub-command + `puzzle_cli.py <domain> <args>`.
- All tools are read-only; no private keys, no third-party fund access, no transaction execution.

## 3. Modules to build

### 3A. `tools/contract_audit.py` — Smart contract analysis
- Input: Solidity file path, or `address` (pulls source/bytecode via `cast code`, `cast storage`, or
  `contract-code` public RPC).
- Pure-Python OWASP Smart Contract Top 10 detectors (no Slither hard-dependency, optional external):
  - SC01 reentrancy (single / cross-function / protected)
  - SC02 unchecked-return / unchecked-call
  - SC03 integer overflow/underflow (+ SMTChecker hint)
  - SC04 arithmetic / division-by-zero
  - SC05 tx.origin misuse (critical)
  - SC06 unsafe delegatecall
  - SC07 selfdestruct / parity multi-sig (old) / suicide
  - SC08 time manipulation (block.timestamp, difficulty, difficulty)
  - SC09 bad randomness (blockhash, block.difficulty)
  - SC10 access control (onlyOwner, tx.origin, missing checks)
- Optional: run `slither`, `forge`, `cast` if installed; else the pure-Python engine owns 90%.
- Output: verdict (0–100 risk score), ranked finding list with severity + remediation.
- Acceptance: built-in `tester.sol` (reentrancy + unchecked + tx.origin) → 3 findings, score high.

### 3B. `tools/reverse_analyze.py` — Reversing
- EVM bytecode path:
  - `cast code <addr>` (ABI/bytecode), `cast storage <addr>` (layout), `cast 4byte <selector>`.
  - heuristic tool: `heimdall-rs`, `EVMole`, `WhatsABI`, `Panoramix`, `rattle` (if present); else a pure-Python
    selector-recog engine (EQ, ADD, SSTORE, CALL, POP, JUMPI dispatch table) → selector → function name.
- Native path (when available): Ghidra / radare2 (`r2 -q -c 'aa; afl'`), `r2dec`, `pycdc` for Python bytecode
  (`.pyc` → disassembly/decompile).
- Output: selector table, storage layout hints, entry-point candidates, "rev-ish" summary; never decompiles to
  proprietary keys.
- Acceptance: built-in `apple` contract with `selector` `811243b3` → recognizer emits `owner()`-ish note + storage
  indices; no false "private key" claims.

### 3C. `tools/vector_funds.py` — Against vectors / funds "aivable to get"
- "Smell funds": evidence-only exposure scoring using public on-chain signals (no keys, no moves).
- Public on-chain signals to score:
  - **admin/upgradeable**: `owner()` is a module (proxies, Diamond) → admin dump/upgrade risk.
  - **timelock**: role functions need timelock wait (wash/withdrawal timing).
  - **unbacked mint**: `mint(address, amount)` with no verify → creator can inflate supply.
  - **export/EMV**: `address public export` (creator-owned, unlocked) → funds can be swept by holder.
  - **unlocked LP**: LP with no withdrawal lock → creator can exit, price impact.
  - **token/coin balance**: wallet has large idle ERC-20/SOL/raincheck + unlock schedule.
  - **burn/unlock**: `burn()` vs `mint()` ratio, vesting end.
- Output: a "funds-availability score" (0–100), list of `OPEN`/`LOCKED` flags, remediation.
- Acceptance: address `0xDe0DAFC80d487b8aE652bBF906ac6c6007aE3A5e` (creator-held, unlocked export, 100% supply) →
  100 "maximal single-wallet control / funds-sweep possible" (historical, read-only, no moves).
- Explicit: never claims profit; only flags reachability + trust model.

### 3D. `tools/ctf_agent.py` — CTF/agent pipeline
- STRIATUM-CTF-like closed loop: `plan()` → `protocol_validate()` (schema-gated tool calls) →
  `execute()` (sandboxed tools) → `parse()` (calibrated flag patterns) → `self-correct()`.
- Tools: `solc` AST dump, `cast`, `foundry`, hash/obfuscation decoys, flag detection regex.
- Output: structured solve profile (phases, findings, flag evidence) + confidence.
- Acceptance: happy-path CTF sample (e.g., an Ethereum wargame storage/selector level) yields low-confidence
  flag; the pipeline doesn't over-claim.

### 3E. `tools/base44_agent.py` — base44 agent
- base44.app is the PR/files platform for the open-crypto-puzzles project (base44.app/api/apps/{id}/files/mp/public/{id}/{hash}).
- Endpoints: `POST /api/files/{id}` (upload file content), `POST /api/comments` (comment on PR), `GET /api/files/...` (list).
- A `/base44` sub-command posts a file/content to an app, or comments on a PR.
- Acceptance: smoke test posts a tiny text snippet and reads it back (POST-then-GET roundtrip).

## 4. Dispatch table (exact command patterns the bot will support)
```
/puzzle <plain puzzle>                 -> existing: math/cipher/algebraic/brute/mnemonic/oracle/encoder
/puzzle sc <file.sol or "address 0x...">          -> smart-contract audit
/puzzle rev <text or "addr 0x...">                -> reversing (bytecode/native)
/puzzle vector <contract|addr>                    -> funds-availability odor
/puzzle funds <contract|addr>                     -> same as vector (alias)
/puzzle ctf <text>                                -> CTF/autonomous agent
/puzzle base44 <base44-url-or-file-url>           -> base44 post/comment
```
Optional quick routes: `/sc`, `/rev`, `/vector`, `/ctf`, `/b44`.

## 5. Web research (already gathered — used to pick tools)
- Smart-contract auditing: Slither, Mythril, Aderyn, Semgrep, Solhint, Echidna, Foundry (`forge`/`cast`),
  hevm/echidna (OWASP SC01-SC10). AuditForge multi-engine consensus.
- EVM reversing: heimdall-rs, EVMole, WhatsABI, Panoramix, rattle, Foundry `cast code`/`cast storage`,
  `evm.codes`; native Ghidra/radare2/r2dec/IDA/Binary Ninja (no cracked builds).
- Fund-sourcing / "smell funds": OWASP DeFi Recovery Patterns (atomicity, pause+upgrade, timelock, export,
  cash-out flow, negotiation), on-chain archives/subgraphs/Dune for who-lost-what.
- CTF agents: STRIATUM-CTF (MCP + schema validation + sandboxed tools), PentestAGI, ctf-abacus (trace audit).

## 6. Deployment / verification
1. `python3 tools/contract_audit.py --selftest` → finds reentrancy+tx.origin+unchecked on `tester.sol`.
2. `python3 tools/reverse_analyze.py --selftest` → selector table + storage indices on `apple.sol`.
3. `python3 tools/vector_funds.py --selftest` → known test vector (creator wallet = unlocked = high).
4. `python3 tools/base44_agent.py --selftest` → POST-then-GET roundtrip.
5. `node --check fjf-token/tools/fjf_telegram_bot.js` → syntax clean.
6. End-to-end: send `/puzzle sc /tmp/tester.sol` and `/puzzle vector 0xDe0DAFC80d487b8aE652bBF906ac6c6007aE3A5e`
   against a live Telegram bot instance.

## 7. Scope & risk
- Defensive-only. No private-key decoding, no real exploit, no fund extraction, no flash loans as automation.
- Detection tools can false-positive; the bot clips findings to quoted, evidence-backed lines.
- "Funds aivable to get" is **reachability/trust-only** scoring; it never moves money.
- Fuzzy regex/code paths: keep a positive-control test + a zero-hit control before shipping.
- Tool install tolerance: slither/foundry/heimdall are optional; the bot must still answer with the pure-Python
  engine if any external tool is absent.
