-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitcoin_api.py
More file actions
1754 lines (1509 loc) · 64.9 KB
/
bitcoin_api.py
File metadata and controls
1754 lines (1509 loc) · 64.9 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Starlight Bitcoin Scanning API - FastAPI Implementation
REST API for scanning Bitcoin transactions for steganography in embedded images.
This API integrates with the existing Starlight scanner to provide:
- Transaction scanning for steganography
- Direct image scanning
- Batch processing capabilities
- Message extraction from steganographic images
"""
from typing import List, Optional, Dict, Any, Union
from datetime import datetime, timedelta
import uuid
import logging
import base64
import io
import os
import tempfile
import hashlib
import json
import hmac
import time
from pathlib import Path
import requests
from contextlib import asynccontextmanager
import glob
import threading
from PIL import Image
from starlight.agents.config import Config as AgentConfig
from starlight.agents.client import StargateClient
from starlight.agents.watcher import WatcherAgent
from starlight.agents.worker import WorkerAgent
from starlight.agents.dynamic_loader import dynamic_loader, LoadRequest as DynamicLoadRequest
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def validate_safe_path(path: str, allowed_bases: List[str]) -> str:
"""Validate path is within allowed base directories to prevent directory traversal."""
abs_path = os.path.abspath(path)
for base in allowed_bases:
abs_base = os.path.abspath(base)
if abs_path == abs_base or abs_path.startswith(abs_base + os.sep):
return abs_path
# If no match found, use first allowed base as safe default
return os.path.abspath(allowed_bases[0])
# Default blocks directory (override via env for testing only)
# SECURITY: Restrict to safe subdirectories to prevent path traversal
# Include common Docker mount points and production paths
ALLOWED_BLOCKS_BASES = [
"blocks", "./blocks", "../blocks", "../../blocks", # Development paths
"/data/blocks", "/app/blocks", "/starlight/blocks", # Docker/container paths
"/var/lib/starlight/blocks" # System installation paths
]
_env_blocks = os.environ.get("BLOCKS_DIR", "blocks")
BLOCKS_DIR = validate_safe_path(_env_blocks, ALLOWED_BLOCKS_BASES)
STARGATE_STEGO_CALLBACK_URL = os.environ.get("STARGATE_STEGO_CALLBACK_URL", "")
STARGATE_STEGO_CALLBACK_SECRET = os.environ.get("STARGATE_STEGO_CALLBACK_SECRET", "")
def send_stargate_callback(payload: Dict[str, Any]) -> Dict[str, Any]:
"""Send scan results to Stargate callback API when configured."""
if not STARGATE_STEGO_CALLBACK_URL:
return {"skipped": True}
try:
body = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if STARGATE_STEGO_CALLBACK_SECRET:
signature = hmac.new(
STARGATE_STEGO_CALLBACK_SECRET.encode("utf-8"),
body,
hashlib.sha256,
).hexdigest()
headers["X-Starlight-Signature"] = signature
resp = requests.post(
STARGATE_STEGO_CALLBACK_URL, data=body, headers=headers, timeout=10
)
return {"status_code": resp.status_code, "response": resp.text}
except Exception as exc: # pragma: no cover - network issues are runtime concerns
logger.warning("Stargate stego callback failed: %s", exc)
return {"error": str(exc)}
try:
from fastapi import (
FastAPI,
HTTPException,
Depends,
Query,
Header,
BackgroundTasks,
File,
UploadFile,
Form,
)
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, Field
except ImportError as exc: # pragma: no cover - FastAPI is required for this service
raise RuntimeError(
"FastAPI dependencies are required. Install with `pip install -r bitcoin_api_requirements.txt`."
) from exc
# Import scanner components
try:
from scanner import StarlightScanner, _scan_logic
SCANNER_AVAILABLE = True
logger.info("Starlight scanner loaded successfully")
except ImportError as e:
SCANNER_AVAILABLE = False
logger.error(f"Could not import Starlight scanner: {e}")
# Stego embedding helpers (re-use existing tool functions when available)
embed_alpha = embed_lsb = embed_palette = embed_exif = embed_eoi = None
try:
from scripts.stego_tool import (
embed_alpha,
embed_lsb,
embed_palette,
embed_exif,
embed_eoi,
)
STEGO_HELPERS_AVAILABLE = True
except Exception as e:
STEGO_HELPERS_AVAILABLE = False
logger.warning(f"stego_tool helpers unavailable: {e}")
# Bitcoin integration (stub for now - would integrate with actual Bitcoin node)
class BitcoinNodeClient:
"""Bitcoin node client for transaction data retrieval"""
def __init__(self, node_url: str = "https://blockstream.info/api"):
self.node_url = node_url
self.connected = True
async def get_transaction(self, tx_id: str) -> Dict[str, Any]:
"""Get transaction details from Bitcoin node"""
# Stub implementation - would integrate with actual Bitcoin API
return {
"txid": tx_id,
"block_height": 170000,
"timestamp": datetime.utcnow().isoformat(),
"status": "confirmed",
"outputs": [
{
"script_pubkey": "OP_RETURN "
+ "48656c6c6f20576f726c64", # "Hello World" in hex
"value": 0,
}
],
}
async def extract_images(self, tx_id: str) -> List[Dict[str, Any]]:
"""Extract images from transaction outputs"""
# Stub implementation - would parse actual transaction data
return [
{
"index": 0,
"data": base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
),
"format": "png",
"size_bytes": 67,
}
]
async def get_block_height(self) -> int:
"""Get current block height"""
return 856789
# Pydantic models for request/response validation
class ScanOptions(BaseModel):
extract_message: bool = Field(
default=True, description="Extract hidden messages if stego detected"
)
confidence_threshold: float = Field(
default=0.5, ge=0.0, le=1.0, description="Minimum confidence threshold"
)
include_metadata: bool = Field(
default=True, description="Include detailed metadata in response"
)
enable_patch_scanning: bool = Field(
default=True, description="Enable patch-based scanning for large images"
)
patch_size: int = Field(
default=256, description="Patch size for large image scanning"
)
patch_stride: int = Field(
default=128, description="Stride between patches for overlap"
)
patch_aggregation: str = Field(
default="weighted",
description="Method to aggregate patch results: 'max', 'avg', or 'weighted'",
)
class TransactionScanRequest(BaseModel):
transaction_id: str = Field(
..., pattern=r"^[a-fA-F0-9]{64}$", description="64-character hex transaction ID"
)
extract_images: bool = Field(
default=True, description="Extract images from transaction"
)
scan_options: ScanOptions = Field(
default_factory=ScanOptions, description="Scanning options"
)
class ScanResult(BaseModel):
is_stego: bool = Field(..., description="Whether steganography was detected")
stego_probability: float = Field(
..., ge=0.0, le=1.0, description="Steganography probability"
)
stego_type: Optional[str] = Field(
None, description="Type of steganography detected"
)
confidence: float = Field(..., ge=0.0, le=1.0, description="Detection confidence")
prediction: str = Field(
..., pattern="^(stego|clean)$", description="Model prediction"
)
method_id: Optional[int] = Field(None, description="Steganography method ID")
extracted_message: Optional[str] = Field(
None, description="Extracted hidden message"
)
extraction_error: Optional[str] = Field(
None, description="Error during message extraction"
)
class ImageScanResult(BaseModel):
index: int = Field(..., description="Image index in transaction")
size_bytes: int = Field(..., ge=0, description="Image size in bytes")
format: str = Field(..., description="Image format")
scan_result: ScanResult = Field(..., description="Scanning result")
class TransactionScanResponse(BaseModel):
transaction_id: str = Field(..., description="Transaction ID")
block_height: int = Field(..., description="Block height")
timestamp: str = Field(..., description="Transaction timestamp")
scan_results: Dict[str, Any] = Field(..., description="Summary of scan results")
images: List[ImageScanResult] = Field(
..., description="Individual image scan results"
)
request_id: str = Field(..., description="Unique request ID")
class DirectImageScanResponse(BaseModel):
scan_result: ScanResult = Field(..., description="Scanning result")
image_info: Dict[str, Any] = Field(..., description="Image information")
processing_time_ms: float = Field(
..., ge=0, description="Processing time in milliseconds"
)
request_id: str = Field(..., description="Unique request ID")
class BatchItem(BaseModel):
type: str = Field(..., pattern="^(transaction|image)$", description="Item type")
transaction_id: Optional[str] = Field(
None, description="Transaction ID for transaction type"
)
image_data: Optional[str] = Field(
None, description="Base64 image data for image type"
)
class BatchScanRequest(BaseModel):
items: List[BatchItem]
scan_options: ScanOptions = Field(default_factory=ScanOptions)
class BatchItemResult(BaseModel):
item_id: str = Field(..., description="Item identifier")
type: str = Field(..., description="Item type")
status: str = Field(
..., pattern="^(completed|failed)$", description="Processing status"
)
stego_detected: bool = Field(..., description="Whether steganography was detected")
images_with_stego: int = Field(
..., ge=0, description="Number of images with steganography"
)
total_images: int = Field(..., ge=0, description="Total number of images")
error: Optional[str] = Field(None, description="Error message if failed")
class BatchScanResponse(BaseModel):
batch_id: str = Field(..., description="Batch processing ID")
total_items: int = Field(..., description="Total items in batch")
processed_items: int = Field(..., description="Successfully processed items")
stego_detected: int = Field(..., description="Items with steganography detected")
processing_time_ms: float = Field(..., ge=0, description="Total processing time")
results: List[BatchItemResult] = Field(..., description="Individual item results")
request_id: str = Field(..., description="Unique request ID")
class ExtractionResult(BaseModel):
message_found: bool = Field(..., description="Whether a message was found")
message: Optional[str] = Field(None, description="Extracted message")
method_used: Optional[str] = Field(None, description="Steganography method used")
method_confidence: Optional[float] = Field(
None, description="Confidence in method detection"
)
extraction_details: Dict[str, Any] = Field(..., description="Extraction details")
class ExtractResponse(BaseModel):
extraction_result: ExtractionResult = Field(..., description="Extraction result")
image_info: Dict[str, Any] = Field(..., description="Image information")
processing_time_ms: float = Field(
..., ge=0, description="Processing time in milliseconds"
)
request_id: str = Field(..., description="Unique request ID")
class HealthResponse(BaseModel):
status: str = Field(..., description="Service health status")
timestamp: str = Field(..., description="Current timestamp")
version: str = Field(..., description="API version")
scanner: Dict[str, Any] = Field(..., description="Scanner status")
bitcoin: Dict[str, Any] = Field(..., description="Bitcoin node status")
class InfoResponse(BaseModel):
name: str = Field(..., description="API name")
version: str = Field(..., description="API version")
description: str = Field(..., description="API description")
supported_formats: List[str] = Field(..., description="Supported image formats")
stego_methods: List[str] = Field(..., description="Supported steganography methods")
max_image_size: int = Field(..., description="Maximum image size in bytes")
endpoints: Dict[str, str] = Field(..., description="Available endpoints")
class InscribeResponse(BaseModel):
request_id: str = Field(..., description="Unique request ID")
method: str = Field(..., description="Embedding method used")
message_length: int = Field(..., description="Length of embedded message in bytes")
output_file: str = Field(..., description="Relative path to saved inscribed image")
image_bytes: int = Field(..., description="Size of inscribed image in bytes")
image_sha256: str = Field(
..., description="SHA256 hash of inscribed image for ID tracking"
)
image_base64: str = Field(..., description="Base64-encoded stego-processed image")
status: str = Field(..., description="Inscribe status (pending upload)")
note: str = Field(..., description="Next step hint for Stargate uploader")
class BlockScanRequest(BaseModel):
block_height: int = Field(..., ge=0, description="Block height to scan")
scan_options: ScanOptions = Field(
default_factory=ScanOptions, description="Scanning options"
)
class BlockScanInscription(BaseModel):
tx_id: str = Field(..., description="Transaction ID")
input_index: int = Field(..., description="Input index")
content_type: str = Field(..., description="Content type")
content: str = Field(..., description="Content")
size_bytes: int = Field(..., ge=0, description="Size in bytes")
file_name: str = Field(..., description="File name")
file_path: str = Field(..., description="File path")
scan_result: Optional[ScanResult] = Field(None, description="Scan result")
class BlockScanResponse(BaseModel):
block_height: int = Field(..., description="Block height")
block_hash: str = Field(..., description="Block hash")
timestamp: int = Field(..., description="Block timestamp")
total_inscriptions: int = Field(..., description="Total inscriptions")
images_scanned: int = Field(..., description="Images scanned")
stego_detected: int = Field(..., description="Steganography detected")
processing_time_ms: float = Field(
..., ge=0, description="Processing time in milliseconds"
)
inscriptions: List[BlockScanInscription] = Field(
..., description="Inscription scan results"
)
request_id: str = Field(..., description="Unique request ID")
# Global instances
bitcoin_client = BitcoinNodeClient()
scanner_instance = None
# Metrics
REQUEST_COUNT = Counter(
"starlight_request_total",
"Total requests",
["endpoint", "status"],
)
REQUEST_LATENCY = Histogram(
"starlight_request_duration_seconds",
"Request latency seconds",
["endpoint"],
)
# Initialize scanner if available
if SCANNER_AVAILABLE:
try:
from scanner import StarlightScanner
# SECURITY: Validate model path is within expected directories
ALLOWED_MODEL_BASES = ["models", "./models", "../models", "../../models"]
model_rel_path = "detector_balanced.pth"
model_base = validate_safe_path("models", ALLOWED_MODEL_BASES)
model_path = os.path.join(model_base, model_rel_path)
if os.path.exists(model_path):
scanner_instance = StarlightScanner(model_path, num_workers=4, quiet=True)
logger.info(f"Scanner initialized with model: {model_path}")
else:
logger.warning(f"Model file not found: {model_path}")
except Exception as e:
logger.error(f"Failed to initialize scanner: {e}")
# Background task for async scanning
async def scan_image_async(
image_data: bytes, options: ScanOptions, request_id: str, filename: Optional[str] = None
) -> ScanResult:
"""Background task for image scanning"""
try:
if scanner_instance is not None:
# Use Starlight scanner directly on memory
result = scanner_instance.scan_file(image_data)
# Convert to ScanResult format
scan_result = ScanResult(
is_stego=result.get("is_stego", False),
stego_probability=result.get("stego_probability", 0.0),
stego_type=result.get("stego_type"),
confidence=result.get("confidence", 0.0),
prediction="stego" if result.get("is_stego") else "clean",
method_id=result.get("method_id"),
extracted_message=(
result.get("extracted_message")
if options.extract_message
else None
),
extraction_error=result.get("extraction_error"),
)
# Apply confidence threshold
if scan_result.stego_probability < options.confidence_threshold:
scan_result.is_stego = False
scan_result.prediction = "clean"
return scan_result
else:
# Stub response when scanner not available
return ScanResult(
is_stego=False,
stego_probability=0.1,
stego_type=None,
confidence=0.9,
prediction="clean",
method_id=None,
extracted_message=None,
extraction_error=None,
)
except Exception as e:
logger.error(f"Error scanning image for request {request_id}: {e}")
return ScanResult(
is_stego=False,
stego_probability=0.0,
stego_type=None,
confidence=0.0,
prediction="clean",
method_id=None,
extracted_message=None,
extraction_error=str(e),
)
def embed_message_to_image(
image_bytes: bytes, method: str, message: str
) -> tuple[bytes, str]:
"""Embed a UTF-8 message into an image using the selected stego method."""
if not STEGO_HELPERS_AVAILABLE:
raise RuntimeError("Stego helpers are unavailable; cannot inscribe message.")
method_map = {
"alpha": embed_alpha,
"lsb": embed_lsb,
"palette": embed_palette,
"exif": embed_exif,
"eoi": embed_eoi,
}
method_key = method.lower()
if method_key not in method_map:
raise ValueError(
f"Unsupported method '{method}'. Supported: {', '.join(sorted(method_map.keys()))}"
)
cover = Image.open(io.BytesIO(image_bytes))
embed_func = method_map[method_key]
if embed_func is None:
raise RuntimeError(f"Embed function for method '{method}' is not available")
stego_img = embed_func(cover, message.encode("utf-8"))
if method_key in ("exif", "eoi"):
output_format = "JPEG"
elif method_key == "palette":
output_format = "GIF"
else:
output_format = "PNG"
buf = io.BytesIO()
save_kwargs = {}
if output_format == "JPEG":
save_kwargs["quality"] = 95
exif_bytes = stego_img.info.get("exif_bytes")
if exif_bytes:
save_kwargs["exif"] = exif_bytes
stego_img.save(buf, format=output_format, **save_kwargs)
payload = buf.getvalue()
if method_key == "eoi":
append_data = stego_img.info.get("eoi_append")
if append_data:
payload += append_data
return payload, output_format
# Dependency for API key authentication
async def verify_api_key(authorization: str = Header(None)):
"""Verify API key for protected endpoints"""
required_key = os.environ.get("STARGATE_API_KEY", "demo-api-key")
if authorization is None:
# Allow missing header if explicit bypass is configured
if os.environ.get("ALLOW_ANONYMOUS_SCAN", "false").lower() == "true":
return "anonymous"
raise HTTPException(status_code=401, detail="Authorization header required")
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid authorization format")
api_key = authorization.split(" ")[1]
# Simple validation (replace with proper JWT verification in production)
if api_key != required_key:
raise HTTPException(status_code=403, detail="Invalid API key")
return api_key
# Import agent manager
AGENT_MANAGER_AVAILABLE = False
from typing import Callable, Dict, Any, Optional
# Type hints for agent manager functions - these will be properly typed after import
get_manager: Any = None
start_agents: Any = None
stop_agents: Any = None
get_agent_status: Any = None
process_cycle: Any = None
try:
from starlight.agents.agent_manager import (
get_manager as _get_manager,
start_agents as _start_agents,
stop_agents as _stop_agents,
get_agent_status as _get_agent_status,
process_cycle as _process_cycle
)
AGENT_MANAGER_AVAILABLE = True
get_manager = _get_manager
start_agents = _start_agents
stop_agents = _stop_agents
get_agent_status = _get_agent_status
process_cycle = _process_cycle
logger.info("Agent manager module loaded successfully")
except ImportError as e:
AGENT_MANAGER_AVAILABLE = False
logger.error(f"Could not import agent manager: {e}")
# Global Agent State (backward compatibility)
agent_running = False
def run_agents_loop():
"""Backward compatibility wrapper using new agentManager."""
global agent_running
if AGENT_MANAGER_AVAILABLE and get_manager is not None:
# Use the new modular agentManager
manager = get_manager()
if manager and hasattr(manager, 'initialize') and manager.initialize():
agent_running = manager.start(blocking=True, max_cycles=None)
logger.info("Agent loop started using AgentManager")
return agent_running
# Fallback to original logic if manager unavailable
agent_running = False
logger.info("Starting Autonomous Agents Loop (fallback mode)")
try:
client = StargateClient()
# Bind wallet if configured (needed for write operations like approval)
if AgentConfig.DONATION_ADDRESS:
logger.info(f"Attempting to bind wallet: {AgentConfig.DONATION_ADDRESS}")
client.bind_wallet(AgentConfig.DONATION_ADDRESS)
else:
logger.warning("No DONATION_ADDRESS configured. Write operations might fail.")
watcher = WatcherAgent(client, ai_identifier=AgentConfig.AI_IDENTIFIER) if AgentConfig.WATCHER_ENABLED else None
worker = WorkerAgent(client, ai_identifier=AgentConfig.AI_IDENTIFIER) if AgentConfig.WORKER_ENABLED else None
logger.info(f"Watcher enabled: {AgentConfig.WATCHER_ENABLED}, Worker enabled: {AgentConfig.WORKER_ENABLED}")
while agent_running:
try:
# 1. Worker looks for wishes and creates proposals
if worker:
logger.info("Agent loop iteration: Starting worker.process_wishes()")
worker.process_wishes()
# 2. Watcher looks for proposals (audits/approves them) and tasks
tasks = []
if watcher:
logger.info("Agent loop iteration: Starting watcher.run_once()")
tasks = watcher.run_once()
logger.info(f"Agent loop iteration: Found {len(tasks)} available tasks")
# 3. Worker processes available tasks
if worker:
for i, task in enumerate(tasks):
logger.info(f"Agent loop iteration: Processing task {i+1}/{len(tasks)}")
worker.process_task(task)
# 3. Wait
# Use a loop for sleep to allow faster shutdown
for _ in range(AgentConfig.POLL_INTERVAL):
if not agent_running:
break
time.sleep(1)
# Clear any stale flags that might prevent next iteration
if agent_running:
logger.info("Agent loop iteration completed, starting next cycle")
except Exception as e:
logger.error(f"Agent loop error: {e}")
import traceback
logger.error(f"Agent loop traceback: {traceback.format_exc()}")
time.sleep(5)
except Exception as e:
logger.critical(f"Failed to initialize agents: {e}")
async def restore_existing_functions(app: FastAPI):
"""Discovers and reloads existing api.py files from the results directory."""
logger.info("🔄 Scanning for existing agent APIs to restore...")
try:
requests = dynamic_loader.discover_existing()
count = 0
for req in requests:
try:
# Re-use the loading logic
# For bitcoin_api, we want them under /sandbox/api/handler
req.endpoint_path = f"/sandbox/api/{req.visible_pixel_hash}/{req.function_name}"
loaded_module = dynamic_loader.load_function(req)
func = dynamic_loader.get_function(req.visible_pixel_hash, req.function_name)
if func:
app.add_api_route(
loaded_module.endpoint_path,
func,
methods=[loaded_module.method],
name=f"sandbox_{loaded_module.module_id[:8]}",
operation_id=f"sandbox_api_{loaded_module.visible_pixel_hash}_{loaded_module.function_name}",
include_in_schema=True
)
count += 1
except Exception as e:
logger.warning(f"Failed to restore API for {req.visible_pixel_hash}: {e}")
if count > 0:
logger.info(f"✅ Successfully restored {count} agent APIs.")
app.openapi_schema = None
except Exception as e:
logger.error(f"Error during API restoration: {e}")
# FastAPI application
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
logger.info("Starlight Bitcoin Scanning API starting up...")
# Restore existing functions
await restore_existing_functions(app)
# Start Autonomous Agents
global agent_running, agent_thread
agent_running = True
agent_thread = threading.Thread(target=run_agents_loop, daemon=True)
agent_thread.start()
logger.info("Autonomous agents thread started")
yield
# Shutdown
logger.info("Starlight Bitcoin Scanning API shutting down...")
agent_running = False
if agent_thread:
agent_thread.join(timeout=5)
logger.info("Autonomous agents thread stopped")
app = FastAPI(
title="Starlight Bitcoin Scanning API",
description="API for scanning Bitcoin transactions for steganography",
version="1.0.0",
lifespan=lifespan,
)
@app.middleware("http")
async def metrics_middleware(request, call_next):
start = datetime.utcnow()
response = await call_next(request)
endpoint = request.url.path
status = getattr(response, "status_code", 500)
try:
REQUEST_COUNT.labels(endpoint=endpoint, status=status).inc()
REQUEST_LATENCY.labels(endpoint=endpoint).observe(
(datetime.utcnow() - start).total_seconds()
)
except Exception as e:
logger.debug(f"metrics middleware skipped: {e}")
return response
# Health endpoints
@app.get("/health", response_model=HealthResponse, tags=["Health"])
async def health_check():
"""Service health check with scanner and Bitcoin node status"""
scanner_status = {
"model_loaded": scanner_instance is not None,
"model_version": "v4-prod" if scanner_instance else "none",
"model_path": "models/detector_balanced.pth", # Relative path for security
"device": "cpu", # Would detect actual device
}
bitcoin_status = {
"node_connected": bitcoin_client.connected,
"node_url": bitcoin_client.node_url,
"block_height": await bitcoin_client.get_block_height(),
}
return HealthResponse(
status=(
"healthy" if scanner_instance and bitcoin_client.connected else "degraded"
),
timestamp=datetime.utcnow().isoformat(),
version="1.0.0",
scanner=scanner_status,
bitcoin=bitcoin_status,
)
@app.get("/info", response_model=InfoResponse, tags=["Info"])
async def api_info():
"""API information and capabilities"""
return InfoResponse(
name="Starlight Bitcoin Steganography Scanner",
version="1.0.0",
description="AI-powered steganography detection for Bitcoin transaction images",
supported_formats=["png", "jpg", "jpeg", "gif", "bmp", "webp"],
stego_methods=["alpha", "palette", "lsb.rgb", "exif", "raw"],
max_image_size=10485760, # 10MB
endpoints={
"scan_tx": "/scan/transaction",
"scan_image": "/scan/image",
"batch_scan": "/scan/batch",
"extract": "/extract",
"inscribe": "/inscribe",
},
)
@app.get("/metrics")
async def metrics():
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
# Transaction scanning endpoint
@app.post(
"/scan/transaction", response_model=TransactionScanResponse, tags=["Scanning"]
)
async def scan_transaction(
request: TransactionScanRequest,
background_tasks: BackgroundTasks,
api_key: str = Depends(verify_api_key),
):
"""Scan a Bitcoin transaction for steganography in embedded images"""
start_time = datetime.utcnow()
request_id = str(uuid.uuid4())
try:
# Get transaction data
tx_data = await bitcoin_client.get_transaction(request.transaction_id)
# Extract images from transaction
images = []
if request.extract_images:
extracted_images = await bitcoin_client.extract_images(
request.transaction_id
)
for img_data in extracted_images:
# Scan image asynchronously
scan_result = await scan_image_async(
img_data["data"], request.scan_options, request_id, filename=f"tx_{request.transaction_id}_{img_data['index']}.{img_data['format']}"
)
images.append(
ImageScanResult(
index=img_data["index"],
size_bytes=img_data["size_bytes"],
format=img_data["format"],
scan_result=scan_result,
)
)
# Calculate summary
stego_detected = any(img.scan_result.is_stego for img in images)
processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
scan_summary = {
"images_found": len(images),
"images_scanned": len(images),
"stego_detected": stego_detected,
"processing_time_ms": processing_time,
}
return TransactionScanResponse(
transaction_id=request.transaction_id,
block_height=tx_data["block_height"],
timestamp=tx_data["timestamp"],
scan_results=scan_summary,
images=images,
request_id=request_id,
)
except Exception as e:
logger.error(f"Error scanning transaction {request.transaction_id}: {e}")
raise HTTPException(
status_code=500, detail=f"Transaction scan failed: {str(e)}"
)
# Direct image scanning endpoint
@app.post("/scan/image", response_model=DirectImageScanResponse, tags=["Scanning"])
async def scan_image(
image: UploadFile = File(...),
extract_message: bool = Form(True),
confidence_threshold: float = Form(0.5),
include_metadata: bool = Form(True),
api_key: str = Depends(verify_api_key),
):
"""Scan a directly uploaded image for steganography"""
start_time = datetime.utcnow()
request_id = str(uuid.uuid4())
try:
# Read image data
image_data = await image.read()
# Validate image size
if len(image_data) > 10485760: # 10MB limit
raise HTTPException(status_code=413, detail="Image too large")
# Create scan options
options = ScanOptions(
extract_message=extract_message,
confidence_threshold=confidence_threshold,
include_metadata=include_metadata,
)
# Scan image
scan_result = await scan_image_async(image_data, options, request_id, filename=filename)
# Get image info
filename = image.filename or "unknown"
image_info = {
"filename": filename,
"size_bytes": len(image_data),
"format": filename.split(".")[-1].lower() if "." in filename else "unknown",
}
processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
return DirectImageScanResponse(
scan_result=scan_result,
image_info=image_info,
processing_time_ms=processing_time,
request_id=request_id,
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error scanning image: {e}")
raise HTTPException(status_code=500, detail=f"Image scan failed: {str(e)}")
# Inscription preparation endpoint (embed text into image and save for Stargate upload)
@app.post("/inscribe", response_model=InscribeResponse, tags=["Inscribe"])
async def inscribe_image(
image: UploadFile = File(...),
message: str = Form(...),
method: str = Form("alpha"),
api_key: str = Depends(verify_api_key),
):
"""Embed a text message into an image and save it for Stargate to broadcast."""
request_id = str(uuid.uuid4())
try:
if not message:
raise HTTPException(
status_code=400, detail="Message is required for inscription"
)
image_bytes = await image.read()
if len(image_bytes) > 10485760:
raise HTTPException(status_code=413, detail="Image too large")
try:
stego_bytes, output_format = embed_message_to_image(
image_bytes, method, message
)
except ValueError as ve:
raise HTTPException(status_code=400, detail=str(ve))
except RuntimeError as re:
raise HTTPException(status_code=503, detail=str(re))
filename = image.filename or "inscribe.png"
safe_name = os.path.basename(filename) or "inscribe.png"
if output_format:
ext_map = {"JPEG": ".jpg", "PNG": ".png", "GIF": ".gif"}
new_ext = ext_map.get(output_format)
if new_ext:
base, _ = os.path.splitext(safe_name)
safe_name = base + new_ext
# Optional direct handoff to Stargate via REST
ingest_url = os.environ.get("STARGATE_INGEST_URL")
ingest_token = os.environ.get("STARGATE_INGEST_TOKEN", "")
ingest_result = None
if ingest_url:
try:
payload = {
"id": request_id,
"filename": safe_name,
"method": method,
"message_length": len(message.encode("utf-8")),
"image_base64": base64.b64encode(stego_bytes).decode("utf-8"),
# Include the embedded message so Stargate can surface it in pending UI
"metadata": {"embedded_message": message},
}
headers = {"Content-Type": "application/json"}
if ingest_token:
headers["X-Ingest-Token"] = ingest_token
resp = requests.post(
ingest_url, json=payload, headers=headers, timeout=10
)
ingest_result = {"status_code": resp.status_code, "response": resp.text}
except Exception as e:
ingest_result = {"error": str(e)}
# Calculate SHA256 hash of the inscribed image
image_sha256 = hashlib.sha256(stego_bytes).hexdigest()
response_payload = {
"request_id": request_id,
"method": method,
"message_length": len(message.encode("utf-8")),
"output_file": safe_name,
"image_bytes": len(stego_bytes),
"image_sha256": image_sha256,
"image_base64": base64.b64encode(stego_bytes).decode("utf-8"),
"status": "ingested" if ingest_result else "pending_upload",
"note": (
"Ingested to Stargate via REST"
if ingest_result
else "No ingest URL configured"
),
"ingest": ingest_result,
}
return InscribeResponse(**response_payload)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error embedding inscription: {e}")
raise HTTPException(status_code=500, detail=f"Inscribe failed: {str(e)}")