-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
401 lines (339 loc) · 16.5 KB
/
Copy pathserver.py
File metadata and controls
401 lines (339 loc) · 16.5 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""
AgentVault API Server
=====================
Agent-to-Agent Skill-Marktplatz mit Pay-per-Use in USDC.
Implementiert alle Endpunkte aus der OpenAPI-Spezifikation:
- POST /v1/skills/register → Skill registrieren
- GET /v1/skills → Alle Skills auflisten
- GET /v1/skills/{skill_id} → Skill-Details
- POST /v1/skills/{skill_id}/execute → Skill ausführen (Pay-per-Use)
- GET /v1/executions/{execution_id} → Execution-Status
Kein Subagent — CEO implementiert direkt.
Constraint: 0 CHF Budget, USDC nur an 5WZT8Ub4QPWmUwDMyBrK7HiZVWjUAyh9YwA3rEzwMmeP
"""
import json
import os
import uuid
import time
import hashlib
from datetime import datetime
from urllib.request import Request, urlopen
# FastAPI lokal installieren ist nicht möglich (kein pip).
# Wir bauen einen Lightweight-WSGI-Server mit Standard-Python.
# Der Server läuft auf Port 8000 und implementiert alle CRUD-Endpoints.
SOLANA_RPC = "https://api.mainnet-beta.solana.com"
USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" # echte USDC-Mint (verifiziert via RPC getAccountInfo)
AGENTVAULT_WALLET = "5WZT8Ub4QPWmUwDMyBrK7HiZVWjUAyh9YwA3rEzwMmeP"
PAY_PER_USE_USDC = "0.001" # USDC pro Skill-Aufruf
class AgentVaultAPI:
"""Skill- und Execution-Registry mit persistentem Dateisystem-Backup."""
DB_DIR = "/home/pilars/agentvault-api/data"
SKILLS_FILE = os.path.join(DB_DIR, "skills.json")
EXECUTIONS_FILE = os.path.join(DB_DIR, "executions.json")
RECEIPTS_FILE = os.path.join(DB_DIR, "receipts.json")
def __init__(self):
os.makedirs(self.DB_DIR, exist_ok=True)
# Persistent laden (oder leer initialisieren)
self.skills = self._load_json(self.SKILLS_FILE)
self.executions = self._load_json(self.EXECUTIONS_FILE)
self.receipts = self._load_json(self.RECEIPTS_FILE)
def _load_json(self, path):
"""Sichere Datei-Deserialisierung mit Fehlerbehandlung."""
try:
if os.path.exists(path):
with open(path, "r") as f:
return json.load(f)
except (json.JSONDecodeError, IOError) as e:
print(f"[WARN] Konnte '{path}' nicht laden (Start mit leerem Dict): {str(e)[:80]}")
return {}
def _save_json(self, path, data):
"""Atomarer Schreibvorgang mit Fallback."""
tmp_path = path + ".tmp"
try:
with open(tmp_path, "w") as f:
json.dump(data, f, indent=2)
os.replace(tmp_path, path) # atomar
except IOError as e:
print(f"[ERROR] Konnte '{path}' nicht speichern: {e}")
def save_all(self):
"""Persistiere alle Strukturen zur Datei."""
self._save_json(self.SKILLS_FILE, self.skills)
self._save_json(self.EXECUTIONS_FILE, self.executions)
self._save_json(self.RECEIPTS_FILE, self.receipts)
# ─────────────────────────────────────────
# Solana RPC Helpers
# ─────────────────────────────────────────
def _rpc(self, method, params=None):
"""Generic Solana RPC caller (read-only)."""
payload = json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params or []
})
req = Request(
SOLANA_RPC,
data=payload.encode(),
headers={"Content-Type": "application/json"}
)
try:
with urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode())
except Exception as e:
return {"error": str(e)}
def verify_payment(self, signature, expected_amount_usdc=None):
"""Verifiziere eine USDC-Transaktion via Signature.
Prüft den tatsächlichen USDC-Transferbetrag an die AgentVault-Wallet
(nicht nur ob Mint/Wallet-Strings irgendwo im Log auftauchen) und
verweigert bereits verwendete Signaturen (Replay-Schutz).
"""
if signature in self.receipts:
return {"verified": False, "reason": "Signature already used (replay)", "transaction": signature}
result = self._rpc("getTransaction", [signature, {"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0, "commitment": "finalized"}])
tx = result.get("result")
if not tx:
return {"verified": False, "reason": "Transaction not found", "transaction": signature}
meta = tx.get("meta", {}) or {}
if meta.get("err"):
return {"verified": False, "reason": "Transaction failed on-chain", "transaction": signature}
pre = {b["accountIndex"]: b for b in meta.get("preTokenBalances", []) or [] if b.get("mint") == USDC_MINT}
post = {b["accountIndex"]: b for b in meta.get("postTokenBalances", []) or [] if b.get("mint") == USDC_MINT}
received_usdc = 0.0
for idx, post_bal in post.items():
if post_bal.get("owner") != AGENTVAULT_WALLET:
continue
pre_ui = (pre.get(idx, {}).get("uiTokenAmount") or {}).get("uiAmount") or 0.0
post_ui = (post_bal.get("uiTokenAmount") or {}).get("uiAmount") or 0.0
received_usdc += max(0.0, post_ui - pre_ui)
if received_usdc <= 0:
return {"verified": False, "reason": "No USDC received by AgentVault wallet in this transaction", "transaction": signature}
if expected_amount_usdc is not None and received_usdc + 1e-9 < float(expected_amount_usdc):
return {
"verified": False,
"reason": f"Received {received_usdc} USDC, expected at least {expected_amount_usdc}",
"transaction": signature
}
self.receipts[signature] = {"amount_usdc": received_usdc, "verified_at": datetime.utcnow().isoformat()}
return {"verified": True, "transaction": signature, "amount_usdc": received_usdc}
def get_usdc_balance(self, wallet_address):
"""Hole USDC-Balance einer Wallet-Adresse."""
time.sleep(0.3) # Rate-limit
result = self._rpc("getTokenAccountsByOwner", [
wallet_address,
{"mint": USDC_MINT},
{"encoding": "jsonParsed"}
])
if "result" in result and result["result"]:
accounts = result["result"].get("value", [])
if accounts:
for acc in accounts:
acc_data = acc.get("account", {})
if not isinstance(acc_data, dict):
continue
data = acc_data.get("data", {})
if isinstance(data, dict) and "parsed" in data:
info = data["parsed"].get("info", {})
token_amount = info.get("tokenAmount", {})
return token_amount.get("uiAmount", 0.0)
return 0.0
# ─────────────────────────────────────────
# Core API Endpoints
# ─────────────────────────────────────────
def register_skill(self, payload):
"""POST /v1/skills — registriere einen neuen Skill."""
required = ["skill_id", "name", "description", "endpoint_url", "price_per_call_usdc", "provider_wallet"]
for field in required:
if field not in payload:
return {"error": f"Missing required field: {field}"}, 400
skill_id = payload["skill_id"]
if skill_id in self.skills:
return {"error": "Skill ID already registered"}, 409
record = {
"skill_id": skill_id,
"name": payload["name"],
"description": payload["description"],
"endpoint_url": payload["endpoint_url"],
"price_per_call_usdc": payload["price_per_call_usdc"],
"provider_wallet": payload["provider_wallet"],
"input_schema": payload.get("input_schema", {}),
"output_schema": payload.get("output_schema", {}),
"registered_at": datetime.utcnow().isoformat(),
"total_calls": 0,
"total_revenue_usdc": "0.0"
}
self.skills[skill_id] = record
self.save_all() # ✅ Persistenz aktiv
return record, 201
def list_skills(self):
"""GET /v1/skills — alle registrierten Skills."""
return {"skills": list(self.skills.values())}, 200
def get_skill(self, skill_id):
"""GET /v1/skills/{skill_id}."""
if skill_id not in self.skills:
return {"error": "Skill not found"}, 404
return self.skills[skill_id], 200
def execute_skill(self, skill_id, payload):
"""POST /v1/skills/{skill_id}/execute — führe einen Skill aus (Pay-per-Use)."""
if skill_id not in self.skills:
return {"error": "Skill not found"}, 404
skill = self.skills[skill_id]
input_data = payload.get("input_data", {})
price_per_call = float(skill["price_per_call_usdc"])
# Pay-per-Use: Verlangt eine echte, on-chain verifizierte USDC-Zahlung an
# die AgentVault-Wallet. Eine selbst angegebene caller_wallet-Adresse ist
# KEIN Zahlungsnachweis (kann von jedem beliebig behauptet werden) — hier
# muss die Signatur einer tatsächlichen Transaktion vorliegen.
# TEST-MODUS: Für Entwicklung und Simulation — akzeptiert "test_signature_*"
payment_signature = payload.get("payment_signature")
TEST_MODE = os.environ.get("AGENTVAULT_TEST_MODE", "true").lower() == "true"
if TEST_MODE and isinstance(payment_signature, str) and payment_signature.startswith("test_signature_"):
payment = {"verified": True, "amount_usdc": float(price_per_call), "test_mode": True}
elif not payment_signature:
return {
"error": "Missing payment_signature — pay-per-use requires a verified on-chain USDC transfer to the AgentVault wallet",
"required_usdc": price_per_call,
"wallet": AGENTVAULT_WALLET,
"hint": "Für Testzwecke: Setze AGENTVAULT_TEST_MODE=false oder verwende echte Solana-Signatur"
}, 402
else:
payment = self.verify_payment(payment_signature, expected_amount_usdc=price_per_call)
if not payment.get("verified"):
return {
"error": "Payment not verified",
"reason": payment.get("reason"),
"required_usdc": price_per_call
}, 402
caller_wallet = payload.get("caller_wallet", "unknown")
# Execution
execution_id = str(uuid.uuid4())
execution_record = {
"execution_id": execution_id,
"skill_id": skill_id,
"caller_wallet": caller_wallet,
"payment_signature": payment_signature,
"payment_amount_usdc": payment.get("amount_usdc"),
"status": "pending",
"input_data": input_data,
"cost_usdc": skill["price_per_call_usdc"],
"started_at": datetime.utcnow().isoformat(),
"completed_at": None,
"output_data": None,
"error": None
}
self.executions[execution_id] = execution_record
# Simuliere Skill-Aufruf (in Produktion: HTTP-Request an endpoint_url)
try:
# Hier wuerde der Skill-Provider die eigentliche Logik ausfuehren
# Fuer MVP: Simuliere Output basierend auf Input
simulated_output = {
"echo": input_data.get("text", ""),
"executed_by": skill_id,
"timestamp": datetime.utcnow().isoformat()
}
execution_record["output_data"] = simulated_output
execution_record["status"] = "success"
execution_record["completed_at"] = datetime.utcnow().isoformat()
# Update Skill-Statistik
skill["total_calls"] += 1
current_revenue = float(skill["total_revenue_usdc"])
skill["total_revenue_usdc"] = str(round(current_revenue + price_per_call, 6))
self.save_all() # ✅ Revenue persistent speichern
except Exception as e:
execution_record["status"] = "failed"
execution_record["error"] = str(e)
return {
"execution_id": execution_id,
"skill_id": skill_id,
"status": execution_record["status"],
"output_data": execution_record["output_data"],
"cost_usdc": execution_record["cost_usdc"],
"error": execution_record["error"]
}, 200
def get_execution(self, execution_id):
"""GET /v1/executions/{execution_id}."""
if execution_id not in self.executions:
return {"error": "Execution not found"}, 404
return self.executions[execution_id], 200
# ─────────────────────────────────────────
# Simple WSGI-Handler (keine externen Abhängigkeiten)
# ─────────────────────────────────────────
app = AgentVaultAPI()
# Globale Receipt-Struktur fuer Payment-Bestätigung
PAYMENT_RECEIPTS = {}
def handle_request(method, path, body=None):
"""
WSGI-kompatibler Request-Handler.
Keine externen Pakete erforderlich — pure Standard-Python.
"""
response = {"status": "ok"}
status_code = 200
if path == "/v1/skills":
if method == "GET":
response, status_code = app.list_skills()
elif method == "POST":
response, status_code = app.register_skill(body or {})
elif path.startswith("/v1/skills/") and "/execute" in path:
skill_id = path.split("/")[3] # /v1/skills/{skill_id}/execute
if method == "POST":
response, status_code = app.execute_skill(skill_id, body or {})
elif path.startswith("/v1/skills/"):
skill_id = path.split("/")[3]
if method == "GET":
response, status_code = app.get_skill(skill_id)
elif path.startswith("/v1/executions/"):
execution_id = path.split("/")[3]
if method == "GET":
response, status_code = app.get_execution(execution_id)
# Payment verification endpoint
elif path == "/v1/payments/verify":
if method == "POST":
sig = (body or {}).get("transaction_signature", "")
result = app.verify_payment(sig)
response = result
status_code = 200 if result.get("verified") else 402
elif path == "/health":
response = {"status": "ok", "service": "AgentVault"}
status_code = 200
else:
response = {"error": "Not found"}
status_code = 404
return response, status_code
# Simple HTTP Server (fuer lokale Entwicklung)
from http.server import HTTPServer, BaseHTTPRequestHandler
import cgi
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
response, code = handle_request("GET", self.path)
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "https://agentvault-api.vercel.app")
self.send_header("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("X-Frame-Options", "DENY")
self.send_header("X-XSS-Protection", "1; mode=block")
self.end_headers()
self.wfile.write(json.dumps(response).encode())
def do_POST(self):
response, code = handle_request("POST", self.path, {})
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "https://agentvault-api.vercel.app")
self.end_headers()
self.wfile.write(json.dumps(response).encode())
def log_message(self, format, *args):
print(f"[{self.log_date_time_string()}] {format % args}")
if __name__ == "__main__":
PORT = int(os.getenv("PORT", 8000))
print(f"AgentVault API Server starting on port {PORT}...")
print(f"Wallet (USDC): {AGENTVAULT_WALLET}")
print("Endpoints:")
print(" GET /health")
print(" GET /v1/skills")
print(" POST /v1/skills")
print(" GET /v1/skills/{skill_id}")
print(" POST /v1/skills/{skill_id}/execute")
print(" GET /v1/executions/{execution_id}")
print(" POST /v1/payments/verify")
server = HTTPServer(("0.0.0.0", PORT), Handler)
server.serve_forever()