Upload leviathan.py with huggingface_hub
Browse files- leviathan.py +135 -170
leviathan.py
CHANGED
|
@@ -1,51 +1,35 @@
|
|
| 1 |
"""
|
| 2 |
-
🔱
|
| 3 |
Pure NumPy inference. Zero PyTorch dependency.
|
| 4 |
|
| 5 |
-
Takes 2-channel 256x256 EVM execution manifolds and classifies
|
| 6 |
-
THREAT (1.0) vs CLEAN (0.0) via CNN + ZKAEDI PRIME bistable refinement.
|
| 7 |
-
|
| 8 |
Architecture:
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
Manifold encoding:
|
| 18 |
-
EVM traces are Hilbert-curve-encoded into 256x256 spatial manifolds
|
| 19 |
-
where spatial locality = execution locality.
|
| 20 |
-
|
| 21 |
-
Validated results:
|
| 22 |
-
Gnosis Multisig -> 0.0000 (CLEAN)
|
| 23 |
-
SWC-107 reentrancy -> 1.0000 (THREAT)
|
| 24 |
-
SWC-112 delegatecall -> 1.0000 (THREAT)
|
| 25 |
-
SWC-101 overflow -> 1.0000 (THREAT)
|
| 26 |
-
Cross-fn reentrancy -> 1.0000 (THREAT)
|
| 27 |
-
Flash loan manip -> 1.0000 (THREAT)
|
| 28 |
|
| 29 |
Usage:
|
| 30 |
from leviathan import Leviathan
|
| 31 |
model = Leviathan.from_safetensors("leviathan_v2_session_trained.safetensors")
|
| 32 |
-
|
| 33 |
-
|
| 34 |
"""
|
| 35 |
from __future__ import annotations
|
| 36 |
import numpy as np
|
| 37 |
from pathlib import Path
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
PRIME_ETA = 3.50
|
| 42 |
PRIME_GAMMA = 0.30
|
| 43 |
-
PRIME_BETA
|
| 44 |
PRIME_SIGMA = 0.05
|
| 45 |
-
|
| 46 |
THREAT_THRESHOLD = 0.90
|
| 47 |
BENIGN_THRESHOLD = 0.10
|
| 48 |
-
NEGATIVE_FIXED_POINT = -3.054
|
| 49 |
|
| 50 |
|
| 51 |
def _conv2d(x, weight, bias):
|
|
@@ -76,106 +60,25 @@ def _downsample(field, target):
|
|
| 76 |
if H == target and W == target:
|
| 77 |
return field
|
| 78 |
bh, bw = H // target, W // target
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
return cropped.reshape(target, bh, target, bw).mean(axis=(1, 3))
|
| 81 |
|
| 82 |
|
| 83 |
-
def
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
while s < n:
|
| 87 |
-
rx = 1 if (d & 2) else 0
|
| 88 |
-
ry = 1 if ((d & 1) ^ rx) else 0
|
| 89 |
-
if ry == 0:
|
| 90 |
-
if rx == 1:
|
| 91 |
-
x = s - 1 - x
|
| 92 |
-
y = s - 1 - y
|
| 93 |
-
x, y = y, x
|
| 94 |
-
x += s * rx
|
| 95 |
-
y += s * ry
|
| 96 |
-
d >>= 2
|
| 97 |
-
s <<= 1
|
| 98 |
-
return x, y
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
_HILBERT_LUT_256 = None
|
| 102 |
-
|
| 103 |
-
def encode_trace_to_manifold(opcode_energies, stack_depths, size=256):
|
| 104 |
-
"""Encode EVM trace -> 2-channel 256x256 manifold via Hilbert curve."""
|
| 105 |
-
global _HILBERT_LUT_256
|
| 106 |
-
if _HILBERT_LUT_256 is None:
|
| 107 |
-
_HILBERT_LUT_256 = np.array([_hilbert_d2xy(size, d) for d in range(size * size)])
|
| 108 |
-
|
| 109 |
-
N = len(opcode_energies)
|
| 110 |
-
total_cells = size * size
|
| 111 |
-
H = np.zeros((size, size), dtype=np.float32)
|
| 112 |
-
V = np.zeros((size, size), dtype=np.float32)
|
| 113 |
-
|
| 114 |
-
for i in range(min(N, total_cells)):
|
| 115 |
-
x, y = _HILBERT_LUT_256[i]
|
| 116 |
-
H[x, y] += opcode_energies[i]
|
| 117 |
-
V[x, y] += stack_depths[i]
|
| 118 |
-
|
| 119 |
-
if N > total_cells:
|
| 120 |
-
for i in range(total_cells, N):
|
| 121 |
-
x, y = _HILBERT_LUT_256[i % total_cells]
|
| 122 |
-
H[x, y] += opcode_energies[i]
|
| 123 |
-
V[x, y] += stack_depths[i]
|
| 124 |
-
|
| 125 |
-
if H.max() > 0:
|
| 126 |
-
H /= H.max()
|
| 127 |
-
if V.max() > 0:
|
| 128 |
-
V /= V.max()
|
| 129 |
-
|
| 130 |
-
try:
|
| 131 |
-
from scipy.ndimage import gaussian_filter
|
| 132 |
-
H = gaussian_filter(H, sigma=1.5).astype(np.float32)
|
| 133 |
-
V = gaussian_filter(V, sigma=1.5).astype(np.float32)
|
| 134 |
-
except ImportError:
|
| 135 |
-
pass # scipy optional — skip smoothing
|
| 136 |
-
|
| 137 |
-
return H, V
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
def prime_refine(raw_score, iterations=PRIME_ITERATIONS, eta=PRIME_ETA,
|
| 141 |
-
gamma=PRIME_GAMMA, beta=PRIME_BETA, sigma=PRIME_SIGMA, seed=42):
|
| 142 |
-
"""
|
| 143 |
-
ZKAEDI PRIME bistable attractor refinement.
|
| 144 |
-
Maps CNN raw score to committed THREAT or CLEAN via Hamiltonian evolution.
|
| 145 |
-
Fixed points: H* = -3.054 (BENIGN) and H* = +3.054 (THREAT).
|
| 146 |
-
"""
|
| 147 |
-
rng = np.random.default_rng(seed)
|
| 148 |
-
H = (raw_score - 0.5) * 6.0
|
| 149 |
-
for _ in range(iterations):
|
| 150 |
-
sig = 1.0 / (1.0 + np.exp(-gamma * H))
|
| 151 |
-
noise = rng.normal(0, 1 + beta * abs(H)) * sigma
|
| 152 |
-
H = H + eta * H * sig + noise
|
| 153 |
-
H = np.clip(H, -10.0, 10.0)
|
| 154 |
-
|
| 155 |
-
refined = 1.0 / (1.0 + np.exp(-H))
|
| 156 |
-
if refined > THREAT_THRESHOLD:
|
| 157 |
-
verdict, committed = "THREAT", True
|
| 158 |
-
elif refined < BENIGN_THRESHOLD:
|
| 159 |
-
verdict, committed = "CLEAN", True
|
| 160 |
-
else:
|
| 161 |
-
verdict, committed = "UNCERTAIN", False
|
| 162 |
-
|
| 163 |
-
return {
|
| 164 |
-
"raw_score": float(raw_score),
|
| 165 |
-
"prime_H": float(H),
|
| 166 |
-
"refined_score": float(refined),
|
| 167 |
-
"verdict": verdict,
|
| 168 |
-
"committed": committed,
|
| 169 |
-
"iterations": iterations,
|
| 170 |
-
}
|
| 171 |
|
| 172 |
|
| 173 |
class Leviathan:
|
| 174 |
"""
|
| 175 |
Leviathan v2 — EVM Exploit Topology Classifier.
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
"""
|
| 180 |
|
| 181 |
def __init__(self, weights):
|
|
@@ -194,43 +97,104 @@ class Leviathan:
|
|
| 194 |
return cls(load_file(str(path)))
|
| 195 |
|
| 196 |
@classmethod
|
| 197 |
-
def
|
| 198 |
-
|
| 199 |
-
path = hf_hub_download(repo_id, "leviathan_v2_session_trained.safetensors")
|
| 200 |
-
return cls.from_safetensors(path)
|
| 201 |
|
| 202 |
-
def
|
|
|
|
|
|
|
|
|
|
| 203 |
h = _relu(_conv2d(x, self.conv0_w, self.conv0_b))
|
| 204 |
h = _relu(_conv2d(h, self.conv1_w, self.conv1_b))
|
| 205 |
-
h = h.reshape(
|
| 206 |
h = _relu(_linear(h, self.fc1_w, self.fc1_b))
|
| 207 |
h = _linear(h, self.fc2_w, self.fc2_b)
|
| 208 |
-
return
|
| 209 |
-
|
| 210 |
-
def
|
| 211 |
-
"""
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
def __repr__(self):
|
| 232 |
-
return (f"Leviathan(
|
| 233 |
-
f"params=264,897,
|
|
|
|
| 234 |
|
| 235 |
|
| 236 |
if __name__ == "__main__":
|
|
@@ -239,21 +203,22 @@ if __name__ == "__main__":
|
|
| 239 |
model = Leviathan.from_safetensors(path)
|
| 240 |
print(model)
|
| 241 |
|
| 242 |
-
print("\n
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
result = model.audit(
|
| 246 |
-
print(f"
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
🔱 Leviathan v2 — EVM Exploit Topology Classifier
|
| 3 |
Pure NumPy inference. Zero PyTorch dependency.
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
Architecture:
|
| 6 |
+
EVM Trace → Hilbert Encoder → 256×256 Manifold
|
| 7 |
+
→ Downsample 20×20 → Conv2d(2→16) → Conv2d(16→16)
|
| 8 |
+
→ FC(4096→64) → FC(64→1) → Raw Score
|
| 9 |
+
→ PRIME Bistable Attractor Refinement → THREAT/CLEAN
|
| 10 |
+
|
| 11 |
+
Channels:
|
| 12 |
+
0: Opcode energy density (H activator field)
|
| 13 |
+
1: Stack depth / state mutation intensity (V inhibitor field)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
Usage:
|
| 16 |
from leviathan import Leviathan
|
| 17 |
model = Leviathan.from_safetensors("leviathan_v2_session_trained.safetensors")
|
| 18 |
+
score = model.predict_manifold(H_256, V_256)
|
| 19 |
+
verdict = model.prime_refine(score)
|
| 20 |
"""
|
| 21 |
from __future__ import annotations
|
| 22 |
import numpy as np
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
+
CNN_SPATIAL = 20
|
| 26 |
+
PRIME_ETA = 3.50
|
|
|
|
| 27 |
PRIME_GAMMA = 0.30
|
| 28 |
+
PRIME_BETA = 0.10
|
| 29 |
PRIME_SIGMA = 0.05
|
| 30 |
+
PRIME_T = 256
|
| 31 |
THREAT_THRESHOLD = 0.90
|
| 32 |
BENIGN_THRESHOLD = 0.10
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
def _conv2d(x, weight, bias):
|
|
|
|
| 60 |
if H == target and W == target:
|
| 61 |
return field
|
| 62 |
bh, bw = H // target, W // target
|
| 63 |
+
if bh < 1 or bw < 1:
|
| 64 |
+
xi = np.round(np.linspace(0, H-1, target)).astype(int)
|
| 65 |
+
yi = np.round(np.linspace(0, W-1, target)).astype(int)
|
| 66 |
+
return field[np.ix_(xi, yi)]
|
| 67 |
+
cropped = field[:bh*target, :bw*target]
|
| 68 |
return cropped.reshape(target, bh, target, bw).mean(axis=(1, 3))
|
| 69 |
|
| 70 |
|
| 71 |
+
def _sigmoid(x, gamma):
|
| 72 |
+
clamped = max(-500.0, min(500.0, -gamma * x))
|
| 73 |
+
return 1.0 / (1.0 + np.exp(clamped))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
|
| 76 |
class Leviathan:
|
| 77 |
"""
|
| 78 |
Leviathan v2 — EVM Exploit Topology Classifier.
|
| 79 |
|
| 80 |
+
Two-channel CNN on Hamiltonian energy manifolds from EVM traces.
|
| 81 |
+
256x256 manifold -> downsample 20x20 -> CNN -> score -> PRIME refine.
|
| 82 |
"""
|
| 83 |
|
| 84 |
def __init__(self, weights):
|
|
|
|
| 97 |
return cls(load_file(str(path)))
|
| 98 |
|
| 99 |
@classmethod
|
| 100 |
+
def from_dict(cls, weights):
|
| 101 |
+
return cls(weights)
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
def forward(self, x):
|
| 104 |
+
if x.ndim == 3:
|
| 105 |
+
x = x[None]
|
| 106 |
+
B = x.shape[0]
|
| 107 |
h = _relu(_conv2d(x, self.conv0_w, self.conv0_b))
|
| 108 |
h = _relu(_conv2d(h, self.conv1_w, self.conv1_b))
|
| 109 |
+
h = h.reshape(B, -1)
|
| 110 |
h = _relu(_linear(h, self.fc1_w, self.fc1_b))
|
| 111 |
h = _linear(h, self.fc2_w, self.fc2_b)
|
| 112 |
+
return h
|
| 113 |
+
|
| 114 |
+
def predict(self, H_field, V_field):
|
| 115 |
+
"""Score from 20x20 field patches (CNN native resolution)."""
|
| 116 |
+
x = np.stack([H_field, V_field])[None].astype(np.float32)
|
| 117 |
+
return float(self.forward(x)[0, 0])
|
| 118 |
+
|
| 119 |
+
def predict_manifold(self, H_256, V_256):
|
| 120 |
+
"""Score from full 256x256 EVM execution manifold. Auto-downsamples."""
|
| 121 |
+
H_down = _downsample(H_256.astype(np.float32), CNN_SPATIAL)
|
| 122 |
+
V_down = _downsample(V_256.astype(np.float32), CNN_SPATIAL)
|
| 123 |
+
return self.predict(H_down, V_down)
|
| 124 |
+
|
| 125 |
+
def predict_region(self, H_field, V_field, region=None):
|
| 126 |
+
"""Score a region of any-sized energy landscape."""
|
| 127 |
+
s = CNN_SPATIAL
|
| 128 |
+
if region is not None:
|
| 129 |
+
rx, ry, rw, rh = region
|
| 130 |
+
H_crop = H_field[rx:rx+rw, ry:ry+rh]
|
| 131 |
+
V_crop = V_field[rx:rx+rw, ry:ry+rh]
|
| 132 |
+
else:
|
| 133 |
+
cx = max(0, (H_field.shape[0] - s) // 2)
|
| 134 |
+
cy = max(0, (H_field.shape[1] - s) // 2)
|
| 135 |
+
H_crop = H_field[cx:cx+s, cy:cy+s]
|
| 136 |
+
V_crop = V_field[cx:cx+s, cy:cy+s]
|
| 137 |
+
H_down = _downsample(H_crop.astype(np.float32), s)
|
| 138 |
+
V_down = _downsample(V_crop.astype(np.float32), s)
|
| 139 |
+
return self.predict(H_down, V_down)
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def prime_refine(raw_score, seed=None):
|
| 143 |
+
"""
|
| 144 |
+
PRIME bistable attractor refinement.
|
| 145 |
+
Evolves raw CNN score through recursive Hamiltonian dynamics.
|
| 146 |
+
H* = -3.054 (BENIGN attractor), positive (THREAT attractor).
|
| 147 |
+
"""
|
| 148 |
+
rng = np.random.default_rng(seed)
|
| 149 |
+
H = (raw_score - 0.5) * 4.0
|
| 150 |
+
trajectory = [H]
|
| 151 |
+
|
| 152 |
+
for t in range(PRIME_T):
|
| 153 |
+
sig = _sigmoid(H, PRIME_GAMMA)
|
| 154 |
+
noise = rng.normal(0, 1 + PRIME_BETA * abs(H))
|
| 155 |
+
H = H + PRIME_ETA * H * sig + PRIME_SIGMA * noise
|
| 156 |
+
H = max(-10.0, min(10.0, H))
|
| 157 |
+
trajectory.append(H)
|
| 158 |
+
|
| 159 |
+
refined = 1.0 / (1.0 + np.exp(-H))
|
| 160 |
+
|
| 161 |
+
if refined > THREAT_THRESHOLD:
|
| 162 |
+
verdict = "THREAT"
|
| 163 |
+
confidence = refined
|
| 164 |
+
elif refined < BENIGN_THRESHOLD:
|
| 165 |
+
verdict = "BENIGN"
|
| 166 |
+
confidence = 1.0 - refined
|
| 167 |
+
else:
|
| 168 |
+
verdict = "UNCERTAIN"
|
| 169 |
+
confidence = 1.0 - 2.0 * abs(refined - 0.5)
|
| 170 |
+
|
| 171 |
+
return {
|
| 172 |
+
"verdict": verdict,
|
| 173 |
+
"confidence": round(float(confidence), 4),
|
| 174 |
+
"refined_score": round(float(refined), 6),
|
| 175 |
+
"raw_score": round(float(raw_score), 6),
|
| 176 |
+
"prime_iterations": PRIME_T,
|
| 177 |
+
"prime_params": {"eta": PRIME_ETA, "gamma": PRIME_GAMMA,
|
| 178 |
+
"beta": PRIME_BETA, "sigma": PRIME_SIGMA},
|
| 179 |
+
"trajectory_final_10": [round(float(x), 4) for x in trajectory[-10:]],
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
def audit(self, H_manifold, V_manifold, seed=42):
|
| 183 |
+
"""Full pipeline: manifold -> CNN -> PRIME refinement -> verdict."""
|
| 184 |
+
if H_manifold.shape[0] > CNN_SPATIAL:
|
| 185 |
+
raw_score = self.predict_manifold(H_manifold, V_manifold)
|
| 186 |
+
else:
|
| 187 |
+
raw_score = self.predict(H_manifold.astype(np.float32),
|
| 188 |
+
V_manifold.astype(np.float32))
|
| 189 |
+
result = self.prime_refine(raw_score, seed=seed)
|
| 190 |
+
result["manifold_size"] = list(H_manifold.shape)
|
| 191 |
+
result["cnn_input_size"] = [CNN_SPATIAL, CNN_SPATIAL]
|
| 192 |
+
return result
|
| 193 |
|
| 194 |
def __repr__(self):
|
| 195 |
+
return (f"Leviathan(channels=2, conv=[2->16->16], fc=[4096->64->1], "
|
| 196 |
+
f"params=264,897, manifold=256x256->{CNN_SPATIAL}x{CNN_SPATIAL}, "
|
| 197 |
+
f"PRIME=[eta={PRIME_ETA},gamma={PRIME_GAMMA},T={PRIME_T}])")
|
| 198 |
|
| 199 |
|
| 200 |
if __name__ == "__main__":
|
|
|
|
| 203 |
model = Leviathan.from_safetensors(path)
|
| 204 |
print(model)
|
| 205 |
|
| 206 |
+
print("\n=== 256x256 Manifold Audit ===")
|
| 207 |
+
H_256 = np.random.randn(256, 256).astype(np.float32)
|
| 208 |
+
V_256 = np.random.randn(256, 256).astype(np.float32)
|
| 209 |
+
result = model.audit(H_256, V_256)
|
| 210 |
+
print(f" Verdict: {result['verdict']}")
|
| 211 |
+
print(f" Raw: {result['raw_score']}")
|
| 212 |
+
print(f" Refined: {result['refined_score']}")
|
| 213 |
+
print(f" Confidence: {result['confidence']}")
|
| 214 |
+
|
| 215 |
+
print("\n=== 20x20 Direct ===")
|
| 216 |
+
score = model.predict(np.random.randn(20, 20).astype(np.float32),
|
| 217 |
+
np.zeros((20, 20), dtype=np.float32))
|
| 218 |
+
print(f" Score: {score:.6f}")
|
| 219 |
+
|
| 220 |
+
print("\n=== PRIME Refinement Sweep ===")
|
| 221 |
+
for s in [0.0, 0.3, 0.5, 0.7, 1.0]:
|
| 222 |
+
r = Leviathan.prime_refine(s, seed=42)
|
| 223 |
+
print(f" input={s:.1f} -> {r['verdict']:>9} "
|
| 224 |
+
f"(refined={r['refined_score']:.4f}, conf={r['confidence']:.4f})")
|