-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe_bot.py
More file actions
298 lines (241 loc) · 11.6 KB
/
safe_bot.py
File metadata and controls
298 lines (241 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
safe_bot.py — RWA Liquidation Bot with Headless Oracle Integration
This bot demonstrates how a 3-line integration with Headless Oracle
prevents the DST phantom hour failure shown in vulnerable_bot.py.
Instead of computing market hours locally, the bot asks a signed oracle
whether the market is actually open. Every response is Ed25519 signed.
If anything is wrong (bad signature, UNKNOWN status, network error),
the bot halts. Fail-closed by design.
Run: python safe_bot.py
Requires: pip install requests pynacl
"""
import json
import sys
from datetime import datetime, timezone, timedelta
from typing import Optional
# ─── Configuration ──────────────────────────────────────────────────────────
COLLATERAL_ASSET = "OUSG"
COLLATERAL_VALUE_USD = 100_000_000 # $100M position (Ondo OUSG TVL is $1.3B Jan 2026)
COLLATERALIZATION_RATIO = 1.50 # 150% (typical RWA lending protocol)
OVERNIGHT_DROP_PCT = 0.15 # 15% after-hours drop
ORACLE_URL = "https://headlessoracle.com/v5/demo" # Public demo (no auth)
ORACLE_PUBLIC_KEY_HEX = "03dc27993a2c90856cdeb45e228ac065f18f69f0933c917b2336c1e75712f178"
# For production, use the authenticated endpoint:
# ORACLE_URL = "https://headlessoracle.com/v5/status?mic=XNYS"
# and include header: X-Oracle-Key: <your_api_key>
# ─── Oracle Client ──────────────────────────────────────────────────────────
def verify_receipt(receipt: dict, public_key_hex: str) -> bool:
"""Verify Ed25519 signature on an oracle receipt.
Reconstructs the canonical payload (all fields except 'signature')
in the exact field order used by the oracle, then verifies the
Ed25519 signature against the known public key.
"""
try:
from nacl.signing import VerifyKey
except ImportError:
print(" [ERROR] pynacl not installed. Run: pip install pynacl")
return False
try:
# Reconstruct canonical payload in exact field order
payload = {
"receipt_id": receipt["receipt_id"],
"issued_at": receipt["issued_at"],
"mic": receipt["mic"],
"status": receipt["status"],
"source": receipt["source"],
"terms_hash": receipt["terms_hash"],
"public_key_id": receipt["public_key_id"],
}
canonical = json.dumps(payload, separators=(",", ":"))
msg_bytes = canonical.encode("utf-8")
sig_bytes = bytes.fromhex(receipt["signature"])
vk = VerifyKey(bytes.fromhex(public_key_hex))
vk.verify(msg_bytes, sig_bytes)
return True
except Exception as e:
print(f" [SIGNATURE FAILED] {e}")
return False
def check_oracle(mic: str = "XNYS") -> Optional[dict]:
"""Query Headless Oracle for market status.
Returns the verified receipt dict, or None if anything fails.
This is the fail-closed pattern: if we can't get a valid,
signed response, we return None and the caller halts.
"""
try:
import requests
except ImportError:
print(" [ERROR] requests not installed. Run: pip install requests")
return None
try:
url = f"{ORACLE_URL}{'&' if '?' in ORACLE_URL else '?'}mic={mic}"
resp = requests.get(url, timeout=4)
if resp.status_code != 200:
print(f" [ORACLE ERROR] HTTP {resp.status_code}")
return None
receipt = resp.json()
# Verify signature — MANDATORY
if not verify_receipt(receipt, ORACLE_PUBLIC_KEY_HEX):
print(" [HALT] Signature verification failed. Treating as UNKNOWN.")
return None
# Check for UNKNOWN status — MANDATORY halt
if receipt.get("status") == "UNKNOWN":
print(" [HALT] Oracle returned UNKNOWN. Fail-closed: treating as market closed.")
return None
return receipt
except requests.exceptions.Timeout:
print(" [HALT] Oracle request timed out (>4s). Fail-closed: halting.")
return None
except Exception as e:
print(f" [HALT] Oracle error: {e}. Fail-closed: halting.")
return None
# ─── Safe Liquidation Logic ─────────────────────────────────────────────────
_UNSET = object() # Sentinel to distinguish "no simulation" from "simulate None"
def check_liquidation_safe(nav_drop_pct: float, simulated_receipt=_UNSET) -> dict:
"""Decide whether to liquidate — but ONLY if the oracle confirms market is OPEN."""
current_value = COLLATERAL_VALUE_USD * (1 - nav_drop_pct)
debt_value = COLLATERAL_VALUE_USD / COLLATERALIZATION_RATIO
health_factor = current_value / debt_value
result = {
"collateral_value": f"${current_value:,.0f}",
"debt_value": f"${debt_value:,.0f}",
"health_factor": round(health_factor, 3),
"liquidation_triggered": False,
"oracle_status": None,
"oracle_verified": False,
}
# ── THE 3-LINE INTEGRATION ──────────────────────────────────────────
# Line 1: Query the oracle
receipt = simulated_receipt if simulated_receipt is not _UNSET else check_oracle("XNYS")
# Line 2: If oracle failed or returned non-OPEN, HALT
if not receipt or receipt.get("status") != "OPEN":
result["action"] = "HALT — Oracle did not confirm market OPEN"
result["oracle_status"] = receipt.get("status") if receipt else "UNREACHABLE"
return result
# Line 3: Only execute if oracle says OPEN and signature is valid
result["oracle_status"] = receipt["status"]
result["oracle_verified"] = True
# ── END INTEGRATION ─────────────────────────────────────────────────
if health_factor < 1.0:
result["liquidation_triggered"] = True
result["action"] = "LIQUIDATE — Market confirmed OPEN by signed oracle"
else:
result["action"] = "HOLD — Health factor above 1.0"
return result
# ─── Simulation ─────────────────────────────────────────────────────────────
def run_simulation():
print("=" * 72)
print("SAFE BOT — Headless Oracle Integration")
print("=" * 72)
print()
# ── Scenario 1: Market is OPEN (oracle confirms) ────────────────────
print("SCENARIO 1: Market is OPEN — Oracle confirms with signed receipt")
print("-" * 72)
open_receipt = {
"receipt_id": "sim-001",
"issued_at": "2026-03-09T14:30:00.000Z",
"mic": "XNYS",
"status": "OPEN",
"source": "SCHEDULE",
"terms_hash": "v5.0-beta",
"public_key_id": "key_2026_v1",
"signature": "simulated",
}
result = check_liquidation_safe(OVERNIGHT_DROP_PCT, simulated_receipt=open_receipt)
print(f" Oracle Status: {result['oracle_status']}")
print(f" Collateral: {result['collateral_value']}")
print(f" Health Factor: {result['health_factor']}")
print(f" Action: {result['action']}")
print()
# ── Scenario 2: Market CLOSED — first trading day after DST ─────────
print("SCENARIO 2: Monday March 9, 2026 — First trading day after DST")
print("-" * 72)
print()
print(" It's 8:30 PM UTC on March 9 (4:30 PM EDT — market closed 30 min ago).")
print(" The vulnerable bot thinks it's 3:30 PM EST (market still open).")
print(" Let's see what the safe bot does.")
print()
closed_receipt = {
"receipt_id": "sim-002",
"issued_at": "2026-03-09T20:30:00.000Z",
"mic": "XNYS",
"status": "CLOSED",
"source": "SCHEDULE",
"terms_hash": "v5.0-beta",
"public_key_id": "key_2026_v1",
"signature": "simulated",
}
result = check_liquidation_safe(OVERNIGHT_DROP_PCT, simulated_receipt=closed_receipt)
print(f" Oracle Status: {result['oracle_status']}")
print(f" Collateral: {result['collateral_value']}")
print(f" Health Factor: {result['health_factor']}")
print(f" Action: {result['action']}")
print()
print(" The safe bot HALTED. It does not care what time it thinks it is.")
print(" It only cares what the signed oracle says. Oracle said CLOSED.")
print(" No liquidation. No bad debt. No wasted gas.")
print()
# ── Scenario 3: Oracle unreachable (fail-closed) ────────────────────
print("SCENARIO 3: Oracle is unreachable")
print("-" * 72)
print()
result = check_liquidation_safe(OVERNIGHT_DROP_PCT, simulated_receipt=None)
print(f" Oracle Status: {result['oracle_status']}")
print(f" Action: {result['action']}")
print()
print(" Oracle was unreachable. Safe bot HALTED.")
print(" Fail-closed: if you don't KNOW the market is open, don't execute.")
print()
# ── Scenario 4: Oracle returns UNKNOWN (system error) ───────────────
print("SCENARIO 4: Oracle returns UNKNOWN (internal error)")
print("-" * 72)
print()
unknown_receipt = {
"receipt_id": "sim-003",
"issued_at": "2026-03-08T20:00:00.000Z",
"mic": "XNYS",
"status": "UNKNOWN",
"source": "SYSTEM",
"terms_hash": "v5.0-beta",
"public_key_id": "key_2026_v1",
"signature": "simulated",
}
result = check_liquidation_safe(OVERNIGHT_DROP_PCT, simulated_receipt=unknown_receipt)
print(f" Oracle Status: {result['oracle_status']}")
print(f" Action: {result['action']}")
print()
print(" Oracle returned UNKNOWN (its own database was unreachable).")
print(" Safe bot HALTED. UNKNOWN = CLOSED. Always.")
print()
# ── Live Test ───────────────────────────────────────────────────────
print("=" * 72)
print("LIVE TEST — Querying Headless Oracle API right now")
print("=" * 72)
print()
try:
import requests
from nacl.signing import VerifyKey
receipt = check_oracle("XNYS")
if receipt:
print(f" Receipt ID: {receipt['receipt_id']}")
print(f" Status: {receipt['status']}")
print(f" Source: {receipt['source']}")
print(f" Issued At: {receipt['issued_at']}")
print(f" Signature: {receipt['signature'][:32]}...")
print(f" Verified: YES — Ed25519 signature valid")
print()
result = check_liquidation_safe(OVERNIGHT_DROP_PCT, simulated_receipt=receipt)
print(f" Bot Decision: {result['action']}")
else:
print(" Oracle returned None (fail-closed triggered).")
print(" Bot would HALT all execution.")
except ImportError:
print(" [SKIP] Install requests and pynacl for live test:")
print(" pip install requests pynacl")
print()
print("=" * 72)
print("The safe bot never computes time zones. It never guesses.")
print("It asks a signed oracle. If the answer isn't OPEN, it halts.")
print("Three lines of code. Zero DST bugs.")
print("=" * 72)
if __name__ == "__main__":
run_simulation()