AI-powered on-chain compliance agent for Hedera Token Service
HederaShield is a real-time compliance monitoring system built natively on Hedera. It watches HTS token transfers via the Mirror Node API, applies configurable rule-based and AI-powered analysis to detect suspicious activity, publishes immutable audit logs to HCS, and can automatically enforce actions (freeze, wipe, KYC revoke) through Hedera SDK.
Built for the Hedera Apex Hackathon 2026.
- Start the app:
docker compose up --build
- Open the dashboard:
http://localhost:8000 - Generate deterministic judge-visible artifacts:
./scripts/run-e2e-simulation.py
- Review judging map and submission packet:
docs/JUDGING_ALIGNMENT.mdSUBMISSION.mdHEDERA_PORTAL_SUBMISSION_PACKET.md
CI parity snapshot (2026-03-13 UTC):
ruff check hedera_shield/ tests/-> PASSpytest tests/ -v --tb=short-> 132 passed, 6 skippedpython3 -m hedera_shield.preflight --offline-> PASS (preflight diagnostics)./scripts/run-integration-harness.sh --mode mock ...-> PASS- Docker image build +
/healthcontainer check -> PASS
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HederaShield β
β β
β ββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββ β
β β Mirror Node βββββΆβ Scanner Module βββββΆβ Compliance β β
β β REST API β β β β Engine β β
β β β β β’ Token xfers β β β β
β β /api/v1/ β β β’ HBAR xfers β β 8 Rules: β β
β β transactionsβ β β’ NFT xfers β β β’ Large TX β β
β β accounts β β β’ Pagination β β β’ Velocity β β
β β tokens β β β’ Retry+Backoff β β β’ Sanctions β β
β β topics β β β β β’ Round Num β β
β ββββββββββββββββ ββββββββββββββββββββ β β’ Rapid β β
β β β’ Structure β β
β ββββββββββββββββ ββββββββββββββββββββ β β’ Dormant β β
β β Claude AI ββββββ AI Analyzer ββββββ β’ Wash Trd β β
β β (Anthropic) β β β β β β
β β βββββΆβ Risk scoring β ββββββββ¬ββββββββ β
β β Contextual β β NL explanations β β β
β β analysis β β Action recs β βΌ β
β ββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββ β
β β Alerts β β
β ββββββββββββββββ ββββββββββββββββββββ β Database β β
β β Hedera SDK ββββββ Enforcer ββββββ€ β β
β β β β β ββββββββ¬ββββββββ β
β β TokenFreeze β β β’ Freeze accts β β β
β β TokenWipe β β β’ Wipe tokens β βΌ β
β β TokenRevoke β β β’ Revoke KYC β ββββββββββββββββ β
β β KYC β β β’ Dry-run mode β β HCS Reporterβ β
β ββββββββββββββββ ββββββββββββββββββββ β β β
β β Immutable β β
β ββββββββββββββββ ββββββββββββββββββββ β audit trail β β
β β FastAPI βββββΆβ Dashboard β β on-chain β β
β β REST API β β (Single-page) β ββββββββββββββββ β
β β β β β β
β β /alerts β β Real-time view β β
β β /rules β β of alerts, β β
β β /enforce β β rules, and β β
β β /status β β enforcement β β
β ββββββββββββββββ ββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Polls Hedera Mirror Node REST API for HTS token transfers, HBAR transfers, and NFT movements
- Automatic pagination across large result sets
- Exponential backoff retry on transient failures (429, 5xx)
- Configurable polling interval
| Rule | Description | Default Severity |
|---|---|---|
| Large Transfer | Flags transfers exceeding configurable threshold (per-token overrides) | HIGH |
| Velocity Check | Detects excessive transfer frequency from a single account | MEDIUM |
| Sanctioned Address | Matches sender/receiver against OFAC-style sanctions list | CRITICAL |
| Round Number | Flags suspiciously round-number transfers (structuring indicator) | MEDIUM |
| Rapid Succession | Detects bot-driven rapid-fire transfers within seconds | HIGH |
| Structuring (Anti-Smurfing) | Catches transfers clustered just below reporting threshold | HIGH |
| Dormant Account Reactivation | Flags sudden activity from long-inactive accounts | MEDIUM |
| Cross-Token Wash Trading | Detects same-pair transfers across multiple token IDs | HIGH |
- Uses Claude (Anthropic) for contextual risk scoring
- Natural language explanations of flagged transactions
- Adaptive risk assessment with recommended enforcement actions
- Graceful fallback when AI is unavailable
- Freeze accounts via
TokenFreezeTransaction - Wipe tokens via
TokenWipeTransaction - Revoke KYC via
TokenRevokeKycTransaction - Dry-run mode by default for safety
- Full Hedera SDK integration
- Publishes every compliance alert to an HCS topic
- Creates tamper-proof, timestamped audit log on the Hedera public ledger
- Fetchable via Mirror Node for dashboard display
- JSON-structured messages with version field for schema evolution
- Single-page web app with auto-refresh (10s)
- Alert severity badges, risk score bars, expandable details
- Rule management (add/remove/toggle via UI)
- Enforcement action panel
- Transaction browser with Mirror Node integration
- Dark theme, responsive design
- YAML-based rule configuration with hot-reload
- Per-token threshold overrides
- External sanctions list file support
- Environment-based settings (12-factor app)
- Python 3.12+
- Hedera testnet account (portal.hedera.com)
- Anthropic API key (optional, for AI analysis)
git clone https://github.com/your-username/hedera-shield.git
cd hedera-shield
cp .env.example .env
# Edit .env with your credentials
docker compose up --buildgit clone https://github.com/your-username/hedera-shield.git
cd hedera-shield
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your credentials
# Run the API server
python -m hedera_shield.apiOpen http://localhost:8000 for the dashboard.
# Unit tests (no network required)
pytest tests/ -v
# Include integration tests against testnet Mirror Node
HEDERA_SHIELD_RUN_INTEGRATION=1 pytest tests/ -v- Demo narration script (3-5 minutes):
DEMO_SCRIPT.md - Final 3-5 minute demo flow (problem -> setup -> findings -> HCS -> impact):
DEMO_RUNBOOK.md - Apex-ready checklist:
SUBMISSION_CHECKLIST.md - Final release gate + operator handoff plan:
RELEASE_READINESS.md - End-to-end portal rehearsal + expected checkpoints:
SUBMISSION_DRY_RUN.md - Hackathon form field mapping packet:
SUBMISSION_PACKET.md - Portal-ready copy/paste packet for submission form fields:
HEDERA_PORTAL_SUBMISSION_PACKET.md - Integration/runtime failure quick reference:
TROUBLESHOOTING_QUICKREF.md - Fast local smoke verification:
./scripts/smoke.sh
Run one command to probe every external dependency and get a structured pass/fail report:
# Offline mode β validate credentials format, SDK availability (no network)
python3 -m hedera_shield.preflight --offline
python3 -m hedera_shield.preflight --env-file .env.testnet --offline
# Full mode β also probe Mirror Node, operator account, Anthropic API
python3 -m hedera_shield.preflight --env-file .env.testnet
# JSON output for automation
python3 -m hedera_shield.preflight --env-file .env.testnet --jsonChecks performed:
| Check | What it probes | Requires network |
|---|---|---|
operator_id |
Account ID format (0.0.x) vs placeholder | No |
operator_key |
Key material format vs placeholder | No |
anthropic_api_key |
API key format | No |
network |
Valid network name (testnet/mainnet/previewnet) | No |
hedera_sdk |
Hedera Python SDK importable | No |
mirror_node |
GET /api/v1/transactions?limit=1 | Yes |
account_lookup |
GET /api/v1/accounts/{operator_id} | Yes |
anthropic_api |
POST /v1/messages (minimal ping) | Yes |
Use these assets to prepare and execute the first live testnet integration pass without requiring unavailable credentials:
- Strict preflight gate (must return GREEN before live run):
./scripts/testnet-preflight.sh --env-file .env.testnet - Detailed preflight breakdown (red-yellow-green checks):
./scripts/integration_preflight.sh --env-file .env.testnet - Operator handoff runbook (credentials-ready, funding/token setup, expected outputs, failure modes):
HEDERA_TESTNET_RUNBOOK.md - Copy-paste first live testnet runbook:
docs/INTEGRATION_READY.md - Current blockers and concrete mitigations:
docs/KNOWN_ISSUES_AND_WORKAROUNDS.md - Existing testnet setup reference:
docs/TESTNET_SETUP.md
Quick run:
./scripts/smoke.shExact integration gate/evidence verification:
# A) Requested real mode with missing or placeholder credentials -> deterministic dry-run fallback
ART=artifacts/integration/manual-fallback
./scripts/run-integration-harness.sh --mode real --env-file .env.testnet --artifacts-dir "$ART"
python3 - <<'PY'
import json, pathlib
p = pathlib.Path("artifacts/integration/manual-fallback/report.json")
r = json.loads(p.read_text(encoding="utf-8"))
print("mode=", r["mode"])
print("effective_mode=", r["effective_mode"])
print("dry_run_fallback=", r["dry_run_fallback"])
print("dry_run_reason=", r["dry_run_reason"])
print("harness_status=", r["checks"]["harness"]["status"])
PY
# B) True real-mode run (requires funded, non-placeholder credentials)
ART=artifacts/integration/manual-real
HEDERA_SHIELD_ENABLE_REAL_TESTNET=1 \
./scripts/run-integration-harness.sh --mode real --env-file .env.testnet --artifacts-dir "$ART"
python3 - <<'PY'
import json, pathlib
p = pathlib.Path("artifacts/integration/manual-real/report.json")
r = json.loads(p.read_text(encoding="utf-8"))
print("mode=", r["mode"])
print("effective_mode=", r["effective_mode"])
print("dry_run_fallback=", r["dry_run_fallback"])
print("integration_status=", r["checks"]["integration_pytest"]["status"])
PY# Fast judge-visible compliance simulation (no credentials, offline-safe)
./scripts/run-e2e-simulation.py
# Safe default (credential-free, non-destructive)
./scripts/release-evidence.sh
# Optional: include real testnet artifacts only with explicit opt-in
HEDERA_SHIELD_ENABLE_REAL_TESTNET=1 \
./scripts/release-evidence.sh --env-file .env.testnet --include-real-testnetDefault command behavior:
- Runs
ruff check hedera_shield/ tests/ - Runs
pytest tests/ -v --tb=short - Runs mock harness (
scripts/run-integration-harness.sh --mode mock) - Builds
dist/submission-bundle.zip - Emits
dist/release-evidence-<timestamp>.tar.gzwith logs + artifacts + submission zip
# 1) Fail fast if any required submission docs/artifacts are missing
./scripts/pre_submit_guard.sh
# 2) Verify docs/demo/artifacts readiness
./scripts/submission-readiness.sh
# 3) Verify final draft-referenced docs/artifacts
./scripts/pre-submit-verify.py
# 3b) Print final operator handoff actions and verify portal-required files/checks
./scripts/final_portal_handoff.sh
# 4) Generate final Hedera Apex portal packet (markdown + json)
./scripts/generate-portal-submission-packet.py
# 5) Verify all packet-referenced files/paths exist
./scripts/verify-portal-submission-packet.py
# 6) Capture immutable submission-freeze snapshot manifest (markdown + json)
./scripts/submission-freeze.py
# 7) Verify current artifacts/commit state against latest freeze manifest
./scripts/verify-submission-freeze.py
# 8) Generate consolidated multi-repo sprint push dashboard (read-only by default)
./scripts/sprint-multi-repo-dashboard.py
# Optional: use mirrored GitLab/Hedera/DO config
./scripts/sprint-multi-repo-dashboard.py --repo-config config/sprint-repos.json
# Optional: attempt safe push via sync helper when remote is reachable
./scripts/sprint-multi-repo-dashboard.py --attempt-push
# 9) Attempt one immediate sync + push with bounded retry/backoff
./scripts/sync-and-submit.sh --max-retries 3 --initial-backoff-seconds 2 --max-backoff-seconds 16
# 10) If still blocked, run periodic network-recovery push runner until reachable
./scripts/network-recovery-push-runner.sh --check-interval-seconds 30 --max-checks 20
# Optional: verify behavior without pushing
./scripts/network-recovery-push-runner.sh --dry-run --check-interval-seconds 15 --max-checks 4
# 11) If push remains blocked, create offline handoff package
./scripts/offline-handoff.sh
# 12) Generate a single handoff index for judges (markdown + json)
./scripts/generate-handoff-index.py
# Optional: deterministic timestamp/output path
./scripts/generate-handoff-index.py --timestamp "$(date -u +%Y%m%dT%H%M%SZ)" --output-base-dir artifacts/handoff-index
# 13) Export cross-repo final handoff package (read-only across source repos)
./scripts/final-handoff-export.shOutputs:
dist/submission-readiness-latest.txt(PASS/FAIL checklist summary)dist/pre-submit-verify-latest.txt(PASS/FAIL final draft-linked verification summary)dist/portal-submission/portal-submission-packet-latest.md(portal copy-paste packet markdown)dist/portal-submission/portal-submission-packet-latest.json(portal copy-paste packet json)dist/portal-submission/portal-submission-verify-latest.txt(portal packet reference verification report)dist/portal-submission/portal-submission-verify-latest.json(machine-readable portal packet verification report)dist/submission-freeze/submission-freeze-latest.md(latest immutable freeze manifest markdown)dist/submission-freeze/submission-freeze-latest.json(latest immutable freeze manifest json)dist/submission-freeze/drift-verify-latest.md(latest drift report markdown)dist/submission-freeze/drift-verify-latest.json(latest drift report json)dist/sprint-status/sprint-dashboard-<timestamp>.md(multi-repo dashboard snapshot)dist/sprint-status/sprint-dashboard-<timestamp>.json(machine-readable multi-repo snapshot)dist/sprint-status/sprint-dashboard-latest.md(latest multi-repo dashboard markdown)dist/sprint-status/sprint-dashboard-latest.json(latest multi-repo dashboard json)dist/sync-submit-status-latest.txt(pending commits + remote reachability + exact push error when push fails)dist/network-recovery-push-status-latest.txt(periodic DNS/reachability checks + exact push/network errors + blocked/clear status)dist/network-recovery-push-status-latest.json(machine-readable recovery status for monitoring)artifacts/offline-handoff/<timestamp>/handoff-summary.txtartifacts/offline-handoff/<timestamp>/branch-status.txtartifacts/offline-handoff/<timestamp>/commit-list.txtartifacts/offline-handoff/<timestamp>/offline.bundleartifacts/offline-handoff/<timestamp>/patches/*.patchartifacts/offline-handoff/<timestamp>/RESTORE_APPLY.mdartifacts/handoff-index/<timestamp>/handoff-index.mdartifacts/handoff-index/<timestamp>/handoff-index.jsondist/final-handoff/final-handoff-<timestamp>/master-index.mddist/final-handoff/final-handoff-<timestamp>/master-index.jsondist/final-handoff/final-handoff-latest.mddist/final-handoff/final-handoff-latest.json
Judge-focused docs:
- docs/DEMO_RECORDING_RUNBOOK.md for deterministic 3-minute recording flow (offline-safe default).
- docs/DEMO_NARRATION_3MIN.md for timestamped narration aligned to runbook checkpoints.
- docs/SUBMISSION_FORM_DRAFT_PACK.md for concise copy-paste-ready submission form answers.
- docs/FINAL_SUBMISSION_CHECKLIST.md for final portal submission checklist and evidence gating.
- docs/JUDGING_ALIGNMENT.md for direct mapping from judging criteria to project evidence artifacts.
- DEMO_RUNBOOK.md for final 3-5 minute demo sequence with talking points and evidence checkpoints.
- SUBMISSION_PACKET.md for direct mapping from project content to portal form fields.
- HEDERA_PORTAL_SUBMISSION_PACKET.md for portal-form-ready copy/paste sections.
- TROUBLESHOOTING_QUICKREF.md for exact failure signatures and remediation commands.
- HEDERA_TESTNET_RUNBOOK.md for credentials-ready operator handoff and strict preflight-first live integration flow.
- docs/TESTNET_SETUP.md for full testnet setup/runbook details.
| Variable | Description | Default |
|---|---|---|
HEDERA_SHIELD_HEDERA_NETWORK |
Network: testnet, mainnet, previewnet | testnet |
HEDERA_SHIELD_HEDERA_OPERATOR_ID |
Operator account ID | β |
HEDERA_SHIELD_HEDERA_OPERATOR_KEY |
Operator private key | β |
HEDERA_SHIELD_MIRROR_NODE_URL |
Mirror Node base URL | testnet URL |
HEDERA_SHIELD_LARGE_TRANSFER_THRESHOLD |
Amount threshold for large transfer rule | 10000 |
HEDERA_SHIELD_VELOCITY_MAX_TRANSFERS |
Max transfers in velocity window | 50 |
HEDERA_SHIELD_MONITORED_TOKEN_IDS |
JSON array of token IDs to monitor | [] |
HEDERA_SHIELD_SANCTIONED_ADDRESSES |
JSON array of sanctioned addresses | [] |
HEDERA_SHIELD_ANTHROPIC_API_KEY |
Anthropic API key for Claude AI | β |
Edit config/rules.yaml to customize rule parameters, enable/disable rules, and set per-token overrides. See the file for detailed documentation of each rule.
docker compose up --build
# or: python -m hedera_shield.apiOpen http://localhost:8000 β see the live dashboard with status, alerts, and rules.
curl http://localhost:8000/rules | python -m json.toolcurl "http://localhost:8000/transactions?token_id=0.0.YOUR_TOKEN&limit=10" | python -m json.tool./scripts/run-e2e-simulation.pyOutputs:
artifacts/demo/e2e-simulation/<timestamp>/report.jsonartifacts/demo/e2e-simulation/<timestamp>/report.md
curl -X POST http://localhost:8000/enforce \
-H "Content-Type: application/json" \
-d '{"action": "freeze", "token_id": "0.0.5555", "account_id": "0.0.1111"}'Response: {"status": "dry_run", ...} β no real blockchain action in dry-run mode.
# List alerts
curl http://localhost:8000/alerts | python -m json.tool
# Resolve one
curl -X POST http://localhost:8000/alerts/{ALERT_ID}/resolve| Endpoint | Method | Description |
|---|---|---|
/ |
GET | Dashboard UI |
/health |
GET | Health check |
/preflight |
GET | Preflight diagnostics (probe all dependencies) |
/status |
GET | System status and stats |
/alerts |
GET | List alerts (optional ?unresolved_only=true) |
/alerts/{id}/resolve |
POST | Resolve an alert |
/rules |
GET | List compliance rules |
/rules |
POST | Add a new rule |
/rules/{id} |
DELETE | Remove a rule |
/transactions |
GET | Fetch transfers from Mirror Node |
/enforce |
POST | Execute enforcement action |
/docs |
GET | Interactive API docs (Swagger) |
hedera-shield/
βββ hedera_shield/
β βββ __init__.py # Package init, logging setup
β βββ api.py # FastAPI REST API + dashboard serving
β βββ compliance.py # 8-rule compliance engine
β βββ scanner.py # Mirror Node poller (tokens, HBAR, NFTs)
β βββ enforcer.py # HTS enforcement (freeze/wipe/KYC)
β βββ hcs_reporter.py # HCS audit trail publisher
β βββ ai_analyzer.py # Claude AI risk analysis
β βββ config.py # Environment-based settings
β βββ preflight.py # Unified preflight diagnostics (python -m hedera_shield.preflight)
β βββ models.py # Pydantic data models
β βββ rules_config.py # YAML rule loader
β βββ logging_config.py # Structured JSON logging
β βββ static/
β βββ dashboard.html # Single-page dashboard
βββ config/
β βββ rules.yaml # Compliance rule configuration
β βββ sanctions.txt # OFAC-style sanctions list
βββ tests/
β βββ test_compliance.py # Compliance engine tests
β βββ test_scanner.py # Scanner tests (mocked HTTP)
β βββ test_api.py # API endpoint tests
β βββ test_new_rules.py # New rules + HCS tests
β βββ test_integration_testnet.py # Live testnet tests
βββ demo/
β βββ simulate_alerts.py # Alert simulation script
β βββ walkthrough.md # Demo walkthrough guide
β βββ sample_alerts.json # Sample alert data
β βββ sample_hts_events.json # Sample HTS transfer stream for E2E simulation
βββ scripts/
β βββ run-e2e-simulation.py # Offline end-to-end simulation (events -> rules -> HCS artifact)
βββ Dockerfile
βββ docker-compose.yml
βββ requirements.txt
βββ .env.example
- Python 3.12+ with type hints and async/await
- FastAPI β REST API framework
- Pydantic v2 β data validation and serialization
- httpx β async HTTP client for Mirror Node
- Hedera SDK β native HTS operations (freeze, wipe, KYC)
- Anthropic Claude β AI-powered risk analysis
- PyYAML β configuration management
- pytest + pytest-asyncio β test framework
- Docker β containerized deployment
MIT
Built with β€οΈ for the Hedera ecosystem