#!/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.
# ==============================================================================
"""Contract Heat Map — Waveprobe visualizer.
Takes the JSON output of evm_bytecode_waveprobe.py and generates an
interactive HTML heat map showing cold/warm/hot regions of a contract.
Usage:
# Pipe from waveprobe
python3 evm_bytecode_waveprobe.py --file contract.hex --json | \
python3 contract_heatmap.py > report.html
# From saved JSON
python3 contract_heatmap.py --input probe_result.json --output report.html
# Direct from bytecode
python3 contract_heatmap.py --bytecode 0x6060... --output report.html
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
# ── HTML Template ────────────────────────────────────────────────────────────
HTML_TEMPLATE = """
Contract Heat Map — Waveprobe v0.1
🧬 Contract Heat Map
SHA-256: {sha256}
Length: {length} bytes |
Chunks: {chunk_count} |
Waveprobe: {version}
{overall_heat}
Overall Heat
{overall_class_upper}
Classification
{cold_count}
🧊 Cold Regions
{warm_count}
🌡️ Warm Regions
{hot_count}
🔥 Hot Regions
Bytecode Heat Map (offset →)
{heat_strip_html}
🧊 Cold (heat < 0.05)
🌡️ Warm (0.05 ≤ heat < 0.25)
🔥 Hot (heat ≥ 0.25)
⚡ KOT Action Cost Estimate
{kot_bar_html}
Estimated traversal cost breakdown by region classification.
Hot regions cost more KOT to interact with (higher probe complexity).
Per-Chunk Analysis
{chunks_html}
Probe Family Response (Chunk 0)
| Probe Family |
Feature Displacement |
Compression Displacement |
{probe_table_html}
"""
# ── Feature names ────────────────────────────────────────────────────────────
FEATURE_NAMES = [
"entropy",
"opcode_dens",
"call_dens",
"ctrl_flow",
"push_ratio",
"jd_spacing",
"repetition",
"compress",
]
FEATURE_COLORS = [
"#8b5cf6", # purple
"#06b6d4", # cyan
"#ef4444", # red
"#f59e0b", # amber
"#10b981", # emerald
"#3b82f6", # blue
"#ec4899", # pink
"#6366f1", # indigo
]
# ── Rendering ────────────────────────────────────────────────────────────────
def _heat_to_color(heat: float) -> str:
"""Map heat value to an RGB color string."""
if heat >= 0.25:
# Hot: red
t = min(1.0, (heat - 0.25) / 0.75)
r = int(239 + t * 16)
g = int(68 - t * 40)
b = int(68 - t * 40)
elif heat >= 0.05:
# Warm: amber
t = (heat - 0.05) / 0.20
r = int(59 + t * 186)
g = int(130 + t * 28)
b = int(246 - t * 178)
else:
# Cold: blue
t = heat / 0.05
r = int(30 + t * 29)
g = int(64 + t * 66)
b = int(175 + t * 71)
return f"rgb({min(255,r)},{min(255,g)},{min(255,b)})"
def _render_heat_strip(data: Dict[str, Any]) -> str:
"""Render the horizontal heat strip cells."""
cells = []
for i, heat in enumerate(data.get("heat_map", [])):
color = _heat_to_color(heat)
cells.append(
f''
)
return "".join(cells)
def _render_kot_bar(data: Dict[str, Any]) -> str:
"""Render the KOT cost estimate bar."""
cold = data.get("cold_region_count", 0)
warm = data.get("warm_region_count", 0)
hot = data.get("high_heat_region_count", 0)
total = cold + warm + hot
if total == 0:
return 'No data
'
# KOT cost weights (cold=1x, warm=4x, hot=16x)
cold_kot = cold * 1
warm_kot = warm * 4
hot_kot = hot * 16
total_kot = cold_kot + warm_kot + hot_kot
parts = []
if cold_kot > 0:
pct = cold_kot / total_kot * 100
parts.append(
f''
f'{cold_kot} KOT ({pct:.0f}%)
'
)
if warm_kot > 0:
pct = warm_kot / total_kot * 100
parts.append(
f''
f'{warm_kot} KOT ({pct:.0f}%)
'
)
if hot_kot > 0:
pct = hot_kot / total_kot * 100
parts.append(
f''
f'{hot_kot} KOT ({pct:.0f}%)
'
)
return "".join(parts)
def _render_feature_bars(features: List[float]) -> str:
"""Render feature bar chart for a chunk."""
bars = []
for i, val in enumerate(features):
name = FEATURE_NAMES[i] if i < len(FEATURE_NAMES) else f"f{i}"
color = FEATURE_COLORS[i] if i < len(FEATURE_COLORS) else "#888"
pct = min(100, max(0, val * 100))
bars.append(
f''
f'
{name}
'
f'
'
f'
{val:.3f}
'
f'
'
)
return "".join(bars)
def _render_chunk_card(idx: int, chunk: Dict[str, Any]) -> str:
"""Render a single chunk detail card."""
cls = chunk.get("classification", "cold")
badge_cls = f"badge-{cls}"
agg = chunk.get("aggregate", {})
features = chunk.get("base_features", [])
return (
f''
f''
f'
'
f'
Heat
'
f'
{agg.get("heat", 0):.6f}
'
f'
Sensitivity
'
f'
{agg.get("sensitivity", 0):.6f}
'
f'
Anisotropy
'
f'
{agg.get("anisotropy", 0):.4f}
'
f'
Comp. Sens.
'
f'
{agg.get("compression_sensitivity", 0):.6f}
'
f'
'
f'
'
f'{_render_feature_bars(features)}'
f'
'
f'
'
)
def _render_chunks(data: Dict[str, Any]) -> str:
"""Render all chunk cards."""
cards = []
for i, chunk in enumerate(data.get("chunks", [])):
cards.append(_render_chunk_card(i, chunk))
return "".join(cards)
def _render_probe_table(data: Dict[str, Any]) -> str:
"""Render probe response table for chunk 0."""
chunks = data.get("chunks", [])
if not chunks:
return "| No chunks |
"
rows = []
for probe in chunks[0].get("probes", []):
mag = probe.get("feature_displacement_magnitude", 0)
comp = probe.get("compression_displacement", 0)
# Color intensity by magnitude
mag_color = _heat_to_color(min(0.5, mag * 10))
comp_color = _heat_to_color(min(0.5, comp * 10))
rows.append(
f''
f'| {probe.get("probe_family", "")} | '
f'{mag:.8f} | '
f'{comp:.8f} | '
f'
'
)
return "".join(rows)
def render_heatmap(data: Dict[str, Any]) -> str:
"""Render the full heat map HTML from waveprobe JSON data."""
overall_class = data.get("overall_classification", "cold")
return HTML_TEMPLATE.format(
sha256=data.get("bytecode_sha256", "unknown"),
length=data.get("total_length", 0),
chunk_count=data.get("chunk_count", 0),
version=data.get("waveprobe_version", "0.1-evm"),
overall_heat=f'{data.get("overall_heat", 0):.6f}',
overall_class=overall_class,
overall_class_upper=overall_class.upper(),
cold_count=data.get("cold_region_count", 0),
warm_count=data.get("warm_region_count", 0),
hot_count=data.get("high_heat_region_count", 0),
heat_strip_html=_render_heat_strip(data),
kot_bar_html=_render_kot_bar(data),
chunks_html=_render_chunks(data),
probe_table_html=_render_probe_table(data),
probe_data_json=json.dumps(data),
)
# ── CLI ──────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Contract Heat Map — Waveprobe visualizer"
)
parser.add_argument("--input", "-i",
help="Path to waveprobe JSON output file")
parser.add_argument("--bytecode", "-b",
help="Hex-encoded bytecode (runs waveprobe first)")
parser.add_argument("--bytecode-file", "-f",
help="File containing hex-encoded bytecode")
parser.add_argument("--output", "-o",
help="Output HTML file path (default: stdout)")
args = parser.parse_args()
probe_data: Optional[Dict[str, Any]] = None
if args.input:
with open(args.input) as f:
probe_data = json.load(f)
elif args.bytecode or args.bytecode_file:
# Import and run the waveprobe
sys.path.insert(0, str(Path(__file__).parent))
from evm_bytecode_waveprobe import EVMBytecodeWaveprobe
if args.bytecode_file:
bc_hex = Path(args.bytecode_file).read_text().strip()
else:
bc_hex = args.bytecode
probe = EVMBytecodeWaveprobe(bytecode_hex=bc_hex)
result = probe.analyze()
probe_data = json.loads(probe.to_json(result))
else:
# Read from stdin
raw = sys.stdin.read().strip()
if not raw:
print("Error: no input. Use --input, --bytecode, or pipe JSON.",
file=sys.stderr)
sys.exit(1)
probe_data = json.loads(raw)
html = render_heatmap(probe_data)
if args.output:
Path(args.output).write_text(html)
print(f"Wrote heat map to {args.output}", file=sys.stderr)
else:
print(html)