Research-Stack/5-Applications/tools-scripts/crypto/mint_claim_agent.py

152 lines
6 KiB
Python

#!/usr/bin/env python3
# ==============================================================================
# COPYRIGHT NO ONE EVERYWHERE LLC (WYOMING HOLDING COMPANY)
# PROJECT: SOVEREIGN STACK
# This artifact is entirely proprietary and cryptographically proven.
# Open-Source usage requires explicit permission from Brandon Scott Schneider.
# ==============================================================================
"""Mint/claim agent: create KOT mint intents from tunnel probe sidecars.
Behavior:
- Scan a sidecar directory for `*.tunnel_probe.json` files.
- For each with `status=="ok"`, validate wavestate sha256 against the rebuilt payload file.
- Read `funding_policy` from `egress_surface.json` to compute mint amounts.
- Emit mint intent JSON files under `5-Applications/out/omnitoken_bridge/mint_intents/`.
- Optional `--execute` will append a ledger entry to `5-Applications/out/omnitoken_bridge/ledger.log` (placeholder for `LEDGER_COMMIT`).
This is a minimal, auditable prototype — adjust allocation formula to match real economics.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Any
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_SIDECAR_DIR = Path.home() / "Gdrive" / "_omnitoken_probe"
SURFACE_PATH = ROOT / "out" / "omnitoken_bridge" / "egress_surface.json"
INTENTS_DIR = ROOT / "out" / "omnitoken_bridge" / "mint_intents"
LEDGER_LOG = ROOT / "out" / "omnitoken_bridge" / "ledger.log"
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
def load_surface(surface_path: Path) -> Dict[str, Any]:
if not surface_path.exists():
raise FileNotFoundError(f"surface not found: {surface_path}")
return json.loads(surface_path.read_text(encoding="utf-8"))
def compute_mint_amount(policy: Dict[str, Any], wavestate: Dict[str, Any]) -> int:
# Tunable formula:
# - `mint_unit`: one of KB, MB, GB (default MB)
# - `mint_amount_per_unit`: tokens to mint per unit (falls back to mint_amount_per_kg)
bytes_ = int(wavestate.get("bytes", 0))
unit = str(policy.get("mint_unit", "MB")).upper()
unit_map = {"KB": 1024, "MB": 1024 * 1024, "GB": 1024 * 1024 * 1024}
unit_bytes = unit_map.get(unit, 1024 * 1024)
per_unit = int(policy.get("mint_amount_per_unit", policy.get("mint_amount_per_kg", 1000)))
# compute number of units (round up small payloads to 1 unit)
units = max(1, bytes_ // unit_bytes)
# apply soft cap to prevent huge mints for very large files (policy can override)
soft_cap_units = int(policy.get("mint_soft_cap_units", 1000))
if units > soft_cap_units:
units = soft_cap_units
return units * per_unit
def make_intent(sidecar: Dict[str, Any], policy: Dict[str, Any], surface: Dict[str, Any]) -> Dict[str, Any]:
wavestate = sidecar.get("wavestate") or {}
amount = compute_mint_amount(policy, wavestate)
intent = {
"intent_id": f"mint-{sidecar.get('register_id','')}-{int(datetime.now().timestamp())}",
"token": policy.get("token", "KOT"),
"amount": amount,
"unit": "KOT",
"source_register_id": sidecar.get("register_id"),
"wavestate": wavestate,
"rebuilt_path": sidecar.get("rebuilt_path"),
"created_utc": utc_now(),
"status": "pending",
"notes": "auto-generated by mint_claim_agent prototype",
}
return intent
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--sidecar-dir", default=str(DEFAULT_SIDECAR_DIR))
ap.add_argument("--surface", default=str(SURFACE_PATH))
ap.add_argument("--out-dir", default=str(INTENTS_DIR))
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--execute", action="store_true", help="Append ledger entries (placeholder) and mark intents as executed")
args = ap.parse_args()
sidecar_dir = Path(os.path.expanduser(args.sidecar_dir))
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
surface = load_surface(Path(args.surface))
policy = surface.get("funding_policy") or {}
sidecars = sorted(sidecar_dir.glob("*.tunnel_probe.json"))
if not sidecars:
print("No sidecars found.")
return
for sc in sidecars:
try:
payload = json.loads(sc.read_text(encoding="utf-8"))
except Exception:
print(f"skipping invalid sidecar: {sc}")
continue
if payload.get("status") != "ok":
print(f"skipping non-ok sidecar: {sc.name}")
continue
wavestate = payload.get("wavestate") or {}
rebuilt = Path(payload.get("rebuilt_path") or "")
verified = False
if rebuilt.exists() and wavestate.get("sha256"):
actual = sha256_file(rebuilt)
verified = actual == wavestate.get("sha256")
if not verified:
print(f"warning: wavestate mismatch or rebuilt file missing for {sc.name}")
intent = make_intent(payload, policy, surface)
intent_path = out_dir / f"{intent['intent_id']}.json"
intent_path.write_text(json.dumps(intent, indent=2) + "\n", encoding="utf-8")
print(f"wrote intent: {intent_path} verified={verified}")
if args.execute:
# Append to local ledger log (blockchain anchoring requires external integration)
entry = {"time": utc_now(), "intent_id": intent["intent_id"], "amount": intent["amount"], "token": intent["token"]}
with LEDGER_LOG.open("a", encoding="utf-8") as fh:
fh.write(json.dumps(entry) + "\n")
intent["status"] = "executed"
intent_path.write_text(json.dumps(intent, indent=2) + "\n", encoding="utf-8")
print(f"executed intent (ledger append): {intent['intent_id']}")
if __name__ == "__main__":
main()