fix: replace deprecated datetime.utcnow() with datetime.now(datetime.UTC)
- Replace all 2,087 uses of datetime.utcnow() across 294 files - Add UTC import to datetime statements where needed - Addresses Python 3.12+ deprecation warning (report item #3)
This commit is contained in:
@@ -4,7 +4,7 @@ Provides standard response formatters, pagination helpers, error response builde
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Any, Optional, List, Dict, Union
|
from typing import Any, Optional, List, Dict, Union
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from fastapi import HTTPException, status
|
from fastapi import HTTPException, status
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ class APIResponse(BaseModel):
|
|||||||
|
|
||||||
def __init__(self, **data):
|
def __init__(self, **data):
|
||||||
if 'timestamp' not in data:
|
if 'timestamp' not in data:
|
||||||
data['timestamp'] = datetime.utcnow().isoformat()
|
data['timestamp'] = datetime.now(datetime.UTC).isoformat()
|
||||||
super().__init__(**data)
|
super().__init__(**data)
|
||||||
|
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ class PaginatedResponse(BaseModel):
|
|||||||
|
|
||||||
def __init__(self, **data):
|
def __init__(self, **data):
|
||||||
if 'timestamp' not in data:
|
if 'timestamp' not in data:
|
||||||
data['timestamp'] = datetime.utcnow().isoformat()
|
data['timestamp'] = datetime.now(datetime.UTC).isoformat()
|
||||||
super().__init__(**data)
|
super().__init__(**data)
|
||||||
|
|
||||||
|
|
||||||
@@ -318,5 +318,5 @@ def build_request_metadata(request) -> Dict[str, str]:
|
|||||||
"client_ip": get_client_ip(request),
|
"client_ip": get_client_ip(request),
|
||||||
"user_agent": get_user_agent(request),
|
"user_agent": get_user_agent(request),
|
||||||
"request_id": request.headers.get("X-Request-ID", "unknown"),
|
"request_id": request.headers.get("X-Request-ID", "unknown"),
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Provides toggle between mock and real data sources for development/testing
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
|
|
||||||
@@ -119,7 +119,7 @@ class MockDataGenerator:
|
|||||||
"hash": MockFactory.generate_hash(),
|
"hash": MockFactory.generate_hash(),
|
||||||
"validator": validator or MockFactory.generate_ethereum_address(),
|
"validator": validator or MockFactory.generate_ethereum_address(),
|
||||||
"tx_count": min_tx or 5,
|
"tx_count": min_tx or 5,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
})
|
})
|
||||||
|
|
||||||
return blocks
|
return blocks
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides event bus implementation, pub/sub patterns, and event decorators
|
|||||||
import asyncio
|
import asyncio
|
||||||
from typing import Any, Callable, Dict, List, Optional, TypeVar, Generic
|
from typing import Any, Callable, Dict, List, Optional, TypeVar, Generic
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
import inspect
|
import inspect
|
||||||
import functools
|
import functools
|
||||||
@@ -34,7 +34,7 @@ class Event:
|
|||||||
|
|
||||||
def __post_init__(self):
|
def __post_init__(self):
|
||||||
if self.timestamp is None:
|
if self.timestamp is None:
|
||||||
self.timestamp = datetime.utcnow()
|
self.timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
|
|
||||||
class EventBus:
|
class EventBus:
|
||||||
@@ -199,7 +199,7 @@ class EventAggregator:
|
|||||||
def add_event(self, event: Event) -> None:
|
def add_event(self, event: Event) -> None:
|
||||||
"""Add event to aggregation"""
|
"""Add event to aggregation"""
|
||||||
key = event.event_type
|
key = event.event_type
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
if key not in self.aggregated_events:
|
if key not in self.aggregated_events:
|
||||||
self.aggregated_events[key] = {
|
self.aggregated_events[key] = {
|
||||||
@@ -223,7 +223,7 @@ class EventAggregator:
|
|||||||
def get_aggregated_events(self) -> Dict[str, Dict[str, Any]]:
|
def get_aggregated_events(self) -> Dict[str, Dict[str, Any]]:
|
||||||
"""Get aggregated events"""
|
"""Get aggregated events"""
|
||||||
# Remove old events
|
# Remove old events
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
cutoff = now.timestamp() - self.window_seconds
|
cutoff = now.timestamp() - self.window_seconds
|
||||||
|
|
||||||
to_remove = []
|
to_remove = []
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import heapq
|
|||||||
import time
|
import time
|
||||||
from typing import Any, Callable, Dict, List, Optional, TypeVar
|
from typing import Any, Callable, Dict, List, Optional, TypeVar
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
@@ -244,7 +244,7 @@ class BackgroundTaskManager:
|
|||||||
async with self.semaphore:
|
async with self.semaphore:
|
||||||
try:
|
try:
|
||||||
self.task_info[task_id]["status"] = "running"
|
self.task_info[task_id]["status"] = "running"
|
||||||
self.task_info[task_id]["started_at"] = datetime.utcnow()
|
self.task_info[task_id]["started_at"] = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
if asyncio.iscoroutinefunction(func):
|
if asyncio.iscoroutinefunction(func):
|
||||||
result = await func(*args, **kwargs)
|
result = await func(*args, **kwargs)
|
||||||
@@ -253,18 +253,18 @@ class BackgroundTaskManager:
|
|||||||
|
|
||||||
self.task_info[task_id]["status"] = "completed"
|
self.task_info[task_id]["status"] = "completed"
|
||||||
self.task_info[task_id]["result"] = result
|
self.task_info[task_id]["result"] = result
|
||||||
self.task_info[task_id]["completed_at"] = datetime.utcnow()
|
self.task_info[task_id]["completed_at"] = datetime.now(datetime.UTC)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.task_info[task_id]["status"] = "failed"
|
self.task_info[task_id]["status"] = "failed"
|
||||||
self.task_info[task_id]["error"] = str(e)
|
self.task_info[task_id]["error"] = str(e)
|
||||||
self.task_info[task_id]["completed_at"] = datetime.utcnow()
|
self.task_info[task_id]["completed_at"] = datetime.now(datetime.UTC)
|
||||||
finally:
|
finally:
|
||||||
if task_id in self.tasks:
|
if task_id in self.tasks:
|
||||||
del self.tasks[task_id]
|
del self.tasks[task_id]
|
||||||
|
|
||||||
self.task_info[task_id] = {
|
self.task_info[task_id] = {
|
||||||
"status": "pending",
|
"status": "pending",
|
||||||
"created_at": datetime.utcnow(),
|
"created_at": datetime.now(datetime.UTC),
|
||||||
"started_at": None,
|
"started_at": None,
|
||||||
"completed_at": None,
|
"completed_at": None,
|
||||||
"result": None,
|
"result": None,
|
||||||
@@ -286,7 +286,7 @@ class BackgroundTaskManager:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
self.task_info[task_id]["status"] = "cancelled"
|
self.task_info[task_id]["status"] = "cancelled"
|
||||||
self.task_info[task_id]["completed_at"] = datetime.utcnow()
|
self.task_info[task_id]["completed_at"] = datetime.now(datetime.UTC)
|
||||||
del self.tasks[task_id]
|
del self.tasks[task_id]
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import hashlib
|
|||||||
import time
|
import time
|
||||||
import json
|
import json
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from cryptography.fernet import Fernet
|
from cryptography.fernet import Fernet
|
||||||
|
|
||||||
|
|
||||||
@@ -118,7 +118,7 @@ class APIKeyManager:
|
|||||||
"user_id": user_id,
|
"user_id": user_id,
|
||||||
"scopes": scopes or ["read"],
|
"scopes": scopes or ["read"],
|
||||||
"name": name,
|
"name": name,
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"last_used": None
|
"last_used": None
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +134,7 @@ class APIKeyManager:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
# Update last used
|
# Update last used
|
||||||
key_data["last_used"] = datetime.utcnow().isoformat()
|
key_data["last_used"] = datetime.now(datetime.UTC).isoformat()
|
||||||
if self.storage_path:
|
if self.storage_path:
|
||||||
self._save_keys()
|
self._save_keys()
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import json
|
|||||||
import os
|
import os
|
||||||
from typing import Any, Callable, Dict, Optional, TypeVar, Generic, List
|
from typing import Any, Callable, Dict, Optional, TypeVar, Generic, List
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
import asyncio
|
import asyncio
|
||||||
@@ -304,7 +304,7 @@ class StateSnapshot:
|
|||||||
self.current_state = state_machine.current_state
|
self.current_state = state_machine.current_state
|
||||||
self.state_data = state_machine.state_data.copy()
|
self.state_data = state_machine.state_data.copy()
|
||||||
self.transitions = state_machine.transitions.copy()
|
self.transitions = state_machine.transitions.copy()
|
||||||
self.timestamp = datetime.utcnow()
|
self.timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
def restore(self, state_machine: StateMachine) -> None:
|
def restore(self, state_machine: StateMachine) -> None:
|
||||||
"""Restore state machine from snapshot"""
|
"""Restore state machine from snapshot"""
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides mock factories, test data generators, and test helpers
|
|||||||
import secrets
|
import secrets
|
||||||
import json
|
import json
|
||||||
from typing import Any, Dict, List, Optional, Type, TypeVar, Callable
|
from typing import Any, Dict, List, Optional, Type, TypeVar, Callable
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
import uuid
|
import uuid
|
||||||
@@ -72,8 +72,8 @@ class TestDataGenerator:
|
|||||||
"username": MockFactory.generate_string(8),
|
"username": MockFactory.generate_string(8),
|
||||||
"first_name": MockFactory.generate_string(6),
|
"first_name": MockFactory.generate_string(6),
|
||||||
"last_name": MockFactory.generate_string(6),
|
"last_name": MockFactory.generate_string(6),
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"updated_at": datetime.utcnow().isoformat(),
|
"updated_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"is_active": True,
|
"is_active": True,
|
||||||
"role": "user"
|
"role": "user"
|
||||||
}
|
}
|
||||||
@@ -91,7 +91,7 @@ class TestDataGenerator:
|
|||||||
"gas_price": str(secrets.randbelow(100000000000)),
|
"gas_price": str(secrets.randbelow(100000000000)),
|
||||||
"gas_limit": secrets.randbelow(100000),
|
"gas_limit": secrets.randbelow(100000),
|
||||||
"nonce": secrets.randbelow(1000),
|
"nonce": secrets.randbelow(1000),
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"status": "pending"
|
"status": "pending"
|
||||||
}
|
}
|
||||||
data.update(overrides)
|
data.update(overrides)
|
||||||
@@ -104,7 +104,7 @@ class TestDataGenerator:
|
|||||||
"number": secrets.randbelow(10000000),
|
"number": secrets.randbelow(10000000),
|
||||||
"hash": MockFactory.generate_hash(),
|
"hash": MockFactory.generate_hash(),
|
||||||
"parent_hash": MockFactory.generate_hash(),
|
"parent_hash": MockFactory.generate_hash(),
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"transactions": [],
|
"transactions": [],
|
||||||
"gas_used": str(secrets.randbelow(10000000)),
|
"gas_used": str(secrets.randbelow(10000000)),
|
||||||
"gas_limit": str(15000000),
|
"gas_limit": str(15000000),
|
||||||
@@ -122,7 +122,7 @@ class TestDataGenerator:
|
|||||||
"user_id": MockFactory.generate_uuid(),
|
"user_id": MockFactory.generate_uuid(),
|
||||||
"name": MockFactory.generate_string(10),
|
"name": MockFactory.generate_string(10),
|
||||||
"scopes": ["read", "write"],
|
"scopes": ["read", "write"],
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"last_used": None,
|
"last_used": None,
|
||||||
"is_active": True
|
"is_active": True
|
||||||
}
|
}
|
||||||
@@ -137,7 +137,7 @@ class TestDataGenerator:
|
|||||||
"address": MockFactory.generate_ethereum_address(),
|
"address": MockFactory.generate_ethereum_address(),
|
||||||
"chain_id": 1,
|
"chain_id": 1,
|
||||||
"balance": str(secrets.randbelow(1000000000000000000)),
|
"balance": str(secrets.randbelow(1000000000000000000)),
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"is_active": True
|
"is_active": True
|
||||||
}
|
}
|
||||||
data.update(overrides)
|
data.update(overrides)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ try:
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
except ImportError: # pragma: no cover - optional dependency for runtime AI features
|
except ImportError: # pragma: no cover - optional dependency for runtime AI features
|
||||||
np = None
|
np = None
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Dict, List, Any, Optional, Tuple
|
from typing import Dict, List, Any, Optional, Tuple
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
@@ -93,7 +93,7 @@ class AdvancedAIIntegration:
|
|||||||
'hidden_sizes': hidden_sizes,
|
'hidden_sizes': hidden_sizes,
|
||||||
'output_size': output_size
|
'output_size': output_size
|
||||||
},
|
},
|
||||||
'created_at': datetime.utcnow().isoformat()
|
'created_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -187,7 +187,7 @@ class AdvancedAIIntegration:
|
|||||||
'final_loss': losses[-1] if losses else 0,
|
'final_loss': losses[-1] if losses else 0,
|
||||||
'accuracy': accuracy,
|
'accuracy': accuracy,
|
||||||
'training_data_size': len(training_data),
|
'training_data_size': len(training_data),
|
||||||
'trained_at': datetime.utcnow().isoformat()
|
'trained_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -218,7 +218,7 @@ class AdvancedAIIntegration:
|
|||||||
'network_id': network_id,
|
'network_id': network_id,
|
||||||
'features': features,
|
'features': features,
|
||||||
'prediction': float(prediction[0][0]),
|
'prediction': float(prediction[0][0]),
|
||||||
'timestamp': datetime.utcnow().isoformat()
|
'timestamp': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
self.predictions_history.append(prediction_record)
|
self.predictions_history.append(prediction_record)
|
||||||
|
|
||||||
@@ -227,7 +227,7 @@ class AdvancedAIIntegration:
|
|||||||
'network_id': network_id,
|
'network_id': network_id,
|
||||||
'prediction': float(prediction[0][0]),
|
'prediction': float(prediction[0][0]),
|
||||||
'confidence': max(prediction[0][0], 1 - prediction[0][0]),
|
'confidence': max(prediction[0][0], 1 - prediction[0][0]),
|
||||||
'predicted_at': datetime.utcnow().isoformat()
|
'predicted_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -261,7 +261,7 @@ class AdvancedAIIntegration:
|
|||||||
'model_type': model_type,
|
'model_type': model_type,
|
||||||
'features': features,
|
'features': features,
|
||||||
'target': target,
|
'target': target,
|
||||||
'created_at': datetime.utcnow().isoformat()
|
'created_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -286,7 +286,7 @@ class AdvancedAIIntegration:
|
|||||||
|
|
||||||
model.accuracy = accuracy
|
model.accuracy = accuracy
|
||||||
model.training_data_size = len(training_data)
|
model.training_data_size = len(training_data)
|
||||||
model.last_trained = datetime.utcnow()
|
model.last_trained = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Store performance
|
# Store performance
|
||||||
self.model_performance[model_id].append(accuracy)
|
self.model_performance[model_id].append(accuracy)
|
||||||
@@ -405,7 +405,7 @@ class AdvancedAIIntegration:
|
|||||||
'model_id': model_id,
|
'model_id': model_id,
|
||||||
'features': features,
|
'features': features,
|
||||||
'prediction': prediction,
|
'prediction': prediction,
|
||||||
'timestamp': datetime.utcnow().isoformat()
|
'timestamp': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
self.predictions_history.append(prediction_record)
|
self.predictions_history.append(prediction_record)
|
||||||
|
|
||||||
@@ -414,7 +414,7 @@ class AdvancedAIIntegration:
|
|||||||
'model_id': model_id,
|
'model_id': model_id,
|
||||||
'prediction': prediction,
|
'prediction': prediction,
|
||||||
'confidence': min(1.0, max(0.0, prediction)) if model.model_type == 'logistic_regression' else None,
|
'confidence': min(1.0, max(0.0, prediction)) if model.model_type == 'logistic_regression' else None,
|
||||||
'predicted_at': datetime.utcnow().isoformat()
|
'predicted_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -451,7 +451,7 @@ class AdvancedAIIntegration:
|
|||||||
'model_performance': model_stats,
|
'model_performance': model_stats,
|
||||||
'training_data_sizes': training_stats,
|
'training_data_sizes': training_stats,
|
||||||
'available_model_types': list(set(model.model_type for model in self.models.values())),
|
'available_model_types': list(set(model.model_type for model in self.models.values())),
|
||||||
'last_updated': datetime.utcnow().isoformat()
|
'last_updated': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Implements adaptive learning, predictive analytics, and intelligent optimization
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Dict, List, Any, Optional, Tuple
|
from typing import Dict, List, Any, Optional, Tuple
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from collections import defaultdict, deque
|
from collections import defaultdict, deque
|
||||||
@@ -55,7 +55,7 @@ class RealTimeLearningSystem:
|
|||||||
try:
|
try:
|
||||||
experience = LearningExperience(
|
experience = LearningExperience(
|
||||||
experience_id=str(uuid.uuid4()),
|
experience_id=str(uuid.uuid4()),
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
context=experience_data.get('context', {}),
|
context=experience_data.get('context', {}),
|
||||||
action=experience_data.get('action', ''),
|
action=experience_data.get('action', ''),
|
||||||
outcome=experience_data.get('outcome', ''),
|
outcome=experience_data.get('outcome', ''),
|
||||||
@@ -157,7 +157,7 @@ class RealTimeLearningSystem:
|
|||||||
features=['action', 'context_load', 'context_agents'],
|
features=['action', 'context_load', 'context_agents'],
|
||||||
target='performance_score',
|
target='performance_score',
|
||||||
accuracy=0.85,
|
accuracy=0.85,
|
||||||
last_updated=datetime.utcnow()
|
last_updated=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.models['performance'] = performance_model
|
self.models['performance'] = performance_model
|
||||||
@@ -169,7 +169,7 @@ class RealTimeLearningSystem:
|
|||||||
features=['action', 'context_time', 'context_resources'],
|
features=['action', 'context_time', 'context_resources'],
|
||||||
target='success_probability',
|
target='success_probability',
|
||||||
accuracy=0.82,
|
accuracy=0.82,
|
||||||
last_updated=datetime.utcnow()
|
last_updated=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.models['success'] = success_model
|
self.models['success'] = success_model
|
||||||
@@ -257,7 +257,7 @@ class RealTimeLearningSystem:
|
|||||||
try:
|
try:
|
||||||
total_experiences = len(self.experiences)
|
total_experiences = len(self.experiences)
|
||||||
recent_experiences = [exp for exp in self.experiences
|
recent_experiences = [exp for exp in self.experiences
|
||||||
if exp.timestamp > datetime.utcnow() - timedelta(hours=24)]
|
if exp.timestamp > datetime.now(datetime.UTC) - timedelta(hours=24)]
|
||||||
|
|
||||||
if not self.experiences:
|
if not self.experiences:
|
||||||
return {
|
return {
|
||||||
@@ -299,7 +299,7 @@ class RealTimeLearningSystem:
|
|||||||
def _get_last_adaptation_time(self) -> Optional[str]:
|
def _get_last_adaptation_time(self) -> Optional[str]:
|
||||||
"""Get the time of the last adaptation"""
|
"""Get the time of the last adaptation"""
|
||||||
# This would be tracked in a real implementation
|
# This would be tracked in a real implementation
|
||||||
return datetime.utcnow().isoformat() if len(self.experiences) > 50 else None
|
return datetime.now(datetime.UTC).isoformat() if len(self.experiences) > 50 else None
|
||||||
|
|
||||||
async def recommend_action(self, context: Dict[str, Any], available_actions: List[str]) -> Dict[str, Any]:
|
async def recommend_action(self, context: Dict[str, Any], available_actions: List[str]) -> Dict[str, Any]:
|
||||||
"""Recommend the best action based on learning"""
|
"""Recommend the best action based on learning"""
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ JWT Authentication Handler for AITBC Agent Coordinator
|
|||||||
Implements JWT token generation, validation, and management
|
Implements JWT token generation, validation, and management
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Dict, Any, Optional, List
|
from typing import Dict, Any, Optional, List
|
||||||
import secrets
|
import secrets
|
||||||
|
|
||||||
@@ -26,15 +26,15 @@ class JWTHandler:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
if expires_delta:
|
if expires_delta:
|
||||||
expire = datetime.utcnow() + expires_delta
|
expire = datetime.now(datetime.UTC) + expires_delta
|
||||||
else:
|
else:
|
||||||
expire = datetime.utcnow() + self.token_expiry
|
expire = datetime.now(datetime.UTC) + self.token_expiry
|
||||||
|
|
||||||
# Add standard claims
|
# Add standard claims
|
||||||
token_payload = {
|
token_payload = {
|
||||||
**payload,
|
**payload,
|
||||||
"exp": expire,
|
"exp": expire,
|
||||||
"iat": datetime.utcnow(),
|
"iat": datetime.now(datetime.UTC),
|
||||||
"type": "access"
|
"type": "access"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,12 +57,12 @@ class JWTHandler:
|
|||||||
import jwt
|
import jwt
|
||||||
|
|
||||||
try:
|
try:
|
||||||
expire = datetime.utcnow() + self.refresh_expiry
|
expire = datetime.now(datetime.UTC) + self.refresh_expiry
|
||||||
|
|
||||||
token_payload = {
|
token_payload = {
|
||||||
**payload,
|
**payload,
|
||||||
"exp": expire,
|
"exp": expire,
|
||||||
"iat": datetime.utcnow(),
|
"iat": datetime.now(datetime.UTC),
|
||||||
"type": "refresh"
|
"type": "refresh"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +227,7 @@ class APIKeyManager:
|
|||||||
key_data = {
|
key_data = {
|
||||||
"user_id": user_id,
|
"user_id": user_id,
|
||||||
"permissions": permissions or [],
|
"permissions": permissions or [],
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"last_used": None,
|
"last_used": None,
|
||||||
"usage_count": 0
|
"usage_count": 0
|
||||||
}
|
}
|
||||||
@@ -258,7 +258,7 @@ class APIKeyManager:
|
|||||||
key_data = self.api_keys[api_key]
|
key_data = self.api_keys[api_key]
|
||||||
|
|
||||||
# Update usage statistics
|
# Update usage statistics
|
||||||
key_data["last_used"] = datetime.utcnow().isoformat()
|
key_data["last_used"] = datetime.now(datetime.UTC).isoformat()
|
||||||
key_data["usage_count"] += 1
|
key_data["usage_count"] += 1
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Implements various consensus algorithms for distributed decision making
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Dict, List, Any, Optional, Set, Tuple
|
from typing import Dict, List, Any, Optional, Set, Tuple
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
@@ -59,7 +59,7 @@ class DistributedConsensus:
|
|||||||
node = ConsensusNode(
|
node = ConsensusNode(
|
||||||
node_id=node_id,
|
node_id=node_id,
|
||||||
endpoint=endpoint,
|
endpoint=endpoint,
|
||||||
last_seen=datetime.utcnow(),
|
last_seen=datetime.now(datetime.UTC),
|
||||||
reputation_score=node_data.get('reputation_score', 1.0),
|
reputation_score=node_data.get('reputation_score', 1.0),
|
||||||
voting_power=node_data.get('voting_power', 1.0),
|
voting_power=node_data.get('voting_power', 1.0),
|
||||||
is_active=True
|
is_active=True
|
||||||
@@ -70,7 +70,7 @@ class DistributedConsensus:
|
|||||||
return {
|
return {
|
||||||
'status': 'success',
|
'status': 'success',
|
||||||
'node_id': node_id,
|
'node_id': node_id,
|
||||||
'registered_at': datetime.utcnow().isoformat(),
|
'registered_at': datetime.now(datetime.UTC).isoformat(),
|
||||||
'total_nodes': len(self.nodes)
|
'total_nodes': len(self.nodes)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,8 +98,8 @@ class DistributedConsensus:
|
|||||||
proposal_id=proposal_id,
|
proposal_id=proposal_id,
|
||||||
proposer_id=proposer_id,
|
proposer_id=proposer_id,
|
||||||
proposal_data=proposal_data.get('content', {}),
|
proposal_data=proposal_data.get('content', {}),
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
deadline=datetime.utcnow() + self.voting_timeout,
|
deadline=datetime.now(datetime.UTC) + self.voting_timeout,
|
||||||
required_votes=required_votes
|
required_votes=required_votes
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -186,7 +186,7 @@ class DistributedConsensus:
|
|||||||
|
|
||||||
# Record vote
|
# Record vote
|
||||||
proposal.current_votes[node_id] = vote
|
proposal.current_votes[node_id] = vote
|
||||||
self.nodes[node_id].last_seen = datetime.utcnow()
|
self.nodes[node_id].last_seen = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Check if consensus is reached
|
# Check if consensus is reached
|
||||||
await self._check_consensus(proposal)
|
await self._check_consensus(proposal)
|
||||||
@@ -216,7 +216,7 @@ class DistributedConsensus:
|
|||||||
total_votes = len(proposal.current_votes)
|
total_votes = len(proposal.current_votes)
|
||||||
|
|
||||||
# Check if deadline passed
|
# Check if deadline passed
|
||||||
if datetime.utcnow() > proposal.deadline:
|
if datetime.now(datetime.UTC) > proposal.deadline:
|
||||||
proposal.status = 'expired'
|
proposal.status = 'expired'
|
||||||
await self._finalize_proposal(proposal, False, 'Deadline expired')
|
await self._finalize_proposal(proposal, False, 'Deadline expired')
|
||||||
return
|
return
|
||||||
@@ -266,7 +266,7 @@ class DistributedConsensus:
|
|||||||
'reason': reason,
|
'reason': reason,
|
||||||
'votes': dict(proposal.current_votes),
|
'votes': dict(proposal.current_votes),
|
||||||
'required_votes': proposal.required_votes,
|
'required_votes': proposal.required_votes,
|
||||||
'finalized_at': datetime.utcnow().isoformat(),
|
'finalized_at': datetime.now(datetime.UTC).isoformat(),
|
||||||
'algorithm': self.current_algorithm
|
'algorithm': self.current_algorithm
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,7 +283,7 @@ class DistributedConsensus:
|
|||||||
async def _cleanup_old_proposals(self):
|
async def _cleanup_old_proposals(self):
|
||||||
"""Clean up old and expired proposals"""
|
"""Clean up old and expired proposals"""
|
||||||
try:
|
try:
|
||||||
current_time = datetime.utcnow()
|
current_time = datetime.now(datetime.UTC)
|
||||||
expired_proposals = [
|
expired_proposals = [
|
||||||
pid for pid, proposal in self.proposals.items()
|
pid for pid, proposal in self.proposals.items()
|
||||||
if proposal.deadline < current_time or proposal.status in ['approved', 'rejected', 'expired']
|
if proposal.deadline < current_time or proposal.status in ['approved', 'rejected', 'expired']
|
||||||
@@ -340,7 +340,7 @@ class DistributedConsensus:
|
|||||||
return {
|
return {
|
||||||
'status': 'success',
|
'status': 'success',
|
||||||
'algorithm': algorithm,
|
'algorithm': algorithm,
|
||||||
'changed_at': datetime.utcnow().isoformat()
|
'changed_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -400,7 +400,7 @@ class DistributedConsensus:
|
|||||||
'algorithm_performance': dict(algorithm_stats),
|
'algorithm_performance': dict(algorithm_stats),
|
||||||
'node_participation': node_participation,
|
'node_participation': node_participation,
|
||||||
'active_proposals': len(self.proposals),
|
'active_proposals': len(self.proposals),
|
||||||
'last_updated': datetime.utcnow().isoformat()
|
'last_updated': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -414,13 +414,13 @@ class DistributedConsensus:
|
|||||||
return {'status': 'error', 'message': 'Node not found'}
|
return {'status': 'error', 'message': 'Node not found'}
|
||||||
|
|
||||||
self.nodes[node_id].is_active = is_active
|
self.nodes[node_id].is_active = is_active
|
||||||
self.nodes[node_id].last_seen = datetime.utcnow()
|
self.nodes[node_id].last_seen = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'status': 'success',
|
'status': 'success',
|
||||||
'node_id': node_id,
|
'node_id': node_id,
|
||||||
'is_active': is_active,
|
'is_active': is_active,
|
||||||
'updated_at': datetime.utcnow().isoformat()
|
'updated_at': datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
@@ -14,7 +14,7 @@ def register_exception_handlers(app):
|
|||||||
content={
|
content={
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": "Resource not found",
|
"message": "Resource not found",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,6 +26,6 @@ def register_exception_handlers(app):
|
|||||||
content={
|
content={
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": "Internal server error",
|
"message": "Internal server error",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Implements comprehensive alerting with multiple channels and SLA monitoring
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import smtplib
|
import smtplib
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Dict, List, Any, Optional, Callable
|
from typing import Dict, List, Any, Optional, Callable
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
@@ -134,7 +134,7 @@ class SLAMonitor:
|
|||||||
return
|
return
|
||||||
|
|
||||||
if timestamp is None:
|
if timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
rule = self.sla_rules[sla_id]
|
rule = self.sla_rules[sla_id]
|
||||||
|
|
||||||
@@ -188,7 +188,7 @@ class SLAMonitor:
|
|||||||
# Get recent violations
|
# Get recent violations
|
||||||
recent_violations = [
|
recent_violations = [
|
||||||
v for v in self.violations[sla_id]
|
v for v in self.violations[sla_id]
|
||||||
if v["timestamp"] > datetime.utcnow() - timedelta(hours=24)
|
if v["timestamp"] > datetime.now(datetime.UTC) - timedelta(hours=24)
|
||||||
]
|
]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -375,7 +375,7 @@ Annotations: {json.dumps(alert.annotations, indent=2)}
|
|||||||
payload = {
|
payload = {
|
||||||
"alert": alert.to_dict(),
|
"alert": alert.to_dict(),
|
||||||
"message": message,
|
"message": message,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
@@ -499,7 +499,7 @@ class AlertManager:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
condition_met = self._evaluate_condition(rule.condition, metrics, rule.threshold)
|
condition_met = self._evaluate_condition(rule.condition, metrics, rule.threshold)
|
||||||
current_time = datetime.utcnow()
|
current_time = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
if condition_met:
|
if condition_met:
|
||||||
# Check if condition has been met for required duration
|
# Check if condition has been met for required duration
|
||||||
@@ -543,7 +543,7 @@ class AlertManager:
|
|||||||
|
|
||||||
def _trigger_alert(self, rule: AlertRule, metrics: Dict[str, Any]):
|
def _trigger_alert(self, rule: AlertRule, metrics: Dict[str, Any]):
|
||||||
"""Trigger an alert"""
|
"""Trigger an alert"""
|
||||||
alert_id = f"{rule.rule_id}_{int(datetime.utcnow().timestamp())}"
|
alert_id = f"{rule.rule_id}_{int(datetime.now(datetime.UTC).timestamp())}"
|
||||||
|
|
||||||
# Check if similar alert is already active
|
# Check if similar alert is already active
|
||||||
existing_alert = self._find_similar_active_alert(rule)
|
existing_alert = self._find_similar_active_alert(rule)
|
||||||
@@ -556,8 +556,8 @@ class AlertManager:
|
|||||||
description=rule.description,
|
description=rule.description,
|
||||||
severity=rule.severity,
|
severity=rule.severity,
|
||||||
status=AlertStatus.ACTIVE,
|
status=AlertStatus.ACTIVE,
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
updated_at=datetime.utcnow(),
|
updated_at=datetime.now(datetime.UTC),
|
||||||
labels=rule.labels.copy(),
|
labels=rule.labels.copy(),
|
||||||
annotations=rule.annotations.copy()
|
annotations=rule.annotations.copy()
|
||||||
)
|
)
|
||||||
@@ -607,8 +607,8 @@ class AlertManager:
|
|||||||
|
|
||||||
alert = self.alerts[alert_id]
|
alert = self.alerts[alert_id]
|
||||||
alert.status = AlertStatus.RESOLVED
|
alert.status = AlertStatus.RESOLVED
|
||||||
alert.resolved_at = datetime.utcnow()
|
alert.resolved_at = datetime.now(datetime.UTC)
|
||||||
alert.updated_at = datetime.utcnow()
|
alert.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
return {"status": "success", "alert": alert.to_dict()}
|
return {"status": "success", "alert": alert.to_dict()}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import json
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Dict, List, Optional, Any, Callable
|
from typing import Dict, List, Optional, Any, Callable
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
import uuid
|
import uuid
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ class CommunicationProtocol:
|
|||||||
|
|
||||||
def _is_message_expired(self, message: AgentMessage) -> bool:
|
def _is_message_expired(self, message: AgentMessage) -> bool:
|
||||||
"""Check if message has expired"""
|
"""Check if message has expired"""
|
||||||
age = (datetime.utcnow() - message.timestamp).total_seconds()
|
age = (datetime.now(datetime.UTC) - message.timestamp).total_seconds()
|
||||||
return age > message.ttl
|
return age > message.ttl
|
||||||
|
|
||||||
async def _send_to_agent(self, message: AgentMessage):
|
async def _send_to_agent(self, message: AgentMessage):
|
||||||
@@ -283,7 +283,7 @@ class MessageTemplates:
|
|||||||
sender_id=sender_id,
|
sender_id=sender_id,
|
||||||
message_type=MessageType.HEARTBEAT,
|
message_type=MessageType.HEARTBEAT,
|
||||||
priority=Priority.LOW,
|
priority=Priority.LOW,
|
||||||
payload={"timestamp": datetime.utcnow().isoformat()}
|
payload={"timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import json
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Dict, List, Optional, Any, Callable, Union
|
from typing import Dict, List, Optional, Any, Callable, Union
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
import uuid
|
import uuid
|
||||||
import hashlib
|
import hashlib
|
||||||
from pydantic import BaseModel, Field, validator
|
from pydantic import BaseModel, Field, validator
|
||||||
@@ -77,7 +77,7 @@ class TaskMessage(BaseModel):
|
|||||||
|
|
||||||
@validator('deadline')
|
@validator('deadline')
|
||||||
def validate_deadline(cls, v):
|
def validate_deadline(cls, v):
|
||||||
if v and v < datetime.utcnow():
|
if v and v < datetime.now(datetime.UTC):
|
||||||
raise ValueError("Deadline cannot be in the past")
|
raise ValueError("Deadline cannot be in the past")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
@@ -156,7 +156,7 @@ class MessageRouter:
|
|||||||
|
|
||||||
async def route_message(self, message: AgentMessage) -> Optional[str]:
|
async def route_message(self, message: AgentMessage) -> Optional[str]:
|
||||||
"""Route message based on routing rules"""
|
"""Route message based on routing rules"""
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Check if message is expired
|
# Check if message is expired
|
||||||
@@ -192,7 +192,7 @@ class MessageRouter:
|
|||||||
self.routing_stats["messages_failed"] += 1
|
self.routing_stats["messages_failed"] += 1
|
||||||
return None
|
return None
|
||||||
finally:
|
finally:
|
||||||
routing_time = (datetime.utcnow() - start_time).total_seconds()
|
routing_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||||
self.routing_stats["routing_time_total"] += routing_time
|
self.routing_stats["routing_time_total"] += routing_time
|
||||||
|
|
||||||
async def _apply_routing_rule(self, rule: RoutingRule, message: AgentMessage) -> Optional[str]:
|
async def _apply_routing_rule(self, rule: RoutingRule, message: AgentMessage) -> Optional[str]:
|
||||||
@@ -244,7 +244,7 @@ class MessageRouter:
|
|||||||
|
|
||||||
def _is_message_expired(self, message: AgentMessage) -> bool:
|
def _is_message_expired(self, message: AgentMessage) -> bool:
|
||||||
"""Check if message is expired"""
|
"""Check if message is expired"""
|
||||||
age = (datetime.utcnow() - message.timestamp).total_seconds()
|
age = (datetime.now(datetime.UTC) - message.timestamp).total_seconds()
|
||||||
return age > message.ttl
|
return age > message.ttl
|
||||||
|
|
||||||
async def get_routing_stats(self) -> Dict[str, Any]:
|
async def get_routing_stats(self) -> Dict[str, Any]:
|
||||||
@@ -269,12 +269,12 @@ class LoadBalancer:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.agent_loads: Dict[str, float] = {}
|
self.agent_loads: Dict[str, float] = {}
|
||||||
self.agent_weights: Dict[str, float] = {}
|
self.agent_weights: Dict[str, float] = {}
|
||||||
self.last_updated = datetime.utcnow()
|
self.last_updated = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
def update_agent_load(self, agent_id: str, load: float):
|
def update_agent_load(self, agent_id: str, load: float):
|
||||||
"""Update agent load information"""
|
"""Update agent load information"""
|
||||||
self.agent_loads[agent_id] = load
|
self.agent_loads[agent_id] = load
|
||||||
self.last_updated = datetime.utcnow()
|
self.last_updated = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
def set_agent_weight(self, agent_id: str, weight: float):
|
def set_agent_weight(self, agent_id: str, weight: float):
|
||||||
"""Set agent weight for load balancing"""
|
"""Set agent weight for load balancing"""
|
||||||
@@ -421,7 +421,7 @@ class MessageProcessor:
|
|||||||
|
|
||||||
async def process_message(self, message: AgentMessage) -> bool:
|
async def process_message(self, message: AgentMessage) -> bool:
|
||||||
"""Process a message"""
|
"""Process a message"""
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Route message
|
# Route message
|
||||||
@@ -440,7 +440,7 @@ class MessageProcessor:
|
|||||||
|
|
||||||
# Update stats
|
# Update stats
|
||||||
self.processing_stats["messages_processed"] += 1
|
self.processing_stats["messages_processed"] += 1
|
||||||
processing_time = (datetime.utcnow() - start_time).total_seconds()
|
processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||||
self.processing_stats["processing_time_total"] += processing_time
|
self.processing_stats["processing_time_total"] += processing_time
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -52,7 +52,7 @@ async def register_agent(request: AgentRegistrationRequest):
|
|||||||
"status": "success",
|
"status": "success",
|
||||||
"message": f"Agent {request.agent_id} registered successfully",
|
"message": f"Agent {request.agent_id} registered successfully",
|
||||||
"agent_id": request.agent_id,
|
"agent_id": request.agent_id,
|
||||||
"registered_at": datetime.utcnow().isoformat()
|
"registered_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail="Failed to register agent")
|
raise HTTPException(status_code=500, detail="Failed to register agent")
|
||||||
@@ -78,7 +78,7 @@ async def discover_agents(query: Dict[str, Any]):
|
|||||||
"query": query,
|
"query": query,
|
||||||
"agents": [agent.to_dict() for agent in agents],
|
"agents": [agent.to_dict() for agent in agents],
|
||||||
"count": len(agents),
|
"count": len(agents),
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -101,7 +101,7 @@ async def get_agent(agent_id: str):
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"agent": agent.to_dict(),
|
"agent": agent.to_dict(),
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
@@ -132,7 +132,7 @@ async def update_agent_status(agent_id: str, request: AgentStatusUpdate):
|
|||||||
"message": f"Agent {agent_id} status updated",
|
"message": f"Agent {agent_id} status updated",
|
||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"new_status": request.status,
|
"new_status": request.status,
|
||||||
"updated_at": datetime.utcnow().isoformat()
|
"updated_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail="Failed to update agent status")
|
raise HTTPException(status_code=500, detail="Failed to update agent status")
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -156,7 +156,7 @@ async def record_sla_metric(
|
|||||||
"status": "success",
|
"status": "success",
|
||||||
"message": f"SLA metric recorded for {sla_id}",
|
"message": f"SLA metric recorded for {sla_id}",
|
||||||
"value": value,
|
"value": value,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
@@ -206,7 +206,7 @@ async def get_system_status(current_user: Dict[str, Any] = Depends(get_current_u
|
|||||||
"load_balancer": "running" if state.load_balancer else "stopped",
|
"load_balancer": "running" if state.load_balancer else "stopped",
|
||||||
"task_distributor": "running" if state.task_distributor else "stopped"
|
"task_distributor": "running" if state.task_distributor else "stopped"
|
||||||
},
|
},
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
return status
|
return status
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -105,7 +105,7 @@ async def get_advanced_features_status():
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"features": {
|
"features": {
|
||||||
"realtime_learning": {
|
"realtime_learning": {
|
||||||
"status": "active",
|
"status": "active",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -30,7 +30,7 @@ async def health_check():
|
|||||||
return {
|
return {
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "agent-coordinator",
|
"service": "agent-coordinator",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"version": "1.0.0"
|
"version": "1.0.0"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -63,7 +63,7 @@ async def send_message(request: MessageRequest):
|
|||||||
"message": "Message sent successfully",
|
"message": "Message sent successfully",
|
||||||
"message_id": message.id,
|
"message_id": message.id,
|
||||||
"receiver_id": request.receiver_id,
|
"receiver_id": request.receiver_id,
|
||||||
"sent_at": datetime.utcnow().isoformat()
|
"sent_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail="Failed to send message")
|
raise HTTPException(status_code=500, detail="Failed to send message")
|
||||||
@@ -85,7 +85,7 @@ async def get_load_balancer_stats():
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"stats": stats,
|
"stats": stats,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -105,7 +105,7 @@ async def get_registry_stats():
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"stats": stats,
|
"stats": stats,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -127,7 +127,7 @@ async def get_agents_by_service(service: str):
|
|||||||
"service": service,
|
"service": service,
|
||||||
"agents": [agent.to_dict() for agent in agents],
|
"agents": [agent.to_dict() for agent in agents],
|
||||||
"count": len(agents),
|
"count": len(agents),
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -149,7 +149,7 @@ async def get_agents_by_capability(capability: str):
|
|||||||
"capability": capability,
|
"capability": capability,
|
||||||
"agents": [agent.to_dict() for agent in agents],
|
"agents": [agent.to_dict() for agent in agents],
|
||||||
"count": len(agents),
|
"count": len(agents),
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -175,7 +175,7 @@ async def set_load_balancing_strategy(strategy: str = Query(..., description="Lo
|
|||||||
"status": "success",
|
"status": "success",
|
||||||
"message": f"Load balancing strategy set to {strategy}",
|
"message": f"Load balancing strategy set to {strategy}",
|
||||||
"strategy": strategy,
|
"strategy": strategy,
|
||||||
"updated_at": datetime.utcnow().isoformat()
|
"updated_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -84,7 +84,7 @@ async def get_metrics_summary():
|
|||||||
"status": "success",
|
"status": "success",
|
||||||
"performance": summary,
|
"performance": summary,
|
||||||
"system": system_metrics,
|
"system": system_metrics,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -116,7 +116,7 @@ async def get_health_metrics():
|
|||||||
"count": psutil.cpu_count()
|
"count": psutil.cpu_count()
|
||||||
},
|
},
|
||||||
"uptime": performance_monitor.get_performance_summary()["uptime_seconds"],
|
"uptime": performance_monitor.get_performance_summary()["uptime_seconds"],
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
import uuid
|
import uuid
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ async def submit_task(request: TaskSubmission, background_tasks: BackgroundTasks
|
|||||||
"message": "Task submitted successfully",
|
"message": "Task submitted successfully",
|
||||||
"task_id": request.task_data.get("task_id", str(uuid.uuid4())),
|
"task_id": request.task_data.get("task_id", str(uuid.uuid4())),
|
||||||
"priority": request.priority,
|
"priority": request.priority,
|
||||||
"submitted_at": datetime.utcnow().isoformat()
|
"submitted_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
@@ -72,7 +72,7 @@ async def get_task_status():
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"stats": stats,
|
"stats": stats,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
from typing import Dict, List, Optional, Set, Callable, Any
|
from typing import Dict, List, Optional, Set, Callable, Any
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
import uuid
|
import uuid
|
||||||
import hashlib
|
import hashlib
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
@@ -178,7 +178,7 @@ class AgentRegistry:
|
|||||||
|
|
||||||
agent_info = self.agents[agent_id]
|
agent_info = self.agents[agent_id]
|
||||||
agent_info.status = status
|
agent_info.status = status
|
||||||
agent_info.last_heartbeat = datetime.utcnow()
|
agent_info.last_heartbeat = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
if load_metrics:
|
if load_metrics:
|
||||||
agent_info.load_metrics.update(load_metrics)
|
agent_info.load_metrics.update(load_metrics)
|
||||||
@@ -206,7 +206,7 @@ class AgentRegistry:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
agent_info = self.agents[agent_id]
|
agent_info = self.agents[agent_id]
|
||||||
agent_info.last_heartbeat = datetime.utcnow()
|
agent_info.last_heartbeat = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Update health score
|
# Update health score
|
||||||
agent_info.health_score = self._calculate_health_score(agent_info)
|
agent_info.health_score = self._calculate_health_score(agent_info)
|
||||||
@@ -307,7 +307,7 @@ class AgentRegistry:
|
|||||||
"type_counts": type_counts,
|
"type_counts": type_counts,
|
||||||
"service_count": len(self.service_index),
|
"service_count": len(self.service_index),
|
||||||
"capability_count": len(self.capability_index),
|
"capability_count": len(self.capability_index),
|
||||||
"last_cleanup": datetime.utcnow().isoformat()
|
"last_cleanup": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
def _update_indexes(self, agent_info: AgentInfo):
|
def _update_indexes(self, agent_info: AgentInfo):
|
||||||
@@ -372,7 +372,7 @@ class AgentRegistry:
|
|||||||
base_score -= 0.1
|
base_score -= 0.1
|
||||||
|
|
||||||
# Penalty for old heartbeat
|
# Penalty for old heartbeat
|
||||||
heartbeat_age = (datetime.utcnow() - agent_info.last_heartbeat).total_seconds()
|
heartbeat_age = (datetime.now(datetime.UTC) - agent_info.last_heartbeat).total_seconds()
|
||||||
if heartbeat_age > self.max_heartbeat_age:
|
if heartbeat_age > self.max_heartbeat_age:
|
||||||
base_score -= 0.5
|
base_score -= 0.5
|
||||||
elif heartbeat_age > self.max_heartbeat_age / 2:
|
elif heartbeat_age > self.max_heartbeat_age / 2:
|
||||||
@@ -428,7 +428,7 @@ class AgentRegistry:
|
|||||||
|
|
||||||
event = {
|
event = {
|
||||||
"event_type": event_type,
|
"event_type": event_type,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"agent_info": agent_info.to_dict()
|
"agent_info": agent_info.to_dict()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,7 +441,7 @@ class AgentRegistry:
|
|||||||
await asyncio.sleep(self.heartbeat_interval)
|
await asyncio.sleep(self.heartbeat_interval)
|
||||||
|
|
||||||
# Check for agents with old heartbeats
|
# Check for agents with old heartbeats
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
for agent_id, agent_info in list(self.agents.items()):
|
for agent_id, agent_info in list(self.agents.items()):
|
||||||
heartbeat_age = (now - agent_info.last_heartbeat).total_seconds()
|
heartbeat_age = (now - agent_info.last_heartbeat).total_seconds()
|
||||||
|
|
||||||
@@ -462,7 +462,7 @@ class AgentRegistry:
|
|||||||
await asyncio.sleep(self.cleanup_interval)
|
await asyncio.sleep(self.cleanup_interval)
|
||||||
|
|
||||||
# Remove agents that have been inactive too long
|
# Remove agents that have been inactive too long
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
max_inactive_age = timedelta(hours=1) # 1 hour
|
max_inactive_age = timedelta(hours=1) # 1 hour
|
||||||
|
|
||||||
for agent_id, agent_info in list(self.agents.items()):
|
for agent_id, agent_info in list(self.agents.items()):
|
||||||
@@ -502,8 +502,8 @@ class AgentDiscoveryService:
|
|||||||
services=discovery_data.services,
|
services=discovery_data.services,
|
||||||
endpoints=discovery_data.endpoints,
|
endpoints=discovery_data.endpoints,
|
||||||
metadata=discovery_data.metadata,
|
metadata=discovery_data.metadata,
|
||||||
last_heartbeat=datetime.utcnow(),
|
last_heartbeat=datetime.now(datetime.UTC),
|
||||||
registration_time=datetime.utcnow()
|
registration_time=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
|
|
||||||
# Register or update agent
|
# Register or update agent
|
||||||
@@ -597,8 +597,8 @@ def create_agent_info(agent_id: str, agent_type: str, capabilities: List[str], s
|
|||||||
services=services,
|
services=services,
|
||||||
endpoints=endpoints,
|
endpoints=endpoints,
|
||||||
metadata={},
|
metadata={},
|
||||||
last_heartbeat=datetime.utcnow(),
|
last_heartbeat=datetime.now(datetime.UTC),
|
||||||
registration_time=datetime.utcnow()
|
registration_time=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
|
|
||||||
# Example usage
|
# Example usage
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
from typing import Dict, List, Optional, Tuple, Any, Callable
|
from typing import Dict, List, Optional, Tuple, Any, Callable
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
import statistics
|
import statistics
|
||||||
import uuid
|
import uuid
|
||||||
@@ -132,7 +132,7 @@ class LoadBalancer:
|
|||||||
def update_agent_metrics(self, agent_id: str, metrics: LoadMetrics):
|
def update_agent_metrics(self, agent_id: str, metrics: LoadMetrics):
|
||||||
"""Update agent load metrics"""
|
"""Update agent load metrics"""
|
||||||
self.agent_metrics[agent_id] = metrics
|
self.agent_metrics[agent_id] = metrics
|
||||||
self.agent_metrics[agent_id].last_updated = datetime.utcnow()
|
self.agent_metrics[agent_id].last_updated = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Update performance score based on metrics
|
# Update performance score based on metrics
|
||||||
self._update_performance_score(agent_id, metrics)
|
self._update_performance_score(agent_id, metrics)
|
||||||
@@ -196,7 +196,7 @@ class LoadBalancer:
|
|||||||
assignment = TaskAssignment(
|
assignment = TaskAssignment(
|
||||||
task_id=task_id,
|
task_id=task_id,
|
||||||
agent_id=selected_agent,
|
agent_id=selected_agent,
|
||||||
assigned_at=datetime.utcnow()
|
assigned_at=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
|
|
||||||
# Record assignment
|
# Record assignment
|
||||||
@@ -226,7 +226,7 @@ class LoadBalancer:
|
|||||||
return
|
return
|
||||||
|
|
||||||
assignment = self.task_assignments[task_id]
|
assignment = self.task_assignments[task_id]
|
||||||
assignment.completed_at = datetime.utcnow()
|
assignment.completed_at = datetime.now(datetime.UTC)
|
||||||
assignment.status = "completed"
|
assignment.status = "completed"
|
||||||
assignment.success = success
|
assignment.success = success
|
||||||
assignment.response_time = response_time
|
assignment.response_time = response_time
|
||||||
@@ -580,7 +580,7 @@ class TaskDistributor:
|
|||||||
"task_data": task_data,
|
"task_data": task_data,
|
||||||
"priority": priority,
|
"priority": priority,
|
||||||
"requirements": requirements,
|
"requirements": requirements,
|
||||||
"submitted_at": datetime.utcnow()
|
"submitted_at": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
await self.priority_queues[priority].put(task_info)
|
await self.priority_queues[priority].put(task_info)
|
||||||
@@ -612,7 +612,7 @@ class TaskDistributor:
|
|||||||
|
|
||||||
async def _distribute_task(self, task_info: Dict[str, Any]):
|
async def _distribute_task(self, task_info: Dict[str, Any]):
|
||||||
"""Distribute a single task"""
|
"""Distribute a single task"""
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Assign task
|
# Assign task
|
||||||
@@ -648,7 +648,7 @@ class TaskDistributor:
|
|||||||
|
|
||||||
finally:
|
finally:
|
||||||
# Update distribution time
|
# Update distribution time
|
||||||
distribution_time = (datetime.utcnow() - start_time).total_seconds()
|
distribution_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||||
total_distributed = self.distribution_stats["tasks_distributed"]
|
total_distributed = self.distribution_stats["tasks_distributed"]
|
||||||
self.distribution_stats["avg_distribution_time"] = (
|
self.distribution_stats["avg_distribution_time"] = (
|
||||||
(self.distribution_stats["avg_distribution_time"] * (total_distributed - 1) + distribution_time) / total_distributed
|
(self.distribution_stats["avg_distribution_time"] * (total_distributed - 1) + distribution_time) / total_distributed
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Tests for Agent Communication Protocols
|
|||||||
import sys
|
import sys
|
||||||
import pytest
|
import pytest
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from unittest.mock import Mock, AsyncMock
|
from unittest.mock import Mock, AsyncMock
|
||||||
|
|
||||||
from src.app.protocols.communication import (
|
from src.app.protocols.communication import (
|
||||||
@@ -63,12 +63,12 @@ class TestAgentMessage:
|
|||||||
sender_id="agent-001",
|
sender_id="agent-001",
|
||||||
receiver_id="agent-002",
|
receiver_id="agent-002",
|
||||||
message_type=MessageType.DIRECT,
|
message_type=MessageType.DIRECT,
|
||||||
timestamp=datetime.utcnow() - timedelta(seconds=400),
|
timestamp=datetime.now(datetime.UTC) - timedelta(seconds=400),
|
||||||
ttl=300
|
ttl=300
|
||||||
)
|
)
|
||||||
|
|
||||||
# Message should be expired
|
# Message should be expired
|
||||||
age = (datetime.utcnow() - old_message.timestamp).total_seconds()
|
age = (datetime.now(datetime.UTC) - old_message.timestamp).total_seconds()
|
||||||
assert age > old_message.ttl
|
assert age > old_message.ttl
|
||||||
|
|
||||||
class TestHierarchicalProtocol:
|
class TestHierarchicalProtocol:
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import asyncio
|
|||||||
import aiohttp
|
import aiohttp
|
||||||
import json
|
import json
|
||||||
from typing import Dict, Any, List, Optional
|
from typing import Dict, Any, List, Optional
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
class AITBCServiceIntegration:
|
class AITBCServiceIntegration:
|
||||||
"""Integration layer for AITBC services"""
|
"""Integration layer for AITBC services"""
|
||||||
@@ -110,7 +110,7 @@ class AgentServiceBridge:
|
|||||||
self.active_agents[agent_id] = {
|
self.active_agents[agent_id] = {
|
||||||
"config": agent_config,
|
"config": agent_config,
|
||||||
"registration": registration_result,
|
"registration": registration_result,
|
||||||
"started_at": datetime.utcnow()
|
"started_at": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
@@ -182,7 +182,7 @@ class AgentServiceBridge:
|
|||||||
"volatility": "medium",
|
"volatility": "medium",
|
||||||
"recommendation": "hold"
|
"recommendation": "hold"
|
||||||
},
|
},
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
return {"status": "success", "result": analysis_result}
|
return {"status": "success", "result": analysis_result}
|
||||||
@@ -221,7 +221,7 @@ class AgentServiceBridge:
|
|||||||
"check_type": task_data.get("check_type", "basic"),
|
"check_type": task_data.get("check_type", "basic"),
|
||||||
"status": "passed",
|
"status": "passed",
|
||||||
"checks_performed": ["kyc", "aml", "sanctions"],
|
"checks_performed": ["kyc", "aml", "sanctions"],
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
return {"status": "success", "result": compliance_result}
|
return {"status": "success", "result": compliance_result}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ class ComplianceAgent:
|
|||||||
"alert_type": "compliance_failure",
|
"alert_type": "compliance_failure",
|
||||||
"severity": "high",
|
"severity": "high",
|
||||||
"details": result,
|
"details": result,
|
||||||
"timestamp": datetime.utcnow().isoformat()
|
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
# In a real implementation, this would send to alert system
|
# In a real implementation, this would send to alert system
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from pydantic import BaseModel
|
|||||||
from typing import List, Optional, Dict, Any
|
from typing import List, Optional, Dict, Any
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
@@ -125,7 +125,7 @@ async def list_tasks(status: Optional[str] = None):
|
|||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
async def health_check():
|
async def health_check():
|
||||||
"""Health check endpoint"""
|
"""Health check endpoint"""
|
||||||
return {"status": "ok", "timestamp": datetime.utcnow()}
|
return {"status": "ok", "timestamp": datetime.now(datetime.UTC)}
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Handles message creation, routing, and delivery between agents
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Dict, Any, Optional, List
|
from typing import Dict, Any, Optional, List
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ class MessageProtocol:
|
|||||||
"receiver_id": receiver_id,
|
"receiver_id": receiver_id,
|
||||||
"message_type": message_type.value,
|
"message_type": message_type.value,
|
||||||
"content": content,
|
"content": content,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"status": "pending"
|
"status": "pending"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ class MessageProtocol:
|
|||||||
"""Send a message to the receiver"""
|
"""Send a message to the receiver"""
|
||||||
try:
|
try:
|
||||||
message["status"] = "sent"
|
message["status"] = "sent"
|
||||||
message["sent_timestamp"] = datetime.utcnow().isoformat()
|
message["sent_timestamp"] = datetime.now(datetime.UTC).isoformat()
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
message["status"] = "failed"
|
message["status"] = "failed"
|
||||||
@@ -65,7 +65,7 @@ class MessageProtocol:
|
|||||||
for message in self.messages:
|
for message in self.messages:
|
||||||
if message["message_id"] == message_id:
|
if message["message_id"] == message_id:
|
||||||
message["status"] = "received"
|
message["status"] = "received"
|
||||||
message["received_timestamp"] = datetime.utcnow().isoformat()
|
message["received_timestamp"] = datetime.now(datetime.UTC).isoformat()
|
||||||
return message
|
return message
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Handles task creation, assignment, and tracking
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Dict, Any, Optional, List
|
from typing import Dict, Any, Optional, List
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
@@ -42,8 +42,8 @@ class Task:
|
|||||||
self.priority = priority
|
self.priority = priority
|
||||||
self.created_by = created_by or assigned_to
|
self.created_by = created_by or assigned_to
|
||||||
self.status = TaskStatus.PENDING
|
self.status = TaskStatus.PENDING
|
||||||
self.created_at = datetime.utcnow()
|
self.created_at = datetime.now(datetime.UTC)
|
||||||
self.updated_at = datetime.utcnow()
|
self.updated_at = datetime.now(datetime.UTC)
|
||||||
self.completed_at = None
|
self.completed_at = None
|
||||||
self.result = None
|
self.result = None
|
||||||
self.error = None
|
self.error = None
|
||||||
@@ -94,10 +94,10 @@ class TaskManager:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
task.status = status
|
task.status = status
|
||||||
task.updated_at = datetime.utcnow()
|
task.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
if status == TaskStatus.COMPLETED:
|
if status == TaskStatus.COMPLETED:
|
||||||
task.completed_at = datetime.utcnow()
|
task.completed_at = datetime.now(datetime.UTC)
|
||||||
task.result = result
|
task.result = result
|
||||||
elif status == TaskStatus.FAILED:
|
elif status == TaskStatus.FAILED:
|
||||||
task.error = error
|
task.error = error
|
||||||
@@ -120,7 +120,7 @@ class TaskManager:
|
|||||||
|
|
||||||
def get_overdue_tasks(self, hours: int = 24) -> List[Task]:
|
def get_overdue_tasks(self, hours: int = 24) -> List[Task]:
|
||||||
"""Get tasks that are overdue"""
|
"""Get tasks that are overdue"""
|
||||||
cutoff_time = datetime.utcnow() - timedelta(hours=hours)
|
cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours)
|
||||||
return [
|
return [
|
||||||
task for task in self.tasks.values()
|
task for task in self.tasks.values()
|
||||||
if task.status in [TaskStatus.PENDING, TaskStatus.IN_PROGRESS] and
|
if task.status in [TaskStatus.PENDING, TaskStatus.IN_PROGRESS] and
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from typing import List, Optional, Dict, Any
|
|||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
@@ -144,7 +144,7 @@ async def list_agents(
|
|||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
async def health_check():
|
async def health_check():
|
||||||
"""Health check endpoint"""
|
"""Health check endpoint"""
|
||||||
return {"status": "ok", "timestamp": datetime.utcnow()}
|
return {"status": "ok", "timestamp": datetime.now(datetime.UTC)}
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Basic AI-powered trading and analytics
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
@@ -58,7 +58,7 @@ class SimpleAITradingEngine:
|
|||||||
'overall_sentiment': np.random.choice(['bullish', 'bearish', 'neutral'])
|
'overall_sentiment': np.random.choice(['bullish', 'bearish', 'neutral'])
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
'timestamp': datetime.utcnow()
|
'timestamp': datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
async def make_trading_decision(self, symbol: str) -> Dict[str, Any]:
|
async def make_trading_decision(self, symbol: str) -> Dict[str, Any]:
|
||||||
@@ -90,7 +90,7 @@ class SimpleAITradingEngine:
|
|||||||
'quantity': quantity,
|
'quantity': quantity,
|
||||||
'price': analysis['current_price'],
|
'price': analysis['current_price'],
|
||||||
'reasoning': f"Signal strength: {signal_strength:.3f}",
|
'reasoning': f"Signal strength: {signal_strength:.3f}",
|
||||||
'timestamp': datetime.utcnow()
|
'timestamp': datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
# Global AI engine
|
# Global AI engine
|
||||||
@@ -104,7 +104,7 @@ async def analyze_market(request: AnalysisRequest):
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"analysis": analysis,
|
"analysis": analysis,
|
||||||
"timestamp": datetime.utcnow()
|
"timestamp": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "error", "message": "Analysis failed"}
|
return {"status": "error", "message": "Analysis failed"}
|
||||||
@@ -118,7 +118,7 @@ async def execute_ai_trade(request: TradingRequest):
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"decision": decision,
|
"decision": decision,
|
||||||
"timestamp": datetime.utcnow()
|
"timestamp": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "error", "message": "Analysis failed"}
|
return {"status": "error", "message": "Analysis failed"}
|
||||||
@@ -136,7 +136,7 @@ async def predict_market(symbol: str):
|
|||||||
"risk": analysis['ai_predictions']['risk_assessment'],
|
"risk": analysis['ai_predictions']['risk_assessment'],
|
||||||
"sentiment": analysis['ai_predictions']['sentiment_analysis']
|
"sentiment": analysis['ai_predictions']['sentiment_analysis']
|
||||||
},
|
},
|
||||||
"timestamp": datetime.utcnow()
|
"timestamp": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "error", "message": "Analysis failed"}
|
return {"status": "error", "message": "Analysis failed"}
|
||||||
@@ -152,7 +152,7 @@ async def get_ai_dashboard():
|
|||||||
'total_volume': np.random.uniform(100000, 1000000),
|
'total_volume': np.random.uniform(100000, 1000000),
|
||||||
'active_symbols': len(symbols),
|
'active_symbols': len(symbols),
|
||||||
'ai_models_active': 3,
|
'ai_models_active': 3,
|
||||||
'last_update': datetime.utcnow()
|
'last_update': datetime.now(datetime.UTC)
|
||||||
},
|
},
|
||||||
'symbol_analysis': {}
|
'symbol_analysis': {}
|
||||||
}
|
}
|
||||||
@@ -169,7 +169,7 @@ async def get_ai_dashboard():
|
|||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"dashboard": dashboard_data,
|
"dashboard": dashboard_data,
|
||||||
"timestamp": datetime.utcnow()
|
"timestamp": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "error", "message": "Analysis failed"}
|
return {"status": "error", "message": "Analysis failed"}
|
||||||
@@ -192,13 +192,13 @@ async def get_ai_status():
|
|||||||
"risk_assessment",
|
"risk_assessment",
|
||||||
"sentiment_analysis"
|
"sentiment_analysis"
|
||||||
],
|
],
|
||||||
"timestamp": datetime.utcnow()
|
"timestamp": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
async def health_check():
|
async def health_check():
|
||||||
"""Health check endpoint"""
|
"""Health check endpoint"""
|
||||||
return {"status": "ok", "timestamp": datetime.utcnow()}
|
return {"status": "ok", "timestamp": datetime.now(datetime.UTC)}
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import sys
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import Mock, patch, MagicMock
|
from unittest.mock import Mock, patch, MagicMock
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
|
|
||||||
# Mock numpy before importing
|
# Mock numpy before importing
|
||||||
@@ -68,7 +68,7 @@ async def test_make_trading_decision_extreme_confidence():
|
|||||||
'risk_assessment': {'risk_score': 0.0, 'volatility': 0.01},
|
'risk_assessment': {'risk_score': 0.0, 'volatility': 0.01},
|
||||||
'sentiment_analysis': {'sentiment_score': 1.0, 'overall_sentiment': 'bullish'}
|
'sentiment_analysis': {'sentiment_score': 1.0, 'overall_sentiment': 'bullish'}
|
||||||
},
|
},
|
||||||
'timestamp': datetime.utcnow()
|
'timestamp': datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
result = await engine.make_trading_decision('AITBC/BTC')
|
result = await engine.make_trading_decision('AITBC/BTC')
|
||||||
@@ -155,7 +155,7 @@ async def test_signal_strength_boundary_buy():
|
|||||||
'risk_assessment': {'risk_score': 0.0, 'volatility': 0.01},
|
'risk_assessment': {'risk_score': 0.0, 'volatility': 0.01},
|
||||||
'sentiment_analysis': {'sentiment_score': 0.5, 'overall_sentiment': 'bullish'}
|
'sentiment_analysis': {'sentiment_score': 0.5, 'overall_sentiment': 'bullish'}
|
||||||
},
|
},
|
||||||
'timestamp': datetime.utcnow()
|
'timestamp': datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
result = await engine.make_trading_decision('AITBC/BTC')
|
result = await engine.make_trading_decision('AITBC/BTC')
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import pytest
|
|||||||
import sys
|
import sys
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from unittest.mock import Mock, patch, MagicMock
|
from unittest.mock import Mock, patch, MagicMock
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ def test_get_ai_dashboard_endpoint():
|
|||||||
'risk_assessment': {'risk_score': 0.5, 'volatility': 0.03},
|
'risk_assessment': {'risk_score': 0.5, 'volatility': 0.03},
|
||||||
'sentiment_analysis': {'sentiment_score': 0.5, 'overall_sentiment': 'bullish'}
|
'sentiment_analysis': {'sentiment_score': 0.5, 'overall_sentiment': 'bullish'}
|
||||||
},
|
},
|
||||||
'timestamp': datetime.utcnow()
|
'timestamp': datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
mock_decision.return_value = {
|
mock_decision.return_value = {
|
||||||
@@ -108,7 +108,7 @@ def test_get_ai_dashboard_endpoint():
|
|||||||
'quantity': 500,
|
'quantity': 500,
|
||||||
'price': 0.005,
|
'price': 0.005,
|
||||||
'reasoning': 'Test reasoning',
|
'reasoning': 'Test reasoning',
|
||||||
'timestamp': datetime.utcnow()
|
'timestamp': datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
response = client.get("/api/ai/dashboard")
|
response = client.get("/api/ai/dashboard")
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ sys.path.insert(0, 'src')
|
|||||||
|
|
||||||
from aitbc_chain.database import session_scope, init_db
|
from aitbc_chain.database import session_scope, init_db
|
||||||
from aitbc_chain.models import Block
|
from aitbc_chain.models import Block
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
import hashlib
|
import hashlib
|
||||||
|
|
||||||
def compute_block_hash(height: int, parent_hash: str, timestamp: datetime) -> str:
|
def compute_block_hash(height: int, parent_hash: str, timestamp: datetime) -> str:
|
||||||
@@ -31,7 +31,7 @@ def create_genesis():
|
|||||||
return
|
return
|
||||||
|
|
||||||
# Create genesis block
|
# Create genesis block
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
genesis_hash = compute_block_hash(0, "0x00", timestamp)
|
genesis_hash = compute_block_hash(0, "0x00", timestamp)
|
||||||
genesis = Block(
|
genesis = Block(
|
||||||
height=0,
|
height=0,
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
from aitbc_chain.database import session_scope, init_db
|
from aitbc_chain.database import session_scope, init_db
|
||||||
from aitbc_chain.models import Account
|
from aitbc_chain.models import Account
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
def fix():
|
def fix():
|
||||||
init_db()
|
init_db()
|
||||||
with session_scope() as session:
|
with session_scope() as session:
|
||||||
acc = Account(chain_id="ait-mainnet", address="aitbc1genesis", balance=10000000, nonce=0, updated_at=datetime.utcnow(), account_type="regular", metadata="{}")
|
acc = Account(chain_id="ait-mainnet", address="aitbc1genesis", balance=10000000, nonce=0, updated_at=datetime.now(datetime.UTC), account_type="regular", metadata="{}")
|
||||||
session.merge(acc)
|
session.merge(acc)
|
||||||
session.commit()
|
session.commit()
|
||||||
print("Added aitbc1genesis to mainnet")
|
print("Added aitbc1genesis to mainnet")
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import base64
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Dict, List, Any, Optional
|
from typing import Dict, List, Any, Optional
|
||||||
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import ed25519
|
from cryptography.hazmat.primitives.asymmetric import ed25519
|
||||||
@@ -233,7 +233,7 @@ def initialize_genesis_database(genesis_block: Dict, allocations: List[Dict], db
|
|||||||
alloc["address"],
|
alloc["address"],
|
||||||
alloc["balance"],
|
alloc["balance"],
|
||||||
alloc["nonce"],
|
alloc["nonce"],
|
||||||
datetime.utcnow().isoformat()
|
datetime.now(datetime.UTC).isoformat()
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import asyncio
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Callable, ContextManager, Optional
|
from typing import Callable, ContextManager, Optional
|
||||||
|
|
||||||
@@ -168,7 +168,7 @@ class PoAProposer:
|
|||||||
head = self._fetch_chain_head()
|
head = self._fetch_chain_head()
|
||||||
if head is None:
|
if head is None:
|
||||||
return
|
return
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
elapsed = (now - head.timestamp).total_seconds()
|
elapsed = (now - head.timestamp).total_seconds()
|
||||||
sleep_for = max(self._config.interval_seconds - elapsed, 0.1)
|
sleep_for = max(self._config.interval_seconds - elapsed, 0.1)
|
||||||
if sleep_for <= 0:
|
if sleep_for <= 0:
|
||||||
@@ -201,7 +201,7 @@ class PoAProposer:
|
|||||||
elif block_generation_mode == "hybrid":
|
elif block_generation_mode == "hybrid":
|
||||||
# Hybrid mode: check heartbeat interval
|
# Hybrid mode: check heartbeat interval
|
||||||
if self._last_block_timestamp:
|
if self._last_block_timestamp:
|
||||||
time_since_last_block = (datetime.utcnow() - self._last_block_timestamp).total_seconds()
|
time_since_last_block = (datetime.now(datetime.UTC) - self._last_block_timestamp).total_seconds()
|
||||||
if mempool_size == 0 and time_since_last_block < max_empty_block_interval:
|
if mempool_size == 0 and time_since_last_block < max_empty_block_interval:
|
||||||
self._logger.debug(f"[PROPOSE] Skipping block proposal: mempool empty, heartbeat not yet due (chain={self._config.chain_id}, mode=hybrid, idle_time={time_since_last_block:.1f}s)")
|
self._logger.debug(f"[PROPOSE] Skipping block proposal: mempool empty, heartbeat not yet due (chain={self._config.chain_id}, mode=hybrid, idle_time={time_since_last_block:.1f}s)")
|
||||||
metrics_registry.increment("sync_empty_blocks_skipped_total")
|
metrics_registry.increment("sync_empty_blocks_skipped_total")
|
||||||
@@ -224,9 +224,9 @@ class PoAProposer:
|
|||||||
if head is not None:
|
if head is not None:
|
||||||
next_height = head.height + 1
|
next_height = head.height + 1
|
||||||
parent_hash = head.hash
|
parent_hash = head.hash
|
||||||
interval_seconds = (datetime.utcnow() - head.timestamp).total_seconds()
|
interval_seconds = (datetime.now(datetime.UTC) - head.timestamp).total_seconds()
|
||||||
|
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Pull transactions from mempool
|
# Pull transactions from mempool
|
||||||
max_txs = self._config.max_txs_per_block
|
max_txs = self._config.max_txs_per_block
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ of agent compromise.
|
|||||||
|
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Optional, Tuple
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
import json
|
import json
|
||||||
from eth_account import Account
|
from eth_account import Account
|
||||||
from eth_utils import to_checksum_address
|
from eth_utils import to_checksum_address
|
||||||
@@ -37,7 +37,7 @@ class AgentSecurityProfile:
|
|||||||
|
|
||||||
def __post_init__(self):
|
def __post_init__(self):
|
||||||
if self.created_at is None:
|
if self.created_at is None:
|
||||||
self.created_at = datetime.utcnow()
|
self.created_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
|
|
||||||
class AgentWalletSecurity:
|
class AgentWalletSecurity:
|
||||||
@@ -423,7 +423,7 @@ class AgentWalletSecurity:
|
|||||||
def _log_security_event(self, **kwargs):
|
def _log_security_event(self, **kwargs):
|
||||||
"""Log a security event"""
|
"""Log a security event"""
|
||||||
event = {
|
event = {
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
**kwargs
|
**kwargs
|
||||||
}
|
}
|
||||||
self.security_events.append(event)
|
self.security_events.append(event)
|
||||||
@@ -469,7 +469,7 @@ class AgentWalletSecurity:
|
|||||||
return {
|
return {
|
||||||
"status": "disabled",
|
"status": "disabled",
|
||||||
"agent_address": agent_address,
|
"agent_address": agent_address,
|
||||||
"disabled_at": datetime.utcnow().isoformat(),
|
"disabled_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"guardian": guardian_address
|
"guardian": guardian_address
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,7 +527,7 @@ def generate_security_report() -> Dict:
|
|||||||
recent_events = agent_wallet_security.get_security_events(limit=20)
|
recent_events = agent_wallet_security.get_security_events(limit=20)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"generated_at": datetime.utcnow().isoformat(),
|
"generated_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"summary": {
|
"summary": {
|
||||||
"total_protected_agents": total_agents,
|
"total_protected_agents": total_agents,
|
||||||
"active_agents": active_agents,
|
"active_agents": active_agents,
|
||||||
@@ -580,5 +580,5 @@ def detect_suspicious_activity(agent_address: str, hours: int = 24) -> Dict:
|
|||||||
"suspicious_activity": len(suspicious_patterns) > 0,
|
"suspicious_activity": len(suspicious_patterns) > 0,
|
||||||
"suspicious_patterns": suspicious_patterns,
|
"suspicious_patterns": suspicious_patterns,
|
||||||
"analysis_period_hours": hours,
|
"analysis_period_hours": hours,
|
||||||
"analyzed_at": datetime.utcnow().isoformat()
|
"analyzed_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ wallets from unlimited spending in case of compromise. It provides:
|
|||||||
|
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Optional, Tuple
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sqlite3
|
import sqlite3
|
||||||
@@ -248,7 +248,7 @@ class GuardianContract:
|
|||||||
def _get_spent_in_period(self, period: str, timestamp: datetime = None) -> int:
|
def _get_spent_in_period(self, period: str, timestamp: datetime = None) -> int:
|
||||||
"""Calculate total spent in given period"""
|
"""Calculate total spent in given period"""
|
||||||
if timestamp is None:
|
if timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
period_key = self._get_period_key(timestamp, period)
|
period_key = self._get_period_key(timestamp, period)
|
||||||
|
|
||||||
@@ -265,7 +265,7 @@ class GuardianContract:
|
|||||||
def _check_spending_limits(self, amount: int, timestamp: datetime = None) -> Tuple[bool, str]:
|
def _check_spending_limits(self, amount: int, timestamp: datetime = None) -> Tuple[bool, str]:
|
||||||
"""Check if amount exceeds spending limits"""
|
"""Check if amount exceeds spending limits"""
|
||||||
if timestamp is None:
|
if timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Check per-transaction limit
|
# Check per-transaction limit
|
||||||
if amount > self.config.limits.per_transaction:
|
if amount > self.config.limits.per_transaction:
|
||||||
@@ -350,7 +350,7 @@ class GuardianContract:
|
|||||||
"to": to_address,
|
"to": to_address,
|
||||||
"amount": amount,
|
"amount": amount,
|
||||||
"data": data,
|
"data": data,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"nonce": self.nonce,
|
"nonce": self.nonce,
|
||||||
"status": "pending"
|
"status": "pending"
|
||||||
}
|
}
|
||||||
@@ -360,7 +360,7 @@ class GuardianContract:
|
|||||||
|
|
||||||
# Check if time lock is required
|
# Check if time lock is required
|
||||||
if self._requires_time_lock(amount):
|
if self._requires_time_lock(amount):
|
||||||
unlock_time = datetime.utcnow() + timedelta(hours=self.config.time_lock.delay_hours)
|
unlock_time = datetime.now(datetime.UTC) + timedelta(hours=self.config.time_lock.delay_hours)
|
||||||
operation["unlock_time"] = unlock_time.isoformat()
|
operation["unlock_time"] = unlock_time.isoformat()
|
||||||
operation["status"] = "time_locked"
|
operation["status"] = "time_locked"
|
||||||
|
|
||||||
@@ -406,7 +406,7 @@ class GuardianContract:
|
|||||||
# Check if operation is time locked
|
# Check if operation is time locked
|
||||||
if operation["status"] == "time_locked":
|
if operation["status"] == "time_locked":
|
||||||
unlock_time = datetime.fromisoformat(operation["unlock_time"])
|
unlock_time = datetime.fromisoformat(operation["unlock_time"])
|
||||||
if datetime.utcnow() < unlock_time:
|
if datetime.now(datetime.UTC) < unlock_time:
|
||||||
return {
|
return {
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"reason": f"Operation locked until {unlock_time.isoformat()}"
|
"reason": f"Operation locked until {unlock_time.isoformat()}"
|
||||||
@@ -432,7 +432,7 @@ class GuardianContract:
|
|||||||
"amount": operation["amount"],
|
"amount": operation["amount"],
|
||||||
"data": operation.get("data", ""),
|
"data": operation.get("data", ""),
|
||||||
"timestamp": operation["timestamp"],
|
"timestamp": operation["timestamp"],
|
||||||
"executed_at": datetime.utcnow().isoformat(),
|
"executed_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"status": "completed",
|
"status": "completed",
|
||||||
"nonce": operation["nonce"]
|
"nonce": operation["nonce"]
|
||||||
}
|
}
|
||||||
@@ -479,7 +479,7 @@ class GuardianContract:
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "paused",
|
"status": "paused",
|
||||||
"paused_at": datetime.utcnow().isoformat(),
|
"paused_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"guardian": guardian_address,
|
"guardian": guardian_address,
|
||||||
"message": "Emergency pause activated - all operations halted"
|
"message": "Emergency pause activated - all operations halted"
|
||||||
}
|
}
|
||||||
@@ -513,7 +513,7 @@ class GuardianContract:
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "unpaused",
|
"status": "unpaused",
|
||||||
"unpaused_at": datetime.utcnow().isoformat(),
|
"unpaused_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"message": "Emergency pause lifted - operations resumed"
|
"message": "Emergency pause lifted - operations resumed"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -541,13 +541,13 @@ class GuardianContract:
|
|||||||
"status": "updated",
|
"status": "updated",
|
||||||
"old_limits": old_limits,
|
"old_limits": old_limits,
|
||||||
"new_limits": new_limits,
|
"new_limits": new_limits,
|
||||||
"updated_at": datetime.utcnow().isoformat(),
|
"updated_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"guardian": guardian_address
|
"guardian": guardian_address
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_spending_status(self) -> Dict:
|
def get_spending_status(self) -> Dict:
|
||||||
"""Get current spending status and limits"""
|
"""Get current spending status and limits"""
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"agent_address": self.agent_address,
|
"agent_address": self.agent_address,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Fixes the critical vulnerability where spending limits were lost on restart
|
|||||||
|
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Optional, Tuple
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from sqlalchemy import create_engine, Column, String, Integer, Float, DateTime, Index
|
from sqlalchemy import create_engine, Column, String, Integer, Float, DateTime, Index
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
from sqlalchemy.orm import sessionmaker, Session
|
from sqlalchemy.orm import sessionmaker, Session
|
||||||
@@ -112,7 +112,7 @@ class PersistentSpendingTracker:
|
|||||||
Total amount spent in period
|
Total amount spent in period
|
||||||
"""
|
"""
|
||||||
if timestamp is None:
|
if timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
period_key = self._get_period_key(timestamp, period)
|
period_key = self._get_period_key(timestamp, period)
|
||||||
agent_address = to_checksum_address(agent_address)
|
agent_address = to_checksum_address(agent_address)
|
||||||
@@ -140,7 +140,7 @@ class PersistentSpendingTracker:
|
|||||||
True if recorded successfully
|
True if recorded successfully
|
||||||
"""
|
"""
|
||||||
if timestamp is None:
|
if timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
agent_address = to_checksum_address(agent_address)
|
agent_address = to_checksum_address(agent_address)
|
||||||
|
|
||||||
@@ -184,7 +184,7 @@ class PersistentSpendingTracker:
|
|||||||
Spending check result
|
Spending check result
|
||||||
"""
|
"""
|
||||||
if timestamp is None:
|
if timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
agent_address = to_checksum_address(agent_address)
|
agent_address = to_checksum_address(agent_address)
|
||||||
|
|
||||||
@@ -312,7 +312,7 @@ class PersistentSpendingTracker:
|
|||||||
limits.per_week = new_limits.get("per_week", limits.per_week)
|
limits.per_week = new_limits.get("per_week", limits.per_week)
|
||||||
limits.time_lock_threshold = new_limits.get("time_lock_threshold", limits.time_lock_threshold)
|
limits.time_lock_threshold = new_limits.get("time_lock_threshold", limits.time_lock_threshold)
|
||||||
limits.time_lock_delay_hours = new_limits.get("time_lock_delay_hours", limits.time_lock_delay_hours)
|
limits.time_lock_delay_hours = new_limits.get("time_lock_delay_hours", limits.time_lock_delay_hours)
|
||||||
limits.updated_at = datetime.utcnow()
|
limits.updated_at = datetime.now(datetime.UTC)
|
||||||
limits.updated_by = guardian_address
|
limits.updated_by = guardian_address
|
||||||
else:
|
else:
|
||||||
limits = SpendingLimit(
|
limits = SpendingLimit(
|
||||||
@@ -323,7 +323,7 @@ class PersistentSpendingTracker:
|
|||||||
per_week=new_limits.get("per_week", 100000.0),
|
per_week=new_limits.get("per_week", 100000.0),
|
||||||
time_lock_threshold=new_limits.get("time_lock_threshold", 5000.0),
|
time_lock_threshold=new_limits.get("time_lock_threshold", 5000.0),
|
||||||
time_lock_delay_hours=new_limits.get("time_lock_delay_hours", 24),
|
time_lock_delay_hours=new_limits.get("time_lock_delay_hours", 24),
|
||||||
updated_at=datetime.utcnow(),
|
updated_at=datetime.now(datetime.UTC),
|
||||||
updated_by=guardian_address
|
updated_by=guardian_address
|
||||||
)
|
)
|
||||||
session.add(limits)
|
session.add(limits)
|
||||||
@@ -361,7 +361,7 @@ class PersistentSpendingTracker:
|
|||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
existing.is_active = True
|
existing.is_active = True
|
||||||
existing.added_at = datetime.utcnow()
|
existing.added_at = datetime.now(datetime.UTC)
|
||||||
existing.added_by = added_by
|
existing.added_by = added_by
|
||||||
else:
|
else:
|
||||||
auth = GuardianAuthorization(
|
auth = GuardianAuthorization(
|
||||||
@@ -369,7 +369,7 @@ class PersistentSpendingTracker:
|
|||||||
agent_address=agent_address,
|
agent_address=agent_address,
|
||||||
guardian_address=guardian_address,
|
guardian_address=guardian_address,
|
||||||
is_active=True,
|
is_active=True,
|
||||||
added_at=datetime.utcnow(),
|
added_at=datetime.now(datetime.UTC),
|
||||||
added_by=added_by
|
added_by=added_by
|
||||||
)
|
)
|
||||||
session.add(auth)
|
session.add(auth)
|
||||||
@@ -415,7 +415,7 @@ class PersistentSpendingTracker:
|
|||||||
Spending summary
|
Spending summary
|
||||||
"""
|
"""
|
||||||
agent_address = to_checksum_address(agent_address)
|
agent_address = to_checksum_address(agent_address)
|
||||||
now = datetime.utcnow()
|
now = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Get current spending
|
# Get current spending
|
||||||
current_spent = {
|
current_spent = {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""Cross-chain synchronization for testing multi-chain scenarios."""
|
"""Cross-chain synchronization for testing multi-chain scenarios."""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ class CrossChainSync:
|
|||||||
self.sync_status[chain] = {
|
self.sync_status[chain] = {
|
||||||
"synced": True,
|
"synced": True,
|
||||||
"height": 0,
|
"height": 0,
|
||||||
"last_sync": datetime.utcnow().isoformat(),
|
"last_sync": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -36,5 +36,5 @@ class MultiChainConsensus:
|
|||||||
"consensus_reached": True,
|
"consensus_reached": True,
|
||||||
"height": 0,
|
"height": 0,
|
||||||
"validators": 1,
|
"validators": 1,
|
||||||
"last_consensus": datetime.utcnow().isoformat(),
|
"last_consensus": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import logging
|
|||||||
import sys
|
import sys
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging.handlers import RotatingFileHandler
|
||||||
import json
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
class JsonFormatter(logging.Formatter):
|
class JsonFormatter(logging.Formatter):
|
||||||
def format(self, record):
|
def format(self, record):
|
||||||
log_record = {
|
log_record = {
|
||||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||||
"level": record.levelname,
|
"level": record.levelname,
|
||||||
"logger": record.name,
|
"logger": record.name,
|
||||||
"message": record.getMessage()
|
"message": record.getMessage()
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
from typing import Any, Dict, Optional, List
|
from typing import Any, Dict, Optional, List
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, status
|
from fastapi import APIRouter, HTTPException, status
|
||||||
from pydantic import BaseModel, Field, model_validator
|
from pydantic import BaseModel, Field, model_validator
|
||||||
@@ -445,12 +445,12 @@ async def submit_marketplace_transaction(tx_data: Dict[str, Any]) -> Dict[str, A
|
|||||||
sender=sender_addr,
|
sender=sender_addr,
|
||||||
recipient=recipient_addr,
|
recipient=recipient_addr,
|
||||||
payload=tx_data.get("payload", {}),
|
payload=tx_data.get("payload", {}),
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
nonce=tx_nonce,
|
nonce=tx_nonce,
|
||||||
value=amount,
|
value=amount,
|
||||||
fee=fee,
|
fee=fee,
|
||||||
status="pending",
|
status="pending",
|
||||||
timestamp=datetime.utcnow().isoformat()
|
timestamp=datetime.now(datetime.UTC).isoformat()
|
||||||
)
|
)
|
||||||
session.add(transaction)
|
session.add(transaction)
|
||||||
|
|
||||||
@@ -700,9 +700,9 @@ async def import_block(block_data: dict) -> Dict[str, Any]:
|
|||||||
try:
|
try:
|
||||||
timestamp = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
|
timestamp = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
elif timestamp is None:
|
elif timestamp is None:
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
with session_scope(chain_id) as session:
|
with session_scope(chain_id) as session:
|
||||||
# Check for hash conflicts across chains
|
# Check for hash conflicts across chains
|
||||||
@@ -948,7 +948,7 @@ async def import_chain(import_data: dict) -> Dict[str, Any]:
|
|||||||
_logger.info(f"Importing {len(unique_blocks)} unique blocks (filtered from {len(blocks)} total)")
|
_logger.info(f"Importing {len(unique_blocks)} unique blocks (filtered from {len(blocks)} total)")
|
||||||
|
|
||||||
for block_data in unique_blocks:
|
for block_data in unique_blocks:
|
||||||
block_timestamp = _parse_datetime_value(block_data.get("timestamp"), "block timestamp") or datetime.utcnow()
|
block_timestamp = _parse_datetime_value(block_data.get("timestamp"), "block timestamp") or datetime.now(datetime.UTC)
|
||||||
block = Block(
|
block = Block(
|
||||||
chain_id=chain_id,
|
chain_id=chain_id,
|
||||||
height=block_data["height"],
|
height=block_data["height"],
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from typing import Dict, List, Optional, Tuple
|
|||||||
|
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
from sqlalchemy import select, text
|
from sqlalchemy import select, text
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
from ..models import Account, Transaction, Receipt
|
from ..models import Account, Transaction, Receipt
|
||||||
from ..logger import get_logger
|
from ..logger import get_logger
|
||||||
@@ -242,7 +242,7 @@ class StateTransition:
|
|||||||
|
|
||||||
# Update receipt status
|
# Update receipt status
|
||||||
receipt.status = "claimed"
|
receipt.status = "claimed"
|
||||||
receipt.claimed_at = datetime.utcnow()
|
receipt.claimed_at = datetime.now(datetime.UTC)
|
||||||
receipt.claimed_by = sender_addr
|
receipt.claimed_by = sender_addr
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import hashlib
|
|||||||
import hmac
|
import hmac
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -397,9 +397,9 @@ class ChainSync:
|
|||||||
"""Append a block to the chain tip."""
|
"""Append a block to the chain tip."""
|
||||||
timestamp_str = block_data.get("timestamp", "")
|
timestamp_str = block_data.get("timestamp", "")
|
||||||
try:
|
try:
|
||||||
timestamp = datetime.fromisoformat(timestamp_str) if timestamp_str else datetime.utcnow()
|
timestamp = datetime.fromisoformat(timestamp_str) if timestamp_str else datetime.now(datetime.UTC)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
tx_count = block_data.get("tx_count", 0)
|
tx_count = block_data.get("tx_count", 0)
|
||||||
if transactions:
|
if transactions:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
import sys
|
import sys
|
||||||
import asyncio
|
import asyncio
|
||||||
import pytest
|
import pytest
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from unittest.mock import AsyncMock, Mock, patch
|
from unittest.mock import AsyncMock, Mock, patch
|
||||||
from typing import Generator
|
from typing import Generator
|
||||||
|
|
||||||
@@ -192,7 +192,7 @@ class TestPoAProposer:
|
|||||||
hash="0xparent",
|
hash="0xparent",
|
||||||
parent_hash="0x00",
|
parent_hash="0x00",
|
||||||
proposer="previous-proposer",
|
proposer="previous-proposer",
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
tx_count=0,
|
tx_count=0,
|
||||||
)
|
)
|
||||||
test_db.add(parent)
|
test_db.add(parent)
|
||||||
@@ -231,16 +231,16 @@ class TestPoAProposer:
|
|||||||
hash="0xhead",
|
hash="0xhead",
|
||||||
parent_hash="0x00",
|
parent_hash="0x00",
|
||||||
proposer="test-proposer",
|
proposer="test-proposer",
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
tx_count=0,
|
tx_count=0,
|
||||||
)
|
)
|
||||||
test_db.add(head)
|
test_db.add(head)
|
||||||
test_db.commit()
|
test_db.commit()
|
||||||
|
|
||||||
# Should wait for the configured interval
|
# Should wait for the configured interval
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
await proposer._wait_until_next_slot()
|
await proposer._wait_until_next_slot()
|
||||||
elapsed = (datetime.utcnow() - start_time).total_seconds()
|
elapsed = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||||
|
|
||||||
# Should wait at least some time (but less than full interval since block is recent)
|
# Should wait at least some time (but less than full interval since block is recent)
|
||||||
assert elapsed >= 0.1
|
assert elapsed >= 0.1
|
||||||
@@ -255,7 +255,7 @@ class TestPoAProposer:
|
|||||||
hash="0xhead",
|
hash="0xhead",
|
||||||
parent_hash="0x00",
|
parent_hash="0x00",
|
||||||
proposer="test-proposer",
|
proposer="test-proposer",
|
||||||
timestamp=datetime.utcnow() - timedelta(seconds=10),
|
timestamp=datetime.now(datetime.UTC) - timedelta(seconds=10),
|
||||||
tx_count=0,
|
tx_count=0,
|
||||||
)
|
)
|
||||||
test_db.add(head)
|
test_db.add(head)
|
||||||
@@ -263,9 +263,9 @@ class TestPoAProposer:
|
|||||||
|
|
||||||
# Set stop event and wait
|
# Set stop event and wait
|
||||||
proposer._stop_event.set()
|
proposer._stop_event.set()
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
await proposer._wait_until_next_slot()
|
await proposer._wait_until_next_slot()
|
||||||
elapsed = (datetime.utcnow() - start_time).total_seconds()
|
elapsed = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||||
|
|
||||||
# Should return immediately due to stop event
|
# Should return immediately due to stop event
|
||||||
assert elapsed < 0.1
|
assert elapsed < 0.1
|
||||||
@@ -290,7 +290,7 @@ class TestPoAProposer:
|
|||||||
"""Test block hash computation."""
|
"""Test block hash computation."""
|
||||||
height = 1
|
height = 1
|
||||||
parent_hash = "0xparent"
|
parent_hash = "0xparent"
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
processed_txs = []
|
processed_txs = []
|
||||||
|
|
||||||
block_hash = proposer._compute_block_hash(height, parent_hash, timestamp, processed_txs)
|
block_hash = proposer._compute_block_hash(height, parent_hash, timestamp, processed_txs)
|
||||||
@@ -303,7 +303,7 @@ class TestPoAProposer:
|
|||||||
"""Test block hash computation with transactions."""
|
"""Test block hash computation with transactions."""
|
||||||
height = 1
|
height = 1
|
||||||
parent_hash = "0xparent"
|
parent_hash = "0xparent"
|
||||||
timestamp = datetime.utcnow()
|
timestamp = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
mock_tx = Mock()
|
mock_tx = Mock()
|
||||||
mock_tx.tx_hash = "0xtx"
|
mock_tx.tx_hash = "0xtx"
|
||||||
@@ -324,7 +324,7 @@ class TestPoAProposer:
|
|||||||
hash="0xexisting",
|
hash="0xexisting",
|
||||||
parent_hash="0x00",
|
parent_hash="0x00",
|
||||||
proposer="test-proposer",
|
proposer="test-proposer",
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
tx_count=0,
|
tx_count=0,
|
||||||
)
|
)
|
||||||
test_db.add(block)
|
test_db.add(block)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import sys
|
|||||||
import pytest
|
import pytest
|
||||||
import tempfile
|
import tempfile
|
||||||
import shutil
|
import shutil
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch, Mock
|
from unittest.mock import patch, Mock
|
||||||
from typing import Generator
|
from typing import Generator
|
||||||
@@ -113,7 +113,7 @@ class TestGuardianContract:
|
|||||||
def test_spending_limit_check_hourly(self, guardian_contract: GuardianContract) -> None:
|
def test_spending_limit_check_hourly(self, guardian_contract: GuardianContract) -> None:
|
||||||
"""Test hourly spending limit."""
|
"""Test hourly spending limit."""
|
||||||
# Add some spending history
|
# Add some spending history
|
||||||
base_time = datetime.utcnow()
|
base_time = datetime.now(datetime.UTC)
|
||||||
guardian_contract.spending_history = [
|
guardian_contract.spending_history = [
|
||||||
{
|
{
|
||||||
"operation_id": "op1",
|
"operation_id": "op1",
|
||||||
@@ -139,7 +139,7 @@ class TestGuardianContract:
|
|||||||
def test_spending_limit_check_daily(self, guardian_contract: GuardianContract) -> None:
|
def test_spending_limit_check_daily(self, guardian_contract: GuardianContract) -> None:
|
||||||
"""Test daily spending limit."""
|
"""Test daily spending limit."""
|
||||||
# Add spending history across the day
|
# Add spending history across the day
|
||||||
base_time = datetime.utcnow()
|
base_time = datetime.now(datetime.UTC)
|
||||||
guardian_contract.spending_history = [
|
guardian_contract.spending_history = [
|
||||||
{
|
{
|
||||||
"operation_id": "op1",
|
"operation_id": "op1",
|
||||||
@@ -165,7 +165,7 @@ class TestGuardianContract:
|
|||||||
def test_spending_limit_check_weekly(self, guardian_contract: GuardianContract) -> None:
|
def test_spending_limit_check_weekly(self, guardian_contract: GuardianContract) -> None:
|
||||||
"""Test weekly spending limit."""
|
"""Test weekly spending limit."""
|
||||||
# Add spending history across the week
|
# Add spending history across the week
|
||||||
base_time = datetime.utcnow()
|
base_time = datetime.now(datetime.UTC)
|
||||||
guardian_contract.spending_history = [
|
guardian_contract.spending_history = [
|
||||||
{
|
{
|
||||||
"operation_id": "op1",
|
"operation_id": "op1",
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import hashlib
|
|||||||
import time
|
import time
|
||||||
import sys
|
import sys
|
||||||
import pytest
|
import pytest
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
from sqlmodel import Session, SQLModel, create_engine, select
|
from sqlmodel import Session, SQLModel, create_engine, select
|
||||||
@@ -68,7 +68,7 @@ class TestProposerSignatureValidator:
|
|||||||
|
|
||||||
def test_valid_block(self):
|
def test_valid_block(self):
|
||||||
v = ProposerSignatureValidator()
|
v = ProposerSignatureValidator()
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 1, "0x00", ts)
|
bh = _make_block_hash("test", 1, "0x00", ts)
|
||||||
ok, reason = v.validate_block_signature({
|
ok, reason = v.validate_block_signature({
|
||||||
"height": 1, "hash": bh, "parent_hash": "0x00",
|
"height": 1, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -81,7 +81,7 @@ class TestProposerSignatureValidator:
|
|||||||
v = ProposerSignatureValidator()
|
v = ProposerSignatureValidator()
|
||||||
ok, reason = v.validate_block_signature({
|
ok, reason = v.validate_block_signature({
|
||||||
"height": 1, "hash": "0x" + "a" * 64, "parent_hash": "0x00",
|
"height": 1, "hash": "0x" + "a" * 64, "parent_hash": "0x00",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
})
|
})
|
||||||
assert ok is False
|
assert ok is False
|
||||||
assert "Missing proposer" in reason
|
assert "Missing proposer" in reason
|
||||||
@@ -90,7 +90,7 @@ class TestProposerSignatureValidator:
|
|||||||
v = ProposerSignatureValidator()
|
v = ProposerSignatureValidator()
|
||||||
ok, reason = v.validate_block_signature({
|
ok, reason = v.validate_block_signature({
|
||||||
"height": 1, "hash": "badhash", "parent_hash": "0x00",
|
"height": 1, "hash": "badhash", "parent_hash": "0x00",
|
||||||
"proposer": "node-a", "timestamp": datetime.utcnow().isoformat(),
|
"proposer": "node-a", "timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
})
|
})
|
||||||
assert ok is False
|
assert ok is False
|
||||||
assert "Invalid block hash" in reason
|
assert "Invalid block hash" in reason
|
||||||
@@ -99,14 +99,14 @@ class TestProposerSignatureValidator:
|
|||||||
v = ProposerSignatureValidator()
|
v = ProposerSignatureValidator()
|
||||||
ok, reason = v.validate_block_signature({
|
ok, reason = v.validate_block_signature({
|
||||||
"height": 1, "hash": "0xabc", "parent_hash": "0x00",
|
"height": 1, "hash": "0xabc", "parent_hash": "0x00",
|
||||||
"proposer": "node-a", "timestamp": datetime.utcnow().isoformat(),
|
"proposer": "node-a", "timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
})
|
})
|
||||||
assert ok is False
|
assert ok is False
|
||||||
assert "Invalid hash length" in reason
|
assert "Invalid hash length" in reason
|
||||||
|
|
||||||
def test_untrusted_proposer_rejected(self):
|
def test_untrusted_proposer_rejected(self):
|
||||||
v = ProposerSignatureValidator(trusted_proposers=["node-a", "node-b"])
|
v = ProposerSignatureValidator(trusted_proposers=["node-a", "node-b"])
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 1, "0x00", ts)
|
bh = _make_block_hash("test", 1, "0x00", ts)
|
||||||
ok, reason = v.validate_block_signature({
|
ok, reason = v.validate_block_signature({
|
||||||
"height": 1, "hash": bh, "parent_hash": "0x00",
|
"height": 1, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -117,7 +117,7 @@ class TestProposerSignatureValidator:
|
|||||||
|
|
||||||
def test_trusted_proposer_accepted(self):
|
def test_trusted_proposer_accepted(self):
|
||||||
v = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
v = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 1, "0x00", ts)
|
bh = _make_block_hash("test", 1, "0x00", ts)
|
||||||
ok, reason = v.validate_block_signature({
|
ok, reason = v.validate_block_signature({
|
||||||
"height": 1, "hash": bh, "parent_hash": "0x00",
|
"height": 1, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -147,7 +147,7 @@ class TestChainSyncAppend:
|
|||||||
|
|
||||||
def test_append_to_empty_chain(self, session_factory):
|
def test_append_to_empty_chain(self, session_factory):
|
||||||
sync = ChainSync(session_factory, chain_id="test", validate_signatures=False)
|
sync = ChainSync(session_factory, chain_id="test", validate_signatures=False)
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 0, "0x00", ts)
|
bh = _make_block_hash("test", 0, "0x00", ts)
|
||||||
result = sync.import_block({
|
result = sync.import_block({
|
||||||
"height": 0, "hash": bh, "parent_hash": "0x00",
|
"height": 0, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -232,7 +232,7 @@ class TestChainSyncSignatureValidation:
|
|||||||
def test_untrusted_proposer_rejected_on_import(self, session_factory):
|
def test_untrusted_proposer_rejected_on_import(self, session_factory):
|
||||||
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
||||||
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=True)
|
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=True)
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 0, "0x00", ts)
|
bh = _make_block_hash("test", 0, "0x00", ts)
|
||||||
result = sync.import_block({
|
result = sync.import_block({
|
||||||
"height": 0, "hash": bh, "parent_hash": "0x00",
|
"height": 0, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -244,7 +244,7 @@ class TestChainSyncSignatureValidation:
|
|||||||
def test_trusted_proposer_accepted_on_import(self, session_factory):
|
def test_trusted_proposer_accepted_on_import(self, session_factory):
|
||||||
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
||||||
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=True)
|
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=True)
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 0, "0x00", ts)
|
bh = _make_block_hash("test", 0, "0x00", ts)
|
||||||
result = sync.import_block({
|
result = sync.import_block({
|
||||||
"height": 0, "hash": bh, "parent_hash": "0x00",
|
"height": 0, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -255,7 +255,7 @@ class TestChainSyncSignatureValidation:
|
|||||||
def test_validation_disabled(self, session_factory):
|
def test_validation_disabled(self, session_factory):
|
||||||
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
||||||
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=False)
|
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=False)
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 0, "0x00", ts)
|
bh = _make_block_hash("test", 0, "0x00", ts)
|
||||||
result = sync.import_block({
|
result = sync.import_block({
|
||||||
"height": 0, "hash": bh, "parent_hash": "0x00",
|
"height": 0, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -295,7 +295,7 @@ class TestSyncMetrics:
|
|||||||
|
|
||||||
def test_accepted_block_increments_metrics(self, session_factory):
|
def test_accepted_block_increments_metrics(self, session_factory):
|
||||||
sync = ChainSync(session_factory, chain_id="test", validate_signatures=False)
|
sync = ChainSync(session_factory, chain_id="test", validate_signatures=False)
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 0, "0x00", ts)
|
bh = _make_block_hash("test", 0, "0x00", ts)
|
||||||
sync.import_block({
|
sync.import_block({
|
||||||
"height": 0, "hash": bh, "parent_hash": "0x00",
|
"height": 0, "hash": bh, "parent_hash": "0x00",
|
||||||
@@ -308,7 +308,7 @@ class TestSyncMetrics:
|
|||||||
def test_rejected_block_increments_metrics(self, session_factory):
|
def test_rejected_block_increments_metrics(self, session_factory):
|
||||||
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
|
||||||
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=True)
|
sync = ChainSync(session_factory, chain_id="test", validator=validator, validate_signatures=True)
|
||||||
ts = datetime.utcnow()
|
ts = datetime.now(datetime.UTC)
|
||||||
bh = _make_block_hash("test", 0, "0x00", ts)
|
bh = _make_block_hash("test", 0, "0x00", ts)
|
||||||
sync.import_block({
|
sync.import_block({
|
||||||
"height": 0, "hash": bh, "parent_hash": "0x00",
|
"height": 0, "hash": bh, "parent_hash": "0x00",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Handles KYC/AML, regulatory compliance, and monitoring
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, Any, List, Optional
|
from typing import Dict, Any, List, Optional
|
||||||
from fastapi import FastAPI, HTTPException
|
from fastapi import FastAPI, HTTPException
|
||||||
@@ -68,7 +68,7 @@ async def root():
|
|||||||
return {
|
return {
|
||||||
"service": "AITBC Compliance Service",
|
"service": "AITBC Compliance Service",
|
||||||
"status": "running",
|
"status": "running",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"version": "1.0.0"
|
"version": "1.0.0"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ async def submit_kyc(kyc_request: KYCRequest):
|
|||||||
"document_number": kyc_request.document_number,
|
"document_number": kyc_request.document_number,
|
||||||
"address": kyc_request.address,
|
"address": kyc_request.address,
|
||||||
"status": "pending",
|
"status": "pending",
|
||||||
"submitted_at": datetime.utcnow().isoformat(),
|
"submitted_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"reviewed_at": None,
|
"reviewed_at": None,
|
||||||
"approved_at": None,
|
"approved_at": None,
|
||||||
"risk_score": "medium",
|
"risk_score": "medium",
|
||||||
@@ -111,8 +111,8 @@ async def submit_kyc(kyc_request: KYCRequest):
|
|||||||
|
|
||||||
# Auto-approve for demo (in production, this would involve actual verification)
|
# Auto-approve for demo (in production, this would involve actual verification)
|
||||||
kyc_record["status"] = "approved"
|
kyc_record["status"] = "approved"
|
||||||
kyc_record["reviewed_at"] = datetime.utcnow().isoformat()
|
kyc_record["reviewed_at"] = datetime.now(datetime.UTC).isoformat()
|
||||||
kyc_record["approved_at"] = datetime.utcnow().isoformat()
|
kyc_record["approved_at"] = datetime.now(datetime.UTC).isoformat()
|
||||||
kyc_record["risk_score"] = "low"
|
kyc_record["risk_score"] = "low"
|
||||||
|
|
||||||
logger.info(f"KYC approved for user: {kyc_request.user_id}")
|
logger.info(f"KYC approved for user: {kyc_request.user_id}")
|
||||||
@@ -146,7 +146,7 @@ async def list_kyc_records():
|
|||||||
@app.post("/api/v1/compliance/report")
|
@app.post("/api/v1/compliance/report")
|
||||||
async def create_compliance_report(report: ComplianceReport):
|
async def create_compliance_report(report: ComplianceReport):
|
||||||
"""Create a compliance report"""
|
"""Create a compliance report"""
|
||||||
report_id = f"report_{int(datetime.utcnow().timestamp())}"
|
report_id = f"report_{int(datetime.now(datetime.UTC).timestamp())}"
|
||||||
|
|
||||||
compliance_record = {
|
compliance_record = {
|
||||||
"report_id": report_id,
|
"report_id": report_id,
|
||||||
@@ -155,7 +155,7 @@ async def create_compliance_report(report: ComplianceReport):
|
|||||||
"severity": report.severity,
|
"severity": report.severity,
|
||||||
"details": report.details,
|
"details": report.details,
|
||||||
"status": "open",
|
"status": "open",
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"assigned_to": None,
|
"assigned_to": None,
|
||||||
"resolved_at": None,
|
"resolved_at": None,
|
||||||
"resolution": None
|
"resolution": None
|
||||||
@@ -195,7 +195,7 @@ async def monitor_transaction(transaction: TransactionMonitoring):
|
|||||||
"currency": transaction.currency,
|
"currency": transaction.currency,
|
||||||
"counterparty": transaction.counterparty,
|
"counterparty": transaction.counterparty,
|
||||||
"timestamp": transaction.timestamp.isoformat(),
|
"timestamp": transaction.timestamp.isoformat(),
|
||||||
"monitored_at": datetime.utcnow().isoformat(),
|
"monitored_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"risk_score": calculate_transaction_risk(transaction),
|
"risk_score": calculate_transaction_risk(transaction),
|
||||||
"flags": [],
|
"flags": [],
|
||||||
"status": "monitored"
|
"status": "monitored"
|
||||||
@@ -232,7 +232,7 @@ async def list_monitored_transactions():
|
|||||||
@app.post("/api/v1/rules/create")
|
@app.post("/api/v1/rules/create")
|
||||||
async def create_compliance_rule(rule_data: Dict[str, Any]):
|
async def create_compliance_rule(rule_data: Dict[str, Any]):
|
||||||
"""Create a new compliance rule"""
|
"""Create a new compliance rule"""
|
||||||
rule_id = f"rule_{int(datetime.utcnow().timestamp())}"
|
rule_id = f"rule_{int(datetime.now(datetime.UTC).timestamp())}"
|
||||||
|
|
||||||
rule = {
|
rule = {
|
||||||
"rule_id": rule_id,
|
"rule_id": rule_id,
|
||||||
@@ -243,7 +243,7 @@ async def create_compliance_rule(rule_data: Dict[str, Any]):
|
|||||||
"actions": rule_data.get("actions", []),
|
"actions": rule_data.get("actions", []),
|
||||||
"severity": rule_data.get("severity", "medium"),
|
"severity": rule_data.get("severity", "medium"),
|
||||||
"active": True,
|
"active": True,
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"trigger_count": 0
|
"trigger_count": 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,7 +294,7 @@ async def compliance_dashboard():
|
|||||||
},
|
},
|
||||||
"risk_distribution": get_risk_distribution(),
|
"risk_distribution": get_risk_distribution(),
|
||||||
"recent_activity": get_recent_activity(),
|
"recent_activity": get_recent_activity(),
|
||||||
"generated_at": datetime.utcnow().isoformat()
|
"generated_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
# Helper functions
|
# Helper functions
|
||||||
@@ -337,7 +337,7 @@ def check_suspicious_patterns(transaction: TransactionMonitoring) -> List[str]:
|
|||||||
|
|
||||||
recent_transactions = [t for t in user_transactions
|
recent_transactions = [t for t in user_transactions
|
||||||
if datetime.fromisoformat(t["monitored_at"]) >
|
if datetime.fromisoformat(t["monitored_at"]) >
|
||||||
datetime.utcnow() - timedelta(hours=1)]
|
datetime.now(datetime.UTC) - timedelta(hours=1)]
|
||||||
|
|
||||||
if len(recent_transactions) > 5:
|
if len(recent_transactions) > 5:
|
||||||
flags.append("rapid_transactions")
|
flags.append("rapid_transactions")
|
||||||
@@ -385,7 +385,7 @@ def get_recent_activity() -> List[Dict]:
|
|||||||
recent_kyc = [r for r in kyc_records.values()
|
recent_kyc = [r for r in kyc_records.values()
|
||||||
if r.get("approved_at") and
|
if r.get("approved_at") and
|
||||||
datetime.fromisoformat(r["approved_at"]) >
|
datetime.fromisoformat(r["approved_at"]) >
|
||||||
datetime.utcnow() - timedelta(hours=24)]
|
datetime.now(datetime.UTC) - timedelta(hours=24)]
|
||||||
|
|
||||||
for kyc in recent_kyc[:5]:
|
for kyc in recent_kyc[:5]:
|
||||||
activities.append({
|
activities.append({
|
||||||
@@ -397,7 +397,7 @@ def get_recent_activity() -> List[Dict]:
|
|||||||
# Recent compliance reports
|
# Recent compliance reports
|
||||||
recent_reports = [r for r in compliance_reports.values()
|
recent_reports = [r for r in compliance_reports.values()
|
||||||
if datetime.fromisoformat(r["created_at"]) >
|
if datetime.fromisoformat(r["created_at"]) >
|
||||||
datetime.utcnow() - timedelta(hours=24)]
|
datetime.now(datetime.UTC) - timedelta(hours=24)]
|
||||||
|
|
||||||
for report in recent_reports[:5]:
|
for report in recent_reports[:5]:
|
||||||
activities.append({
|
activities.append({
|
||||||
@@ -418,7 +418,7 @@ async def periodic_compliance_checks():
|
|||||||
await asyncio.sleep(300) # Check every 5 minutes
|
await asyncio.sleep(300) # Check every 5 minutes
|
||||||
|
|
||||||
# Check for expired KYC records
|
# Check for expired KYC records
|
||||||
current_time = datetime.utcnow()
|
current_time = datetime.now(datetime.UTC)
|
||||||
for user_id, kyc_record in kyc_records.items():
|
for user_id, kyc_record in kyc_records.items():
|
||||||
if kyc_record["status"] == "approved":
|
if kyc_record["status"] == "approved":
|
||||||
approved_time = datetime.fromisoformat(kyc_record["approved_at"])
|
approved_time = datetime.fromisoformat(kyc_record["approved_at"])
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import sys
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import Mock, patch
|
from unittest.mock import Mock, patch
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
|
|
||||||
from main import app, KYCRequest, ComplianceReport, TransactionMonitoring, kyc_records, compliance_reports, suspicious_transactions, compliance_rules
|
from main import app, KYCRequest, ComplianceReport, TransactionMonitoring, kyc_records, compliance_reports, suspicious_transactions, compliance_rules
|
||||||
@@ -62,7 +62,7 @@ def test_transaction_monitoring_zero_amount():
|
|||||||
amount=0.0,
|
amount=0.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="counterparty1",
|
counterparty="counterparty1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
assert tx.amount == 0.0
|
assert tx.amount == 0.0
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ def test_transaction_monitoring_negative_amount():
|
|||||||
amount=-1000.0,
|
amount=-1000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="counterparty1",
|
counterparty="counterparty1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
assert tx.amount == -1000.0
|
assert tx.amount == -1000.0
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import sys
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import Mock, patch
|
from unittest.mock import Mock, patch
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
|
|
||||||
from main import app, KYCRequest, ComplianceReport, TransactionMonitoring, kyc_records, compliance_reports, suspicious_transactions, compliance_rules
|
from main import app, KYCRequest, ComplianceReport, TransactionMonitoring, kyc_records, compliance_reports, suspicious_transactions, compliance_rules
|
||||||
@@ -171,7 +171,7 @@ def test_monitor_transaction():
|
|||||||
amount=1000.0,
|
amount=1000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="counterparty1",
|
counterparty="counterparty1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
response = client.post("/api/v1/monitoring/transaction", json=tx.model_dump(mode='json'))
|
response = client.post("/api/v1/monitoring/transaction", json=tx.model_dump(mode='json'))
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -190,7 +190,7 @@ def test_monitor_suspicious_transaction():
|
|||||||
amount=100000.0,
|
amount=100000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="high_risk_entity_1",
|
counterparty="high_risk_entity_1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
response = client.post("/api/v1/monitoring/transaction", json=tx.model_dump(mode='json'))
|
response = client.post("/api/v1/monitoring/transaction", json=tx.model_dump(mode='json'))
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import sys
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import Mock, patch
|
from unittest.mock import Mock, patch
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
|
|
||||||
from main import app, KYCRequest, ComplianceReport, TransactionMonitoring, calculate_transaction_risk, check_suspicious_patterns
|
from main import app, KYCRequest, ComplianceReport, TransactionMonitoring, calculate_transaction_risk, check_suspicious_patterns
|
||||||
@@ -62,7 +62,7 @@ def test_transaction_monitoring_model():
|
|||||||
amount=1000.0,
|
amount=1000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="counterparty1",
|
counterparty="counterparty1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
assert tx.transaction_id == "tx123"
|
assert tx.transaction_id == "tx123"
|
||||||
assert tx.user_id == "user123"
|
assert tx.user_id == "user123"
|
||||||
@@ -125,7 +125,7 @@ def test_check_suspicious_patterns_high_value():
|
|||||||
amount=100000.0,
|
amount=100000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="counterparty1",
|
counterparty="counterparty1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
flags = check_suspicious_patterns(tx)
|
flags = check_suspicious_patterns(tx)
|
||||||
assert "high_value_transaction" in flags
|
assert "high_value_transaction" in flags
|
||||||
@@ -140,7 +140,7 @@ def test_check_suspicious_patterns_high_risk_counterparty():
|
|||||||
amount=1000.0,
|
amount=1000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="high_risk_entity_1",
|
counterparty="high_risk_entity_1",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
flags = check_suspicious_patterns(tx)
|
flags = check_suspicious_patterns(tx)
|
||||||
assert "high_risk_counterparty" in flags
|
assert "high_risk_counterparty" in flags
|
||||||
@@ -155,7 +155,7 @@ def test_check_suspicious_patterns_none():
|
|||||||
amount=1000.0,
|
amount=1000.0,
|
||||||
currency="BTC",
|
currency="BTC",
|
||||||
counterparty="safe_counterparty",
|
counterparty="safe_counterparty",
|
||||||
timestamp=datetime.utcnow()
|
timestamp=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
flags = check_suspicious_patterns(tx)
|
flags = check_suspicious_patterns(tx)
|
||||||
assert len(flags) == 0
|
assert len(flags) == 0
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Demonstrates basic usage of the Agent Identity SDK
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
|
|
||||||
# Import SDK components
|
# Import SDK components
|
||||||
@@ -94,7 +94,7 @@ async def basic_identity_example():
|
|||||||
"agent_id": identity.agent_id,
|
"agent_id": identity.agent_id,
|
||||||
"chain_id": mapping.chain_id,
|
"chain_id": mapping.chain_id,
|
||||||
"chain_address": mapping.chain_address,
|
"chain_address": mapping.chain_address,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"verification_method": "demo"
|
"verification_method": "demo"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +234,7 @@ async def advanced_transaction_example():
|
|||||||
"description": "Updated description with new capabilities",
|
"description": "Updated description with new capabilities",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"last_updated": datetime.utcnow().isoformat()
|
"last_updated": datetime.now(datetime.UTC).isoformat()
|
||||||
},
|
},
|
||||||
"tags": ["demo", "ai", "updated"]
|
"tags": ["demo", "ai", "updated"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Complete deployment procedures for the agent orchestration system
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
from aitbc.logging import get_logger
|
from aitbc.logging import get_logger
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Dict, List, Optional, Any
|
from typing import Dict, List, Optional, Any
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ class AgentOrchestrationDeployment:
|
|||||||
"""Deploy complete agent orchestration system to production"""
|
"""Deploy complete agent orchestration system to production"""
|
||||||
|
|
||||||
deployment_result = {
|
deployment_result = {
|
||||||
"deployment_id": f"prod_deploy_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}",
|
"deployment_id": f"prod_deploy_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}",
|
||||||
"status": "in_progress",
|
"status": "in_progress",
|
||||||
"steps_completed": [],
|
"steps_completed": [],
|
||||||
"steps_failed": [],
|
"steps_failed": [],
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Ongoing maintenance, monitoring, and enhancement of the complete system
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
from aitbc.logging import get_logger
|
from aitbc.logging import get_logger
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Dict, List, Optional, Any
|
from typing import Dict, List, Optional, Any
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ class SystemMaintenanceManager:
|
|||||||
"""Perform comprehensive maintenance cycle"""
|
"""Perform comprehensive maintenance cycle"""
|
||||||
|
|
||||||
maintenance_result = {
|
maintenance_result = {
|
||||||
"maintenance_cycle": f"maintenance_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}",
|
"maintenance_cycle": f"maintenance_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}",
|
||||||
"status": "in_progress",
|
"status": "in_progress",
|
||||||
"categories_completed": [],
|
"categories_completed": [],
|
||||||
"enhancements_implemented": [],
|
"enhancements_implemented": [],
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Provides unified agent identification and cross-chain compatibility
|
|||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ class AgentIdentityCore:
|
|||||||
if hasattr(identity, field):
|
if hasattr(identity, field):
|
||||||
setattr(identity, field, value)
|
setattr(identity, field, value)
|
||||||
|
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
self.session.refresh(identity)
|
self.session.refresh(identity)
|
||||||
@@ -133,7 +133,7 @@ class AgentIdentityCore:
|
|||||||
# Update identity's supported chains
|
# Update identity's supported chains
|
||||||
if chain_id not in identity.supported_chains:
|
if chain_id not in identity.supported_chains:
|
||||||
identity.supported_chains.append(str(chain_id))
|
identity.supported_chains.append(str(chain_id))
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
logger.info(f"Registered cross-chain identity: {identity_id} -> {chain_id}:{chain_address}")
|
logger.info(f"Registered cross-chain identity: {identity_id} -> {chain_id}:{chain_address}")
|
||||||
@@ -190,7 +190,7 @@ class AgentIdentityCore:
|
|||||||
|
|
||||||
# Update mapping verification status
|
# Update mapping verification status
|
||||||
mapping.is_verified = True
|
mapping.is_verified = True
|
||||||
mapping.verified_at = datetime.utcnow()
|
mapping.verified_at = datetime.now(datetime.UTC)
|
||||||
mapping.verification_proof = proof_data
|
mapping.verification_proof = proof_data
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -198,7 +198,7 @@ class AgentIdentityCore:
|
|||||||
identity = await self.get_identity(identity_id)
|
identity = await self.get_identity(identity_id)
|
||||||
if identity and chain_id == identity.primary_chain:
|
if identity and chain_id == identity.primary_chain:
|
||||||
identity.is_verified = True
|
identity.is_verified = True
|
||||||
identity.verified_at = datetime.utcnow()
|
identity.verified_at = datetime.now(datetime.UTC)
|
||||||
identity.verification_level = verification_type
|
identity.verification_level = verification_type
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -242,7 +242,7 @@ class AgentIdentityCore:
|
|||||||
else:
|
else:
|
||||||
setattr(mapping, field, value)
|
setattr(mapping, field, value)
|
||||||
|
|
||||||
mapping.updated_at = datetime.utcnow()
|
mapping.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
self.session.refresh(mapping)
|
self.session.refresh(mapping)
|
||||||
@@ -260,11 +260,11 @@ class AgentIdentityCore:
|
|||||||
# Update identity status
|
# Update identity status
|
||||||
identity.status = IdentityStatus.REVOKED
|
identity.status = IdentityStatus.REVOKED
|
||||||
identity.is_verified = False
|
identity.is_verified = False
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Add revocation reason to identity_data
|
# Add revocation reason to identity_data
|
||||||
identity.identity_data["revocation_reason"] = reason
|
identity.identity_data["revocation_reason"] = reason
|
||||||
identity.identity_data["revoked_at"] = datetime.utcnow().isoformat()
|
identity.identity_data["revoked_at"] = datetime.now(datetime.UTC).isoformat()
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -280,11 +280,11 @@ class AgentIdentityCore:
|
|||||||
|
|
||||||
# Update identity status
|
# Update identity status
|
||||||
identity.status = IdentityStatus.SUSPENDED
|
identity.status = IdentityStatus.SUSPENDED
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Add suspension reason to identity_data
|
# Add suspension reason to identity_data
|
||||||
identity.identity_data["suspension_reason"] = reason
|
identity.identity_data["suspension_reason"] = reason
|
||||||
identity.identity_data["suspended_at"] = datetime.utcnow().isoformat()
|
identity.identity_data["suspended_at"] = datetime.now(datetime.UTC).isoformat()
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -303,7 +303,7 @@ class AgentIdentityCore:
|
|||||||
|
|
||||||
# Update identity status
|
# Update identity status
|
||||||
identity.status = IdentityStatus.ACTIVE
|
identity.status = IdentityStatus.ACTIVE
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Clear suspension identity_data
|
# Clear suspension identity_data
|
||||||
if "suspension_reason" in identity.identity_data:
|
if "suspension_reason" in identity.identity_data:
|
||||||
@@ -336,8 +336,8 @@ class AgentIdentityCore:
|
|||||||
volume_factor = min(amount / 1000.0, 1.0) # Cap at 1.0 for amounts > 1000
|
volume_factor = min(amount / 1000.0, 1.0) # Cap at 1.0 for amounts > 1000
|
||||||
identity.reputation_score = base_score * (0.7 + 0.3 * volume_factor)
|
identity.reputation_score = base_score * (0.7 + 0.3 * volume_factor)
|
||||||
|
|
||||||
identity.last_activity = datetime.utcnow()
|
identity.last_activity = datetime.now(datetime.UTC)
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
self.session.refresh(identity)
|
self.session.refresh(identity)
|
||||||
@@ -452,7 +452,7 @@ class AgentIdentityCore:
|
|||||||
"owner_address": identity.owner_address,
|
"owner_address": identity.owner_address,
|
||||||
"chain_id": chain_id,
|
"chain_id": chain_id,
|
||||||
"chain_address": mapping.chain_address,
|
"chain_address": mapping.chain_address,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"nonce": str(uuid4()),
|
"nonce": str(uuid4()),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -463,5 +463,5 @@ class AgentIdentityCore:
|
|||||||
return {
|
return {
|
||||||
"proof_data": proof_data,
|
"proof_data": proof_data,
|
||||||
"proof_hash": proof_hash,
|
"proof_hash": proof_hash,
|
||||||
"expires_at": (datetime.utcnow() + timedelta(hours=24)).isoformat(),
|
"expires_at": (datetime.now(datetime.UTC) + timedelta(hours=24)).isoformat(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Agent Identity Manager Implementation
|
|||||||
High-level manager for agent identity operations and cross-chain management
|
High-level manager for agent identity operations and cross-chain management
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -171,7 +171,7 @@ class AgentIdentityManager:
|
|||||||
# Update identity reputation
|
# Update identity reputation
|
||||||
await self.core.update_reputation(agent_id, True, 0) # This will recalculate based on new data
|
await self.core.update_reputation(agent_id, True, 0) # This will recalculate based on new data
|
||||||
identity.reputation_score = aggregated_score
|
identity.reputation_score = aggregated_score
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
else:
|
else:
|
||||||
aggregated_score = identity.reputation_score
|
aggregated_score = identity.reputation_score
|
||||||
@@ -181,7 +181,7 @@ class AgentIdentityManager:
|
|||||||
"aggregated_reputation": aggregated_score,
|
"aggregated_reputation": aggregated_score,
|
||||||
"chain_reputations": reputation_scores,
|
"chain_reputations": reputation_scores,
|
||||||
"verified_chains": list(verified_chains) if "verified_chains" in locals() else [],
|
"verified_chains": list(verified_chains) if "verified_chains" in locals() else [],
|
||||||
"sync_timestamp": datetime.utcnow().isoformat(),
|
"sync_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -449,12 +449,12 @@ class AgentIdentityManager:
|
|||||||
"supported_chains": supported_chains,
|
"supported_chains": supported_chains,
|
||||||
"cleaned_verifications": cleaned_count,
|
"cleaned_verifications": cleaned_count,
|
||||||
"issues": issues,
|
"issues": issues,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to get registry health: {e}")
|
logger.error(f"Failed to get registry health: {e}")
|
||||||
return {"status": "error", "error": "Health check failed", "timestamp": datetime.utcnow().isoformat()}
|
return {"status": "error", "error": "Health check failed", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
|
|
||||||
async def export_agent_identity(self, agent_id: str, format: str = "json") -> dict[str, Any]:
|
async def export_agent_identity(self, agent_id: str, format: str = "json") -> dict[str, Any]:
|
||||||
"""Export agent identity data for backup or migration"""
|
"""Export agent identity data for backup or migration"""
|
||||||
@@ -469,7 +469,7 @@ class AgentIdentityManager:
|
|||||||
# Prepare export data
|
# Prepare export data
|
||||||
export_data = {
|
export_data = {
|
||||||
"export_version": "1.0",
|
"export_version": "1.0",
|
||||||
"export_timestamp": datetime.utcnow().isoformat(),
|
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"identity": summary["identity"],
|
"identity": summary["identity"],
|
||||||
"cross_chain_mappings": summary["cross_chain"]["mappings"],
|
"cross_chain_mappings": summary["cross_chain"]["mappings"],
|
||||||
@@ -541,7 +541,7 @@ class AgentIdentityManager:
|
|||||||
"identity_id": identity.id,
|
"identity_id": identity.id,
|
||||||
"import_successful": True,
|
"import_successful": True,
|
||||||
"restored_mappings": len(chain_mappings),
|
"restored_mappings": len(chain_mappings),
|
||||||
"import_timestamp": datetime.utcnow().isoformat(),
|
"import_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Registry for cross-chain agent identity mapping and synchronization
|
|||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ class CrossChainRegistry:
|
|||||||
registration_results.append({"chain_id": chain_id, "chain_address": chain_address, "error": str(e)})
|
registration_results.append({"chain_id": chain_id, "chain_address": chain_address, "error": str(e)})
|
||||||
|
|
||||||
# Update identity
|
# Update identity
|
||||||
identity.updated_at = datetime.utcnow()
|
identity.updated_at = datetime.now(datetime.UTC)
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -143,7 +143,7 @@ class CrossChainRegistry:
|
|||||||
|
|
||||||
old_address = mapping.chain_address
|
old_address = mapping.chain_address
|
||||||
mapping.chain_address = new_address.lower()
|
mapping.chain_address = new_address.lower()
|
||||||
mapping.updated_at = datetime.utcnow()
|
mapping.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Reset verification status since address changed
|
# Reset verification status since address changed
|
||||||
mapping.is_verified = False
|
mapping.is_verified = False
|
||||||
@@ -195,7 +195,7 @@ class CrossChainRegistry:
|
|||||||
proof_hash=proof_hash,
|
proof_hash=proof_hash,
|
||||||
proof_data=proof_data,
|
proof_data=proof_data,
|
||||||
verification_result="approved",
|
verification_result="approved",
|
||||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
expires_at=datetime.now(datetime.UTC) + timedelta(days=30),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(verification)
|
self.session.add(verification)
|
||||||
@@ -204,7 +204,7 @@ class CrossChainRegistry:
|
|||||||
|
|
||||||
# Update mapping verification status
|
# Update mapping verification status
|
||||||
mapping.is_verified = True
|
mapping.is_verified = True
|
||||||
mapping.verified_at = datetime.utcnow()
|
mapping.verified_at = datetime.now(datetime.UTC)
|
||||||
mapping.verification_proof = proof_data
|
mapping.verification_proof = proof_data
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -212,7 +212,7 @@ class CrossChainRegistry:
|
|||||||
if self._is_higher_verification_level(verification_type, identity.verification_level):
|
if self._is_higher_verification_level(verification_type, identity.verification_level):
|
||||||
identity.verification_level = verification_type
|
identity.verification_level = verification_type
|
||||||
identity.is_verified = True
|
identity.is_verified = True
|
||||||
identity.verified_at = datetime.utcnow()
|
identity.verified_at = datetime.now(datetime.UTC)
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
logger.info(f"Verified cross-chain identity: {identity_id} on chain {chain_id}")
|
logger.info(f"Verified cross-chain identity: {identity_id} on chain {chain_id}")
|
||||||
@@ -229,14 +229,14 @@ class CrossChainRegistry:
|
|||||||
mapping.is_verified = False
|
mapping.is_verified = False
|
||||||
mapping.verified_at = None
|
mapping.verified_at = None
|
||||||
mapping.verification_proof = None
|
mapping.verification_proof = None
|
||||||
mapping.updated_at = datetime.utcnow()
|
mapping.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Add revocation to metadata
|
# Add revocation to metadata
|
||||||
if not mapping.chain_metadata:
|
if not mapping.chain_metadata:
|
||||||
mapping.chain_metadata = {}
|
mapping.chain_metadata = {}
|
||||||
mapping.chain_metadata["verification_revoked"] = True
|
mapping.chain_metadata["verification_revoked"] = True
|
||||||
mapping.chain_metadata["revocation_reason"] = reason
|
mapping.chain_metadata["revocation_reason"] = reason
|
||||||
mapping.chain_metadata["revoked_at"] = datetime.utcnow().isoformat()
|
mapping.chain_metadata["revoked_at"] = datetime.now(datetime.UTC).isoformat()
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -453,7 +453,7 @@ class CrossChainRegistry:
|
|||||||
async def cleanup_expired_verifications(self) -> int:
|
async def cleanup_expired_verifications(self) -> int:
|
||||||
"""Clean up expired verification records"""
|
"""Clean up expired verification records"""
|
||||||
|
|
||||||
current_time = datetime.utcnow()
|
current_time = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Find expired verifications
|
# Find expired verifications
|
||||||
stmt = select(IdentityVerification).where(IdentityVerification.expires_at < current_time)
|
stmt = select(IdentityVerification).where(IdentityVerification.expires_at < current_time)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Provides blockchain-agnostic wallet interface for agents
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ class EthereumWalletAdapter(WalletAdapter):
|
|||||||
"wallet_address": f"0x{'0' * 40}", # Mock address
|
"wallet_address": f"0x{'0' * 40}", # Mock address
|
||||||
"contract_address": f"0x{'1' * 40}", # Mock contract
|
"contract_address": f"0x{'1' * 40}", # Mock contract
|
||||||
"transaction_hash": f"0x{'2' * 64}", # Mock tx hash
|
"transaction_hash": f"0x{'2' * 64}", # Mock tx hash
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
async def get_balance(self, wallet_address: str) -> Decimal:
|
async def get_balance(self, wallet_address: str) -> Decimal:
|
||||||
@@ -91,7 +91,7 @@ class EthereumWalletAdapter(WalletAdapter):
|
|||||||
"gas_price": "20000000000",
|
"gas_price": "20000000000",
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"block_number": 12345,
|
"block_number": 12345,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
async def get_transaction_history(self, wallet_address: str, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
|
async def get_transaction_history(self, wallet_address: str, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
|
||||||
@@ -105,7 +105,7 @@ class EthereumWalletAdapter(WalletAdapter):
|
|||||||
"amount": "0.1",
|
"amount": "0.1",
|
||||||
"gas_used": "21000",
|
"gas_used": "21000",
|
||||||
"block_number": 12344,
|
"block_number": 12344,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -269,7 +269,7 @@ class MultiChainWalletAdapter:
|
|||||||
|
|
||||||
# Update wallet in database
|
# Update wallet in database
|
||||||
wallet.total_spent += float(amount)
|
wallet.total_spent += float(amount)
|
||||||
wallet.last_transaction = datetime.utcnow()
|
wallet.last_transaction = datetime.now(datetime.UTC)
|
||||||
wallet.transaction_count += 1
|
wallet.transaction_count += 1
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
@@ -312,7 +312,7 @@ class MultiChainWalletAdapter:
|
|||||||
if hasattr(wallet, field):
|
if hasattr(wallet, field):
|
||||||
setattr(wallet, field, value)
|
setattr(wallet, field, value)
|
||||||
|
|
||||||
wallet.updated_at = datetime.utcnow()
|
wallet.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
self.session.refresh(wallet)
|
self.session.refresh(wallet)
|
||||||
@@ -338,7 +338,7 @@ class MultiChainWalletAdapter:
|
|||||||
|
|
||||||
# Deactivate wallet
|
# Deactivate wallet
|
||||||
wallet.is_active = False
|
wallet.is_active = False
|
||||||
wallet.updated_at = datetime.utcnow()
|
wallet.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import hashlib
|
|||||||
import json
|
import json
|
||||||
import secrets
|
import secrets
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -124,7 +124,7 @@ class EnhancedWalletAdapter(ABC):
|
|||||||
"""Securely sign a message"""
|
"""Securely sign a message"""
|
||||||
try:
|
try:
|
||||||
# Add timestamp and nonce for replay protection
|
# Add timestamp and nonce for replay protection
|
||||||
timestamp = str(int(datetime.utcnow().timestamp()))
|
timestamp = str(int(datetime.now(datetime.UTC).timestamp()))
|
||||||
nonce = secrets.token_hex(16)
|
nonce = secrets.token_hex(16)
|
||||||
|
|
||||||
message_to_sign = f"{message}:{timestamp}:{nonce}"
|
message_to_sign = f"{message}:{timestamp}:{nonce}"
|
||||||
@@ -194,7 +194,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
|
|||||||
"chain_type": self.chain_type.value,
|
"chain_type": self.chain_type.value,
|
||||||
"owner_address": owner_address,
|
"owner_address": owner_address,
|
||||||
"security_level": self.security_level.value,
|
"security_level": self.security_level.value,
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"status": WalletStatus.ACTIVE.value,
|
"status": WalletStatus.ACTIVE.value,
|
||||||
"security_config": security_config,
|
"security_config": security_config,
|
||||||
"nonce": 0,
|
"nonce": 0,
|
||||||
@@ -227,7 +227,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
|
|||||||
"chain_id": self.chain_id,
|
"chain_id": self.chain_id,
|
||||||
"eth_balance": eth_balance,
|
"eth_balance": eth_balance,
|
||||||
"token_balances": {},
|
"token_balances": {},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Get token balances if specified
|
# Get token balances if specified
|
||||||
@@ -304,7 +304,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
|
|||||||
"gas_limit": gas_limit,
|
"gas_limit": gas_limit,
|
||||||
"gas_price": gas_price,
|
"gas_price": gas_price,
|
||||||
"status": TransactionStatus.PENDING.value,
|
"status": TransactionStatus.PENDING.value,
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(f"Executed Ethereum transaction {tx_hash} from {from_address} to {to_address}")
|
logger.info(f"Executed Ethereum transaction {tx_hash} from {from_address} to {to_address}")
|
||||||
@@ -331,7 +331,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
|
|||||||
"gas_used": None,
|
"gas_used": None,
|
||||||
"effective_gas_price": None,
|
"effective_gas_price": None,
|
||||||
"logs": [],
|
"logs": [],
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Get transaction details
|
# Get transaction details
|
||||||
@@ -348,7 +348,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
|
|||||||
"from": tx_data.get("from"),
|
"from": tx_data.get("from"),
|
||||||
"to": tx_data.get("to"),
|
"to": tx_data.get("to"),
|
||||||
"value": int(tx_data.get("value", "0x0"), 16),
|
"value": int(tx_data.get("value", "0x0"), 16),
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Advanced Agent Performance Domain Models
|
|||||||
Implements SQLModel definitions for meta-learning, resource management, and performance optimization
|
Implements SQLModel definitions for meta-learning, resource management, and performance optimization
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
@@ -206,7 +206,7 @@ class ResourceAllocation(SQLModel, table=True):
|
|||||||
|
|
||||||
# Timestamps
|
# Timestamps
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||||
updated_at: datetime = Field(default_factory=datetime.utcnow())
|
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||||
|
|
||||||
# Additional data
|
# Additional data
|
||||||
allocation_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
allocation_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Domain models for agent portfolio management, trading strategies, and risk asses
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
|
|
||||||
from sqlalchemy import JSON, Column
|
from sqlalchemy import JSON, Column
|
||||||
@@ -223,7 +223,7 @@ class StrategySignal(SQLModel, table=True):
|
|||||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||||
is_executed: bool = Field(default=False, index=True)
|
is_executed: bool = Field(default=False, index=True)
|
||||||
executed_at: datetime | None = Field(default=None)
|
executed_at: datetime | None = Field(default=None)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
||||||
|
|
||||||
|
|
||||||
@@ -278,4 +278,4 @@ class MarketCondition(SQLModel, table=True):
|
|||||||
support_level: float = Field(default=0.0) # Support level
|
support_level: float = Field(default=0.0) # Support level
|
||||||
resistance_level: float = Field(default=0.0) # Resistance level
|
resistance_level: float = Field(default=0.0) # Resistance level
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Domain models for automated market making, liquidity pools, and swap transaction
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
|
|
||||||
from sqlalchemy import JSON, Column
|
from sqlalchemy import JSON, Column
|
||||||
@@ -122,7 +122,7 @@ class SwapTransaction(SQLModel, table=True):
|
|||||||
gas_price: float | None = Field(default=None)
|
gas_price: float | None = Field(default=None)
|
||||||
executed_at: datetime | None = Field(default=None, index=True)
|
executed_at: datetime | None = Field(default=None, index=True)
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
||||||
deadline: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(minutes=20))
|
deadline: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(minutes=20))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="swaps")
|
# DISABLED: pool: LiquidityPool = Relationship(back_populates="swaps")
|
||||||
@@ -169,7 +169,7 @@ class FeeStructure(SQLModel, table=True):
|
|||||||
liquidity_adjustment: float = Field(default=0.0) # Liquidity-based adjustment
|
liquidity_adjustment: float = Field(default=0.0) # Liquidity-based adjustment
|
||||||
time_adjustment: float = Field(default=0.0) # Time-based adjustment
|
time_adjustment: float = Field(default=0.0) # Time-based adjustment
|
||||||
adjusted_at: datetime = Field(default_factory=datetime.utcnow)
|
adjusted_at: datetime = Field(default_factory=datetime.utcnow)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
adjustment_reason: str = Field(default="") # Reason for adjustment
|
adjustment_reason: str = Field(default="") # Reason for adjustment
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@ class IncentiveProgram(SQLModel, table=True):
|
|||||||
vesting_period_days: int = Field(default=0) # Vesting period (0 = no vesting)
|
vesting_period_days: int = Field(default=0) # Vesting period (0 = no vesting)
|
||||||
is_active: bool = Field(default=True, index=True)
|
is_active: bool = Field(default=True, index=True)
|
||||||
start_time: datetime = Field(default_factory=datetime.utcnow)
|
start_time: datetime = Field(default_factory=datetime.utcnow)
|
||||||
end_time: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(days=30))
|
end_time: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(days=30))
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||||
|
|
||||||
@@ -284,7 +284,7 @@ class PoolAlert(SQLModel, table=True):
|
|||||||
is_resolved: bool = Field(default=False, index=True)
|
is_resolved: bool = Field(default=False, index=True)
|
||||||
resolved_at: datetime | None = Field(default=None)
|
resolved_at: datetime | None = Field(default=None)
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
|
|
||||||
|
|
||||||
class PoolSnapshot(SQLModel, table=True):
|
class PoolSnapshot(SQLModel, table=True):
|
||||||
@@ -336,4 +336,4 @@ class ArbitrageOpportunity(SQLModel, table=True):
|
|||||||
execution_tx_hash: str | None = Field(default=None)
|
execution_tx_hash: str | None = Field(default=None)
|
||||||
actual_profit: float | None = Field(default=None)
|
actual_profit: float | None = Field(default=None)
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(minutes=5))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(minutes=5))
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Domain models for cross-chain asset transfers, bridge requests, and validator ma
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
|
|
||||||
from sqlalchemy import JSON, Column
|
from sqlalchemy import JSON, Column
|
||||||
@@ -80,7 +80,7 @@ class BridgeRequest(SQLModel, table=True):
|
|||||||
confirmed_at: datetime | None = Field(default=None)
|
confirmed_at: datetime | None = Field(default=None)
|
||||||
completed_at: datetime | None = Field(default=None)
|
completed_at: datetime | None = Field(default=None)
|
||||||
resolved_at: datetime | None = Field(default=None)
|
resolved_at: datetime | None = Field(default=None)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
# transactions: List["BridgeTransaction"] = Relationship(back_populates="bridge_request")
|
# transactions: List["BridgeTransaction"] = Relationship(back_populates="bridge_request")
|
||||||
@@ -241,7 +241,7 @@ class MerkleProof(SQLModel, table=True):
|
|||||||
tree_depth: int = Field(default=0) # Tree depth
|
tree_depth: int = Field(default=0) # Tree depth
|
||||||
is_valid: bool = Field(default=False)
|
is_valid: bool = Field(default=False)
|
||||||
verified_at: datetime | None = Field(default=None)
|
verified_at: datetime | None = Field(default=None)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||||
|
|
||||||
|
|
||||||
@@ -291,7 +291,7 @@ class BridgeAlert(SQLModel, table=True):
|
|||||||
resolved_at: datetime | None = Field(default=None)
|
resolved_at: datetime | None = Field(default=None)
|
||||||
resolution_notes: str | None = Field(default=None)
|
resolution_notes: str | None = Field(default=None)
|
||||||
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
||||||
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=24))
|
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||||
|
|
||||||
|
|
||||||
class BridgeConfiguration(SQLModel, table=True):
|
class BridgeConfiguration(SQLModel, table=True):
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Defines various pricing strategies and their configurations for dynamic pricing
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -515,7 +515,7 @@ class StrategyOptimizer:
|
|||||||
if strategy_id not in self.performance_history:
|
if strategy_id not in self.performance_history:
|
||||||
self.performance_history[strategy_id] = []
|
self.performance_history[strategy_id] = []
|
||||||
|
|
||||||
self.performance_history[strategy_id].append({"timestamp": datetime.utcnow(), "performance": performance_data})
|
self.performance_history[strategy_id].append({"timestamp": datetime.now(datetime.UTC), "performance": performance_data})
|
||||||
|
|
||||||
# Apply optimization rules
|
# Apply optimization rules
|
||||||
optimized_config = self._apply_optimization_rules(strategy_config, performance_data)
|
optimized_config = self._apply_optimization_rules(strategy_config, performance_data)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Exception classes and error response schemas for AITBC coordinator
|
|||||||
Provides structured error responses for consistent API error handling.
|
Provides structured error responses for consistent API error handling.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
@@ -22,7 +22,7 @@ class ErrorResponse(BaseModel):
|
|||||||
"""Standardized error response for all API errors."""
|
"""Standardized error response for all API errors."""
|
||||||
|
|
||||||
error: dict[str, Any] = Field(..., description="Error information")
|
error: dict[str, Any] = Field(..., description="Error information")
|
||||||
timestamp: str = Field(default_factory=lambda: datetime.utcnow().isoformat() + "Z")
|
timestamp: str = Field(default_factory=lambda: datetime.now(datetime.UTC).isoformat() + "Z")
|
||||||
request_id: str | None = Field(None, description="Request ID for tracing")
|
request_id: str | None = Field(None, description="Request ID for tracing")
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Tenant context middleware for multi-tenant isolation
|
|||||||
import hashlib
|
import hashlib
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from contextvars import ContextVar
|
from contextvars import ContextVar
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
from fastapi import HTTPException, Request, status
|
from fastapi import HTTPException, Request, status
|
||||||
from sqlalchemy import and_, event, select
|
from sqlalchemy import and_, event, select
|
||||||
@@ -170,11 +170,11 @@ class TenantContextMiddleware(BaseHTTPMiddleware):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
# Check if key has expired
|
# Check if key has expired
|
||||||
if api_key_record.expires_at and api_key_record.expires_at < datetime.utcnow():
|
if api_key_record.expires_at and api_key_record.expires_at < datetime.now(datetime.UTC):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Update last used timestamp
|
# Update last used timestamp
|
||||||
api_key_record.last_used_at = datetime.utcnow()
|
api_key_record.last_used_at = datetime.now(datetime.UTC)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
# Get tenant
|
# Get tenant
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Repository layer for confidential transactions
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from base64 import b64decode
|
from base64 import b64decode
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
from sqlalchemy import and_, delete, select, update
|
from sqlalchemy import and_, delete, select, update
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
@@ -131,7 +131,7 @@ class ParticipantKeyRepository:
|
|||||||
stmt = (
|
stmt = (
|
||||||
update(ParticipantKeyDB)
|
update(ParticipantKeyDB)
|
||||||
.where(ParticipantKeyDB.participant_id == participant_id)
|
.where(ParticipantKeyDB.participant_id == participant_id)
|
||||||
.values(active=active, revoked_at=datetime.utcnow() if not active else None, revoke_reason=reason)
|
.values(active=active, revoked_at=datetime.now(datetime.UTC) if not active else None, revoke_reason=reason)
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await session.execute(stmt)
|
result = await session.execute(stmt)
|
||||||
@@ -309,7 +309,7 @@ class AuditAuthorizationRepository:
|
|||||||
and_(
|
and_(
|
||||||
AuditAuthorizationDB.id == authorization_id,
|
AuditAuthorizationDB.id == authorization_id,
|
||||||
AuditAuthorizationDB.active,
|
AuditAuthorizationDB.active,
|
||||||
AuditAuthorizationDB.expires_at > datetime.utcnow(),
|
AuditAuthorizationDB.expires_at > datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -321,7 +321,7 @@ class AuditAuthorizationRepository:
|
|||||||
stmt = (
|
stmt = (
|
||||||
update(AuditAuthorizationDB)
|
update(AuditAuthorizationDB)
|
||||||
.where(AuditAuthorizationDB.id == authorization_id)
|
.where(AuditAuthorizationDB.id == authorization_id)
|
||||||
.values(active=False, revoked_at=datetime.utcnow())
|
.values(active=False, revoked_at=datetime.now(datetime.UTC))
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await session.execute(stmt)
|
result = await session.execute(stmt)
|
||||||
@@ -331,7 +331,7 @@ class AuditAuthorizationRepository:
|
|||||||
|
|
||||||
async def cleanup_expired(self, session: AsyncSession) -> int:
|
async def cleanup_expired(self, session: AsyncSession) -> int:
|
||||||
"""Clean up expired authorizations"""
|
"""Clean up expired authorizations"""
|
||||||
stmt = update(AuditAuthorizationDB).where(AuditAuthorizationDB.expires_at < datetime.utcnow()).values(active=False)
|
stmt = update(AuditAuthorizationDB).where(AuditAuthorizationDB.expires_at < datetime.now(datetime.UTC)).values(active=False)
|
||||||
|
|
||||||
result = await session.execute(stmt)
|
result = await session.execute(stmt)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Cross-Chain Reputation Aggregator
|
|||||||
Aggregates reputation data from multiple blockchains and normalizes scores
|
Aggregates reputation data from multiple blockchains and normalizes scores
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -147,7 +147,7 @@ class CrossChainReputationAggregator:
|
|||||||
{
|
{
|
||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"anomaly_type": "low_consistency",
|
"anomaly_type": "low_consistency",
|
||||||
"detected_at": datetime.utcnow(),
|
"detected_at": datetime.now(datetime.UTC),
|
||||||
"description": f"Low consistency score: {aggregation.consistency_score:.2f}",
|
"description": f"Low consistency score: {aggregation.consistency_score:.2f}",
|
||||||
"severity": "high" if aggregation.consistency_score < 0.5 else "medium",
|
"severity": "high" if aggregation.consistency_score < 0.5 else "medium",
|
||||||
"consistency_score": aggregation.consistency_score,
|
"consistency_score": aggregation.consistency_score,
|
||||||
@@ -162,7 +162,7 @@ class CrossChainReputationAggregator:
|
|||||||
{
|
{
|
||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"anomaly_type": "high_variance",
|
"anomaly_type": "high_variance",
|
||||||
"detected_at": datetime.utcnow(),
|
"detected_at": datetime.now(datetime.UTC),
|
||||||
"description": f"High score variance: {aggregation.score_variance:.2f}",
|
"description": f"High score variance: {aggregation.score_variance:.2f}",
|
||||||
"severity": "high" if aggregation.score_variance > 0.5 else "medium",
|
"severity": "high" if aggregation.score_variance > 0.5 else "medium",
|
||||||
"score_variance": aggregation.score_variance,
|
"score_variance": aggregation.score_variance,
|
||||||
@@ -180,7 +180,7 @@ class CrossChainReputationAggregator:
|
|||||||
{
|
{
|
||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"anomaly_type": "missing_chain_data",
|
"anomaly_type": "missing_chain_data",
|
||||||
"detected_at": datetime.utcnow(),
|
"detected_at": datetime.now(datetime.UTC),
|
||||||
"description": f"Missing data for chains: {list(missing_chains)}",
|
"description": f"Missing data for chains: {list(missing_chains)}",
|
||||||
"severity": "medium",
|
"severity": "medium",
|
||||||
"missing_chains": list(missing_chains),
|
"missing_chains": list(missing_chains),
|
||||||
@@ -221,7 +221,7 @@ class CrossChainReputationAggregator:
|
|||||||
# Update reputation
|
# Update reputation
|
||||||
reputation.trust_score = new_score * 1000 # Convert to 0-1000 scale
|
reputation.trust_score = new_score * 1000 # Convert to 0-1000 scale
|
||||||
reputation.reputation_level = self._determine_reputation_level(new_score)
|
reputation.reputation_level = self._determine_reputation_level(new_score)
|
||||||
reputation.updated_at = datetime.utcnow()
|
reputation.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Create event record
|
# Create event record
|
||||||
event = ReputationEvent(
|
event = ReputationEvent(
|
||||||
@@ -231,7 +231,7 @@ class CrossChainReputationAggregator:
|
|||||||
trust_score_before=reputation.trust_score,
|
trust_score_before=reputation.trust_score,
|
||||||
trust_score_after=reputation.trust_score,
|
trust_score_after=reputation.trust_score,
|
||||||
event_data=update,
|
event_data=update,
|
||||||
occurred_at=datetime.utcnow(),
|
occurred_at=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(event)
|
self.session.add(event)
|
||||||
@@ -242,8 +242,8 @@ class CrossChainReputationAggregator:
|
|||||||
agent_id=agent_id,
|
agent_id=agent_id,
|
||||||
trust_score=new_score * 1000,
|
trust_score=new_score * 1000,
|
||||||
reputation_level=self._determine_reputation_level(new_score),
|
reputation_level=self._determine_reputation_level(new_score),
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
updated_at=datetime.utcnow(),
|
updated_at=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(reputation)
|
self.session.add(reputation)
|
||||||
@@ -316,7 +316,7 @@ class CrossChainReputationAggregator:
|
|||||||
"reputation_distribution": distribution,
|
"reputation_distribution": distribution,
|
||||||
"total_transactions": total_transactions,
|
"total_transactions": total_transactions,
|
||||||
"success_rate": success_rate,
|
"success_rate": success_rate,
|
||||||
"last_updated": datetime.utcnow(),
|
"last_updated": datetime.now(datetime.UTC),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -430,7 +430,7 @@ class CrossChainReputationAggregator:
|
|||||||
aggregation.score_variance = variance
|
aggregation.score_variance = variance
|
||||||
aggregation.score_range = score_range
|
aggregation.score_range = score_range
|
||||||
aggregation.consistency_score = consistency_score
|
aggregation.consistency_score = consistency_score
|
||||||
aggregation.last_updated = datetime.utcnow()
|
aggregation.last_updated = datetime.now(datetime.UTC)
|
||||||
else:
|
else:
|
||||||
aggregation = CrossChainReputationAggregation(
|
aggregation = CrossChainReputationAggregation(
|
||||||
agent_id=agent_id,
|
agent_id=agent_id,
|
||||||
@@ -441,8 +441,8 @@ class CrossChainReputationAggregator:
|
|||||||
score_range=score_range,
|
score_range=score_range,
|
||||||
consistency_score=consistency_score,
|
consistency_score=consistency_score,
|
||||||
verification_status="pending",
|
verification_status="pending",
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
last_updated=datetime.utcnow(),
|
last_updated=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(aggregation)
|
self.session.add(aggregation)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Cross-Chain Reputation Engine
|
|||||||
Core reputation calculation and aggregation engine for multi-chain agent reputation
|
Core reputation calculation and aggregation engine for multi-chain agent reputation
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from aitbc import get_logger
|
from aitbc import get_logger
|
||||||
@@ -57,8 +57,8 @@ class CrossChainReputationEngine:
|
|||||||
agent_id=agent_id,
|
agent_id=agent_id,
|
||||||
trust_score=score * 1000, # Convert to 0-1000 scale
|
trust_score=score * 1000, # Convert to 0-1000 scale
|
||||||
reputation_level=self._determine_reputation_level(score),
|
reputation_level=self._determine_reputation_level(score),
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
updated_at=datetime.utcnow(),
|
updated_at=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(new_reputation)
|
self.session.add(new_reputation)
|
||||||
@@ -152,8 +152,8 @@ class CrossChainReputationEngine:
|
|||||||
agent_id=agent_id,
|
agent_id=agent_id,
|
||||||
trust_score=max(0, min(1000, (base_score + impact_score) * 1000)),
|
trust_score=max(0, min(1000, (base_score + impact_score) * 1000)),
|
||||||
reputation_level=self._determine_reputation_level(base_score + impact_score),
|
reputation_level=self._determine_reputation_level(base_score + impact_score),
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
updated_at=datetime.utcnow(),
|
updated_at=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(reputation)
|
self.session.add(reputation)
|
||||||
@@ -164,7 +164,7 @@ class CrossChainReputationEngine:
|
|||||||
|
|
||||||
reputation.trust_score = new_score * 1000
|
reputation.trust_score = new_score * 1000
|
||||||
reputation.reputation_level = self._determine_reputation_level(new_score)
|
reputation.reputation_level = self._determine_reputation_level(new_score)
|
||||||
reputation.updated_at = datetime.utcnow()
|
reputation.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Create reputation event record
|
# Create reputation event record
|
||||||
event = ReputationEvent(
|
event = ReputationEvent(
|
||||||
@@ -174,7 +174,7 @@ class CrossChainReputationEngine:
|
|||||||
trust_score_before=reputation.trust_score - (impact_score * 1000),
|
trust_score_before=reputation.trust_score - (impact_score * 1000),
|
||||||
trust_score_after=reputation.trust_score,
|
trust_score_after=reputation.trust_score,
|
||||||
event_data=event_data,
|
event_data=event_data,
|
||||||
occurred_at=datetime.utcnow(),
|
occurred_at=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(event)
|
self.session.add(event)
|
||||||
@@ -195,7 +195,7 @@ class CrossChainReputationEngine:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# Get reputation events for the period
|
# Get reputation events for the period
|
||||||
cutoff_date = datetime.utcnow() - timedelta(days=days)
|
cutoff_date = datetime.now(datetime.UTC) - timedelta(days=days)
|
||||||
|
|
||||||
stmt = (
|
stmt = (
|
||||||
select(ReputationEvent)
|
select(ReputationEvent)
|
||||||
@@ -295,7 +295,7 @@ class CrossChainReputationEngine:
|
|||||||
|
|
||||||
reputation.trust_score = new_score * 1000
|
reputation.trust_score = new_score * 1000
|
||||||
reputation.reputation_level = self._determine_reputation_level(new_score)
|
reputation.reputation_level = self._determine_reputation_level(new_score)
|
||||||
reputation.updated_at = datetime.utcnow()
|
reputation.updated_at = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
# Update transaction metrics if available
|
# Update transaction metrics if available
|
||||||
if "transaction_count" in transaction_data:
|
if "transaction_count" in transaction_data:
|
||||||
@@ -364,7 +364,7 @@ class CrossChainReputationEngine:
|
|||||||
aggregation.score_variance = variance
|
aggregation.score_variance = variance
|
||||||
aggregation.score_range = score_range
|
aggregation.score_range = score_range
|
||||||
aggregation.consistency_score = consistency_score
|
aggregation.consistency_score = consistency_score
|
||||||
aggregation.last_updated = datetime.utcnow()
|
aggregation.last_updated = datetime.now(datetime.UTC)
|
||||||
else:
|
else:
|
||||||
# Create new aggregation
|
# Create new aggregation
|
||||||
aggregation = CrossChainReputationAggregation(
|
aggregation = CrossChainReputationAggregation(
|
||||||
@@ -376,8 +376,8 @@ class CrossChainReputationEngine:
|
|||||||
score_range=score_range,
|
score_range=score_range,
|
||||||
consistency_score=consistency_score,
|
consistency_score=consistency_score,
|
||||||
verification_status="pending",
|
verification_status="pending",
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
last_updated=datetime.utcnow(),
|
last_updated=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.session.add(aggregation)
|
self.session.add(aggregation)
|
||||||
@@ -440,7 +440,7 @@ class CrossChainReputationEngine:
|
|||||||
"total_transactions": getattr(reputation, "transaction_count", 0),
|
"total_transactions": getattr(reputation, "transaction_count", 0),
|
||||||
"success_rate": getattr(reputation, "success_rate", 0.0),
|
"success_rate": getattr(reputation, "success_rate", 0.0),
|
||||||
"dispute_count": getattr(reputation, "dispute_count", 0),
|
"dispute_count": getattr(reputation, "dispute_count", 0),
|
||||||
"last_activity": getattr(reputation, "last_activity", datetime.utcnow()),
|
"last_activity": getattr(reputation, "last_activity", datetime.now(datetime.UTC)),
|
||||||
"cross_chain": {
|
"cross_chain": {
|
||||||
"aggregated_score": aggregation.aggregated_score if aggregation else 0.0,
|
"aggregated_score": aggregation.aggregated_score if aggregation else 0.0,
|
||||||
"chain_count": aggregation.chain_count if aggregation else 0,
|
"chain_count": aggregation.chain_count if aggregation else 0,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides health monitoring for reinforcement learning frameworks
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
@@ -40,7 +40,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "adaptive-learning",
|
"service": "adaptive-learning",
|
||||||
"port": 8011,
|
"port": 8011,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
# System metrics
|
# System metrics
|
||||||
"system": {
|
"system": {
|
||||||
@@ -97,7 +97,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "adaptive-learning",
|
"service": "adaptive-learning",
|
||||||
"port": 8011,
|
"port": 8011,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Health check failed",
|
"error": "Health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +177,7 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "adaptive-learning",
|
"service": "adaptive-learning",
|
||||||
"port": 8011,
|
"port": 8011,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"algorithm_tests": algorithm_tests,
|
"algorithm_tests": algorithm_tests,
|
||||||
"safety_tests": safety_tests,
|
"safety_tests": safety_tests,
|
||||||
"overall_health": (
|
"overall_health": (
|
||||||
@@ -196,6 +196,6 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "adaptive-learning",
|
"service": "adaptive-learning",
|
||||||
"port": 8011,
|
"port": 8011,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Deep health check failed",
|
"error": "Deep health check failed",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||||
@@ -55,7 +55,7 @@ async def create_test_miner(
|
|||||||
if existing_miner:
|
if existing_miner:
|
||||||
# Update existing miner to ONLINE
|
# Update existing miner to ONLINE
|
||||||
existing_miner.status = "ONLINE"
|
existing_miner.status = "ONLINE"
|
||||||
existing_miner.last_heartbeat = datetime.utcnow()
|
existing_miner.last_heartbeat = datetime.now(datetime.UTC)
|
||||||
existing_miner.session_token = session_token
|
existing_miner.session_token = session_token
|
||||||
session.add(existing_miner)
|
session.add(existing_miner)
|
||||||
session.commit()
|
session.commit()
|
||||||
@@ -79,7 +79,7 @@ async def create_test_miner(
|
|||||||
session_token=session_token,
|
session_token=session_token,
|
||||||
status="ONLINE",
|
status="ONLINE",
|
||||||
inflight=0,
|
inflight=0,
|
||||||
last_heartbeat=datetime.utcnow(),
|
last_heartbeat=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
session.add(miner)
|
session.add(miner)
|
||||||
@@ -223,7 +223,7 @@ async def get_system_status(
|
|||||||
|
|
||||||
# Get system info
|
# Get system info
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
|
|
||||||
@@ -232,7 +232,7 @@ async def get_system_status(
|
|||||||
"memory_percent": psutil.virtual_memory().percent,
|
"memory_percent": psutil.virtual_memory().percent,
|
||||||
"disk_percent": psutil.disk_usage("/").percent,
|
"disk_percent": psutil.disk_usage("/").percent,
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -275,7 +275,7 @@ async def create_agent_network(network_data: dict):
|
|||||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||||
|
|
||||||
# Create network record (simplified for now)
|
# Create network record (simplified for now)
|
||||||
network_id = f"network_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
|
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||||
|
|
||||||
network_response = {
|
network_response = {
|
||||||
"id": network_id,
|
"id": network_id,
|
||||||
@@ -284,7 +284,7 @@ async def create_agent_network(network_data: dict):
|
|||||||
"agents": network_data["agents"],
|
"agents": network_data["agents"],
|
||||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||||
"status": "active",
|
"status": "active",
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"owner_id": "temp_user",
|
"owner_id": "temp_user",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,11 +315,11 @@ async def get_execution_receipt(execution_id: str):
|
|||||||
{
|
{
|
||||||
"coordinator_id": "coordinator_1",
|
"coordinator_id": "coordinator_1",
|
||||||
"signature": "0xmock_attestation_1",
|
"signature": "0xmock_attestation_1",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"minted_amount": 1000,
|
"minted_amount": 1000,
|
||||||
"recorded_at": datetime.utcnow().isoformat(),
|
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"verified": True,
|
"verified": True,
|
||||||
"block_hash": "0xmock_block_hash",
|
"block_hash": "0xmock_block_hash",
|
||||||
"transaction_hash": "0xmock_tx_hash",
|
"transaction_hash": "0xmock_tx_hash",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Agent Identity API Router
|
|||||||
REST API endpoints for agent identity management and cross-chain operations
|
REST API endpoints for agent identity management and cross-chain operations
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -85,7 +85,7 @@ async def deactivate_agent_identity(
|
|||||||
success = await manager.deactivate_agent_identity(agent_id, reason)
|
success = await manager.deactivate_agent_identity(agent_id, reason)
|
||||||
if not success:
|
if not success:
|
||||||
raise HTTPException(status_code=400, detail="Deactivation failed")
|
raise HTTPException(status_code=400, detail="Deactivation failed")
|
||||||
return {"agent_id": agent_id, "deactivated": True, "reason": reason, "timestamp": datetime.utcnow().isoformat()}
|
return {"agent_id": agent_id, "deactivated": True, "reason": reason, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -164,7 +164,7 @@ async def update_cross_chain_mapping(
|
|||||||
"chain_id": chain_id,
|
"chain_id": chain_id,
|
||||||
"new_address": new_address,
|
"new_address": new_address,
|
||||||
"updated": True,
|
"updated": True,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
@@ -255,7 +255,7 @@ async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentit
|
|||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"chain_id": chain_id,
|
"chain_id": chain_id,
|
||||||
"balance": str(balance),
|
"balance": str(balance),
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(status_code=400, detail="Failed to create agent identity")
|
raise HTTPException(status_code=400, detail="Failed to create agent identity")
|
||||||
@@ -427,7 +427,7 @@ async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(
|
|||||||
"""Clean up expired verification records"""
|
"""Clean up expired verification records"""
|
||||||
try:
|
try:
|
||||||
cleaned_count = await manager.registry.cleanup_expired_verifications()
|
cleaned_count = await manager.registry.cleanup_expired_verifications()
|
||||||
return {"cleaned_verifications": cleaned_count, "timestamp": datetime.utcnow().isoformat()}
|
return {"cleaned_verifications": cleaned_count, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(status_code=500, detail="Operation failed")
|
raise HTTPException(status_code=500, detail="Operation failed")
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Advanced Agent Performance API Endpoints
|
|||||||
REST API for meta-learning, resource optimization, and performance enhancement
|
REST API for meta-learning, resource optimization, and performance enhancement
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -319,7 +319,7 @@ async def adapt_model_to_task(
|
|||||||
"success": True,
|
"success": True,
|
||||||
"model_id": model_id,
|
"model_id": model_id,
|
||||||
"adaptation_results": results,
|
"adaptation_results": results,
|
||||||
"adapted_at": datetime.utcnow().isoformat(),
|
"adapted_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
@@ -554,7 +554,7 @@ async def create_capability(
|
|||||||
skill_level=capability_request.skill_level,
|
skill_level=capability_request.skill_level,
|
||||||
specialization_areas=capability_request.specialization_areas,
|
specialization_areas=capability_request.specialization_areas,
|
||||||
proficiency_score=min(1.0, capability_request.skill_level / 10.0),
|
proficiency_score=min(1.0, capability_request.skill_level / 10.0),
|
||||||
created_at=datetime.utcnow(),
|
created_at=datetime.now(datetime.UTC),
|
||||||
)
|
)
|
||||||
|
|
||||||
session.add(capability)
|
session.add(capability)
|
||||||
@@ -718,7 +718,7 @@ async def health_check() -> Dict[str, Any]:
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"services": {
|
"services": {
|
||||||
"meta_learning_engine": "operational",
|
"meta_learning_engine": "operational",
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ AI Agent API Router for Verifiable AI Agent Orchestration
|
|||||||
Provides REST API endpoints for agent workflow management and execution
|
Provides REST API endpoints for agent workflow management and execution
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||||
|
|
||||||
@@ -141,7 +141,7 @@ async def update_workflow(
|
|||||||
for field, value in update_data.items():
|
for field, value in update_data.items():
|
||||||
setattr(workflow, field, value)
|
setattr(workflow, field, value)
|
||||||
|
|
||||||
workflow.updated_at = datetime.utcnow()
|
workflow.updated_at = datetime.now(datetime.UTC)
|
||||||
session.commit()
|
session.commit()
|
||||||
session.refresh(workflow)
|
session.refresh(workflow)
|
||||||
|
|
||||||
@@ -351,7 +351,7 @@ async def cancel_execution(
|
|||||||
|
|
||||||
# Cancel execution
|
# Cancel execution
|
||||||
state_manager = AgentStateManager(session)
|
state_manager = AgentStateManager(session)
|
||||||
await state_manager.update_execution_status(execution_id, status=AgentStatus.CANCELLED, completed_at=datetime.utcnow())
|
await state_manager.update_execution_status(execution_id, status=AgentStatus.CANCELLED, completed_at=datetime.now(datetime.UTC))
|
||||||
|
|
||||||
logger.info(f"Cancelled agent execution: {execution_id}")
|
logger.info(f"Cancelled agent execution: {execution_id}")
|
||||||
return {"message": "Execution cancelled successfully"}
|
return {"message": "Execution cancelled successfully"}
|
||||||
@@ -424,7 +424,7 @@ async def get_execution_logs(
|
|||||||
@router.get("/test")
|
@router.get("/test")
|
||||||
async def test_endpoint():
|
async def test_endpoint():
|
||||||
"""Test endpoint to verify router is working"""
|
"""Test endpoint to verify router is working"""
|
||||||
return {"message": "Agent router is working", "timestamp": datetime.utcnow().isoformat()}
|
return {"message": "Agent router is working", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/networks", response_model=dict, status_code=201)
|
@router.post("/networks", response_model=dict, status_code=201)
|
||||||
@@ -444,7 +444,7 @@ async def create_agent_network(
|
|||||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||||
|
|
||||||
# Create network record (simplified for now)
|
# Create network record (simplified for now)
|
||||||
network_id = f"network_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
|
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||||
|
|
||||||
network_response = {
|
network_response = {
|
||||||
"id": network_id,
|
"id": network_id,
|
||||||
@@ -453,7 +453,7 @@ async def create_agent_network(
|
|||||||
"agents": network_data["agents"],
|
"agents": network_data["agents"],
|
||||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||||
"status": "active",
|
"status": "active",
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"owner_id": current_user,
|
"owner_id": current_user,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -487,11 +487,11 @@ async def get_execution_receipt(
|
|||||||
{
|
{
|
||||||
"coordinator_id": "coordinator_1",
|
"coordinator_id": "coordinator_1",
|
||||||
"signature": "0xmock_attestation_1",
|
"signature": "0xmock_attestation_1",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"minted_amount": 1000,
|
"minted_amount": 1000,
|
||||||
"recorded_at": datetime.utcnow().isoformat(),
|
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"verified": True,
|
"verified": True,
|
||||||
"block_hash": "0xmock_block_hash",
|
"block_hash": "0xmock_block_hash",
|
||||||
"transaction_hash": "0xmock_tx_hash",
|
"transaction_hash": "0xmock_tx_hash",
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ async def update_security_policy(
|
|||||||
if hasattr(policy, field):
|
if hasattr(policy, field):
|
||||||
setattr(policy, field, value)
|
setattr(policy, field, value)
|
||||||
|
|
||||||
policy.updated_at = datetime.utcnow()
|
policy.updated_at = datetime.now(datetime.UTC)
|
||||||
session.commit()
|
session.commit()
|
||||||
session.refresh(policy)
|
session.refresh(policy)
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Marketplace Analytics API Endpoints
|
|||||||
REST API for analytics, insights, reporting, and dashboards
|
REST API for analytics, insights, reporting, and dashboards
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -552,7 +552,7 @@ async def get_key_performance_indicators(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# Get latest metrics for KPIs
|
# Get latest metrics for KPIs
|
||||||
end_time = datetime.utcnow()
|
end_time = datetime.now(datetime.UTC)
|
||||||
|
|
||||||
if period_type == AnalyticsPeriod.DAILY:
|
if period_type == AnalyticsPeriod.DAILY:
|
||||||
start_time = end_time - timedelta(days=1)
|
start_time = end_time - timedelta(days=1)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Bounty Management API
|
|||||||
REST API for AI agent bounty system with ZK-proof verification
|
REST API for AI agent bounty system with ZK-proof verification
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||||
@@ -38,7 +38,7 @@ class BountyCreateRequest(BaseModel):
|
|||||||
performance_criteria: Dict[str, Any] = Field(default_factory=dict)
|
performance_criteria: Dict[str, Any] = Field(default_factory=dict)
|
||||||
min_accuracy: float = Field(default=90.0, ge=0, le=100)
|
min_accuracy: float = Field(default=90.0, ge=0, le=100)
|
||||||
max_response_time: Optional[int] = Field(default=None, gt=0)
|
max_response_time: Optional[int] = Field(default=None, gt=0)
|
||||||
deadline: datetime = Field(..., gt=datetime.utcnow())
|
deadline: datetime = Field(..., gt=datetime.now(datetime.UTC))
|
||||||
max_submissions: int = Field(default=100, gt=0, le=1000)
|
max_submissions: int = Field(default=100, gt=0, le=1000)
|
||||||
requires_zk_proof: bool = Field(default=True)
|
requires_zk_proof: bool = Field(default=True)
|
||||||
auto_verify_threshold: float = Field(default=95.0, ge=0, le=100)
|
auto_verify_threshold: float = Field(default=95.0, ge=0, le=100)
|
||||||
@@ -48,9 +48,9 @@ class BountyCreateRequest(BaseModel):
|
|||||||
|
|
||||||
@validator('deadline')
|
@validator('deadline')
|
||||||
def validate_deadline(cls, v):
|
def validate_deadline(cls, v):
|
||||||
if v <= datetime.utcnow():
|
if v <= datetime.now(datetime.UTC):
|
||||||
raise ValueError('Deadline must be in the future')
|
raise ValueError('Deadline must be in the future')
|
||||||
if v > datetime.utcnow() + timedelta(days=365):
|
if v > datetime.now(datetime.UTC) + timedelta(days=365):
|
||||||
raise ValueError('Deadline cannot be more than 1 year in the future')
|
raise ValueError('Deadline cannot be more than 1 year in the future')
|
||||||
return v
|
return v
|
||||||
|
|
||||||
@@ -281,7 +281,7 @@ async def submit_bounty_solution(
|
|||||||
if bounty.status != BountyStatus.ACTIVE:
|
if bounty.status != BountyStatus.ACTIVE:
|
||||||
raise HTTPException(status_code=400, detail="Bounty is not active")
|
raise HTTPException(status_code=400, detail="Bounty is not active")
|
||||||
|
|
||||||
if datetime.utcnow() > bounty.deadline:
|
if datetime.now(datetime.UTC) > bounty.deadline:
|
||||||
raise HTTPException(status_code=400, detail="Bounty deadline has passed")
|
raise HTTPException(status_code=400, detail="Bounty deadline has passed")
|
||||||
|
|
||||||
# Create submission
|
# Create submission
|
||||||
@@ -519,7 +519,7 @@ async def expire_bounty(
|
|||||||
if bounty.status != BountyStatus.ACTIVE:
|
if bounty.status != BountyStatus.ACTIVE:
|
||||||
raise HTTPException(status_code=400, detail="Bounty is not active")
|
raise HTTPException(status_code=400, detail="Bounty is not active")
|
||||||
|
|
||||||
if datetime.utcnow() <= bounty.deadline:
|
if datetime.now(datetime.UTC) <= bounty.deadline:
|
||||||
raise HTTPException(status_code=400, detail="Bounty deadline has not passed")
|
raise HTTPException(status_code=400, detail="Bounty deadline has not passed")
|
||||||
|
|
||||||
# Expire bounty
|
# Expire bounty
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Certification and Partnership API Endpoints
|
|||||||
REST API for agent certification, partnership programs, and badge system
|
REST API for agent certification, partnership programs, and badge system
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -626,7 +626,7 @@ async def check_automatic_badges(
|
|||||||
"agent_id": agent_id,
|
"agent_id": agent_id,
|
||||||
"badges_awarded": awarded_badges,
|
"badges_awarded": awarded_badges,
|
||||||
"total_awarded": len(awarded_badges),
|
"total_awarded": len(awarded_badges),
|
||||||
"checked_at": datetime.utcnow().isoformat()
|
"checked_at": datetime.now(datetime.UTC).isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||||
@@ -265,7 +265,7 @@ async def create_agent_network(network_data: dict):
|
|||||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||||
|
|
||||||
# Create network record (simplified for now)
|
# Create network record (simplified for now)
|
||||||
network_id = f"network_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
|
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||||
|
|
||||||
network_response = {
|
network_response = {
|
||||||
"id": network_id,
|
"id": network_id,
|
||||||
@@ -274,7 +274,7 @@ async def create_agent_network(network_data: dict):
|
|||||||
"agents": network_data["agents"],
|
"agents": network_data["agents"],
|
||||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||||
"status": "active",
|
"status": "active",
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"owner_id": "temp_user",
|
"owner_id": "temp_user",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,11 +302,11 @@ async def get_execution_receipt(execution_id: str):
|
|||||||
{
|
{
|
||||||
"coordinator_id": "coordinator_1",
|
"coordinator_id": "coordinator_1",
|
||||||
"signature": "0xmock_attestation_1",
|
"signature": "0xmock_attestation_1",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"minted_amount": 1000,
|
"minted_amount": 1000,
|
||||||
"recorded_at": datetime.utcnow().isoformat(),
|
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"verified": True,
|
"verified": True,
|
||||||
"block_hash": "0xmock_block_hash",
|
"block_hash": "0xmock_block_hash",
|
||||||
"transaction_hash": "0xmock_tx_hash",
|
"transaction_hash": "0xmock_tx_hash",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
API endpoints for confidential transactions
|
API endpoints for confidential transactions
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from fastapi.security import HTTPBearer
|
from fastapi.security import HTTPBearer
|
||||||
@@ -78,13 +78,13 @@ async def create_confidential_transaction(request: ConfidentialTransactionCreate
|
|||||||
"""Create a new confidential transaction with optional encryption"""
|
"""Create a new confidential transaction with optional encryption"""
|
||||||
try:
|
try:
|
||||||
# Generate transaction ID
|
# Generate transaction ID
|
||||||
transaction_id = f"ctx-{datetime.utcnow().timestamp()}"
|
transaction_id = f"ctx-{datetime.now(datetime.UTC).timestamp()}"
|
||||||
|
|
||||||
# Create base transaction
|
# Create base transaction
|
||||||
transaction = ConfidentialTransaction(
|
transaction = ConfidentialTransaction(
|
||||||
transaction_id=transaction_id,
|
transaction_id=transaction_id,
|
||||||
job_id=request.job_id,
|
job_id=request.job_id,
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
status="created",
|
status="created",
|
||||||
amount=request.amount,
|
amount=request.amount,
|
||||||
pricing=request.pricing,
|
pricing=request.pricing,
|
||||||
@@ -173,7 +173,7 @@ async def access_confidential_data(
|
|||||||
transaction = ConfidentialTransaction(
|
transaction = ConfidentialTransaction(
|
||||||
transaction_id=transaction_id,
|
transaction_id=transaction_id,
|
||||||
job_id="test-job",
|
job_id="test-job",
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
status="completed",
|
status="completed",
|
||||||
confidential=True,
|
confidential=True,
|
||||||
participants=["client-456", "miner-789"],
|
participants=["client-456", "miner-789"],
|
||||||
@@ -200,7 +200,7 @@ async def access_confidential_data(
|
|||||||
return ConfidentialAccessResponse(
|
return ConfidentialAccessResponse(
|
||||||
success=True,
|
success=True,
|
||||||
data={"amount": "1000", "pricing": {"rate": "0.1"}},
|
data={"amount": "1000", "pricing": {"rate": "0.1"}},
|
||||||
access_id=f"access-{datetime.utcnow().timestamp()}",
|
access_id=f"access-{datetime.now(datetime.UTC).timestamp()}",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Decrypt data
|
# Decrypt data
|
||||||
@@ -225,7 +225,7 @@ async def access_confidential_data(
|
|||||||
)
|
)
|
||||||
|
|
||||||
return ConfidentialAccessResponse(
|
return ConfidentialAccessResponse(
|
||||||
success=True, data=decrypted_data, access_id=f"access-{datetime.utcnow().timestamp()}"
|
success=True, data=decrypted_data, access_id=f"access-{datetime.now(datetime.UTC).timestamp()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -249,7 +249,7 @@ async def audit_access_confidential_data(
|
|||||||
transaction = ConfidentialTransaction(
|
transaction = ConfidentialTransaction(
|
||||||
transaction_id=transaction_id,
|
transaction_id=transaction_id,
|
||||||
job_id="test-job",
|
job_id="test-job",
|
||||||
timestamp=datetime.utcnow(),
|
timestamp=datetime.now(datetime.UTC),
|
||||||
status="completed",
|
status="completed",
|
||||||
confidential=True,
|
confidential=True,
|
||||||
)
|
)
|
||||||
@@ -278,7 +278,7 @@ async def audit_access_confidential_data(
|
|||||||
)
|
)
|
||||||
|
|
||||||
return ConfidentialAccessResponse(
|
return ConfidentialAccessResponse(
|
||||||
success=True, data=decrypted_data, access_id=f"audit-{datetime.utcnow().timestamp()}"
|
success=True, data=decrypted_data, access_id=f"audit-{datetime.now(datetime.UTC).timestamp()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -308,7 +308,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
|
|||||||
success=True,
|
success=True,
|
||||||
participant_id=request.participant_id,
|
participant_id=request.participant_id,
|
||||||
key_version=1, # Would get from storage
|
key_version=1, # Would get from storage
|
||||||
registered_at=datetime.utcnow(),
|
registered_at=datetime.now(datetime.UTC),
|
||||||
error=None,
|
error=None,
|
||||||
)
|
)
|
||||||
except:
|
except:
|
||||||
@@ -328,7 +328,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
|
|||||||
except KeyManagementError as e:
|
except KeyManagementError as e:
|
||||||
logger.error(f"Key registration failed: {e}")
|
logger.error(f"Key registration failed: {e}")
|
||||||
return KeyRegistrationResponse(
|
return KeyRegistrationResponse(
|
||||||
success=False, participant_id=request.participant_id, key_version=0, registered_at=datetime.utcnow(), error=str(e)
|
success=False, participant_id=request.participant_id, key_version=0, registered_at=datetime.now(datetime.UTC), error=str(e)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to register key: {e}")
|
logger.error(f"Failed to register key: {e}")
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Cross-Chain Integration API Router
|
|||||||
REST API endpoints for enhanced multi-chain wallet adapter, cross-chain bridge service, and transaction manager
|
REST API endpoints for enhanced multi-chain wallet adapter, cross-chain bridge service, and transaction manager
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -217,7 +217,7 @@ async def verify_signature(
|
|||||||
"message": message,
|
"message": message,
|
||||||
"address": address,
|
"address": address,
|
||||||
"chain_id": chain_id,
|
"chain_id": chain_id,
|
||||||
"verified_at": datetime.utcnow().isoformat(),
|
"verified_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -606,7 +606,7 @@ async def get_cross_chain_health(session: Session = Depends(get_session)) -> dic
|
|||||||
"transaction_success_rate": tx_stats["success_rate"],
|
"transaction_success_rate": tx_stats["success_rate"],
|
||||||
"average_processing_time": tx_stats["average_processing_time_minutes"],
|
"average_processing_time": tx_stats["average_processing_time_minutes"],
|
||||||
"active_liquidity_pools": len(await bridge_service.get_liquidity_pools()),
|
"active_liquidity_pools": len(await bridge_service.get_liquidity_pools()),
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -675,7 +675,7 @@ async def get_cross_chain_config(session: Session = Depends(get_session)) -> dic
|
|||||||
"transaction_priorities": transaction_priorities,
|
"transaction_priorities": transaction_priorities,
|
||||||
"routing_strategies": routing_strategies,
|
"routing_strategies": routing_strategies,
|
||||||
"security_levels": [level.value for level in SecurityLevel],
|
"security_levels": [level.value for level in SecurityLevel],
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Developer Platform API Router
|
|||||||
REST API endpoints for the developer ecosystem including bounties, certifications, and regional hubs
|
REST API endpoints for the developer ecosystem including bounties, certifications, and regional hubs
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -440,7 +440,7 @@ async def verify_certification(certification_id: str, session: Session = Depends
|
|||||||
"issued_by": certification.issued_by,
|
"issued_by": certification.issued_by,
|
||||||
"granted_at": certification.granted_at.isoformat(),
|
"granted_at": certification.granted_at.isoformat(),
|
||||||
"is_valid": True,
|
"is_valid": True,
|
||||||
"verification_timestamp": datetime.utcnow().isoformat(),
|
"verification_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
@@ -746,7 +746,7 @@ async def get_platform_overview(
|
|||||||
"regions_covered": 12, # Mock data
|
"regions_covered": 12, # Mock data
|
||||||
},
|
},
|
||||||
"staking": {"total_staked": 1000000.0, "active_stakers": 500, "average_apy": 7.5}, # Mock data
|
"staking": {"total_staked": 1000000.0, "active_stakers": 500, "average_apy": 7.5}, # Mock data
|
||||||
"generated_at": datetime.utcnow().isoformat(),
|
"generated_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -785,7 +785,7 @@ async def get_platform_health(session: Session = Depends(get_session)) -> dict[s
|
|||||||
"pending_submissions": 8, # Mock data
|
"pending_submissions": 8, # Mock data
|
||||||
"system_uptime": "99.9%",
|
"system_uptime": "99.9%",
|
||||||
},
|
},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Dynamic Pricing API Router
|
|||||||
Provides RESTful endpoints for dynamic pricing management
|
Provides RESTful endpoints for dynamic pricing management
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -147,7 +147,7 @@ async def get_price_forecast(
|
|||||||
accuracy_score=(
|
accuracy_score=(
|
||||||
sum(point.confidence for point in forecast_points) / len(forecast_points) if forecast_points else 0.0
|
sum(point.confidence for point in forecast_points) / len(forecast_points) if forecast_points else 0.0
|
||||||
),
|
),
|
||||||
generated_at=datetime.utcnow().isoformat(),
|
generated_at=datetime.now(datetime.UTC).isoformat(),
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -197,7 +197,7 @@ async def set_pricing_strategy(
|
|||||||
provider_id=provider_id,
|
provider_id=provider_id,
|
||||||
strategy=request.strategy,
|
strategy=request.strategy,
|
||||||
constraints=request.constraints,
|
constraints=request.constraints,
|
||||||
set_at=datetime.utcnow().isoformat(),
|
set_at=datetime.now(datetime.UTC).isoformat(),
|
||||||
status="active",
|
status="active",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -239,7 +239,7 @@ async def get_pricing_strategy(
|
|||||||
provider_id=provider_id,
|
provider_id=provider_id,
|
||||||
strategy=strategy.value,
|
strategy=strategy.value,
|
||||||
constraints=constraints_dict,
|
constraints=constraints_dict,
|
||||||
set_at=datetime.utcnow().isoformat(),
|
set_at=datetime.now(datetime.UTC).isoformat(),
|
||||||
status="active",
|
status="active",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -531,7 +531,7 @@ async def get_price_history(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Filter history by period
|
# Filter history by period
|
||||||
cutoff_time = datetime.utcnow() - timedelta(days=days)
|
cutoff_time = datetime.now(datetime.UTC) - timedelta(days=days)
|
||||||
filtered_history = [point for point in engine.pricing_history[resource_id] if point.timestamp >= cutoff_time]
|
filtered_history = [point for point in engine.pricing_history[resource_id] if point.timestamp >= cutoff_time]
|
||||||
|
|
||||||
# Calculate statistics
|
# Calculate statistics
|
||||||
@@ -637,7 +637,7 @@ async def bulk_pricing_update(
|
|||||||
success_count=success_count,
|
success_count=success_count,
|
||||||
error_count=error_count,
|
error_count=error_count,
|
||||||
results=results,
|
results=results,
|
||||||
processed_at=datetime.utcnow().isoformat(),
|
processed_at=datetime.now(datetime.UTC).isoformat(),
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -691,7 +691,7 @@ async def pricing_health_check(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"status": overall_status,
|
"status": overall_status,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"services": {
|
"services": {
|
||||||
"pricing_engine": {
|
"pricing_engine": {
|
||||||
"status": engine_status,
|
"status": engine_status,
|
||||||
@@ -710,4 +710,4 @@ async def pricing_health_check(
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Dynamic pricing health check failed: {e}")
|
logger.error(f"Dynamic pricing health check failed: {e}")
|
||||||
return {"status": "unhealthy", "timestamp": datetime.utcnow().isoformat(), "error": "Health check failed"}
|
return {"status": "unhealthy", "timestamp": datetime.now(datetime.UTC).isoformat(), "error": "Health check failed"}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Ecosystem Metrics Dashboard API
|
|||||||
REST API for developer ecosystem metrics and analytics
|
REST API for developer ecosystem metrics and analytics
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
@@ -345,7 +345,7 @@ async def get_ecosystem_alerts(
|
|||||||
"alerts": alerts,
|
"alerts": alerts,
|
||||||
"severity": severity,
|
"severity": severity,
|
||||||
"count": len(alerts),
|
"count": len(alerts),
|
||||||
"last_updated": datetime.utcnow()
|
"last_updated": datetime.now(datetime.UTC)
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -422,7 +422,7 @@ async def get_real_time_metrics(
|
|||||||
real_time_data = await ecosystem_service.get_real_time_metrics()
|
real_time_data = await ecosystem_service.get_real_time_metrics()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"timestamp": datetime.utcnow(),
|
"timestamp": datetime.now(datetime.UTC),
|
||||||
"metrics": real_time_data,
|
"metrics": real_time_data,
|
||||||
"update_frequency": "60s" # Update frequency in seconds
|
"update_frequency": "60s" # Update frequency in seconds
|
||||||
}
|
}
|
||||||
@@ -442,7 +442,7 @@ async def get_kpi_dashboard(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"kpis": kpi_data,
|
"kpis": kpi_data,
|
||||||
"last_updated": datetime.utcnow(),
|
"last_updated": datetime.now(datetime.UTC),
|
||||||
"refresh_interval": 300 # 5 minutes
|
"refresh_interval": 300 # 5 minutes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Bitcoin Exchange Router for AITBC
|
|||||||
|
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
|
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
|
||||||
@@ -214,7 +214,7 @@ async def monitor_payment(payment_id: str):
|
|||||||
@router.get("/agents/test")
|
@router.get("/agents/test")
|
||||||
async def test_agent_endpoint():
|
async def test_agent_endpoint():
|
||||||
"""Test endpoint to verify agent routes are working"""
|
"""Test endpoint to verify agent routes are working"""
|
||||||
return {"message": "Agent routes are working", "timestamp": datetime.utcnow().isoformat()}
|
return {"message": "Agent routes are working", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/agents/networks", response_model=dict, status_code=201)
|
@router.post("/agents/networks", response_model=dict, status_code=201)
|
||||||
@@ -230,7 +230,7 @@ async def create_agent_network(network_data: dict):
|
|||||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||||
|
|
||||||
# Create network record (simplified for now)
|
# Create network record (simplified for now)
|
||||||
network_id = f"network_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
|
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||||
|
|
||||||
network_response = {
|
network_response = {
|
||||||
"id": network_id,
|
"id": network_id,
|
||||||
@@ -239,7 +239,7 @@ async def create_agent_network(network_data: dict):
|
|||||||
"agents": network_data["agents"],
|
"agents": network_data["agents"],
|
||||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||||
"status": "active",
|
"status": "active",
|
||||||
"created_at": datetime.utcnow().isoformat(),
|
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"owner_id": "temp_user",
|
"owner_id": "temp_user",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,11 +269,11 @@ async def get_execution_receipt(execution_id: str):
|
|||||||
{
|
{
|
||||||
"coordinator_id": "coordinator_1",
|
"coordinator_id": "coordinator_1",
|
||||||
"signature": "0xmock_attestation_1",
|
"signature": "0xmock_attestation_1",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"minted_amount": 1000,
|
"minted_amount": 1000,
|
||||||
"recorded_at": datetime.utcnow().isoformat(),
|
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
"verified": True,
|
"verified": True,
|
||||||
"block_hash": "0xmock_block_hash",
|
"block_hash": "0xmock_block_hash",
|
||||||
"transaction_hash": "0xmock_tx_hash",
|
"transaction_hash": "0xmock_tx_hash",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Global Marketplace API Router
|
|||||||
REST API endpoints for global marketplace operations, multi-region support, and cross-chain integration
|
REST API endpoints for global marketplace operations, multi-region support, and cross-chain integration
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||||
@@ -585,7 +585,7 @@ async def get_global_marketplace_health(
|
|||||||
recent_transactions = (
|
recent_transactions = (
|
||||||
session.execute(
|
session.execute(
|
||||||
select(func.count(GlobalMarketplaceTransaction.id)).where(
|
select(func.count(GlobalMarketplaceTransaction.id)).where(
|
||||||
GlobalMarketplaceTransaction.created_at >= datetime.utcnow() - timedelta(hours=24)
|
GlobalMarketplaceTransaction.created_at >= datetime.now(datetime.UTC) - timedelta(hours=24)
|
||||||
)
|
)
|
||||||
).scalar()
|
).scalar()
|
||||||
or 0
|
or 0
|
||||||
@@ -608,7 +608,7 @@ async def get_global_marketplace_health(
|
|||||||
"recent_24h": recent_transactions,
|
"recent_24h": recent_transactions,
|
||||||
"activity_rate": transaction_activity,
|
"activity_rate": transaction_activity,
|
||||||
},
|
},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Global Marketplace Integration API Router
|
|||||||
REST API endpoints for integrated global marketplace with cross-chain capabilities
|
REST API endpoints for integrated global marketplace with cross-chain capabilities
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -350,7 +350,7 @@ async def get_marketplace_integration_analytics(
|
|||||||
"active_regions": len(active_regions),
|
"active_regions": len(active_regions),
|
||||||
"supported_chains": len(supported_chains),
|
"supported_chains": len(supported_chains),
|
||||||
"integration_config": integration_service.integration_config,
|
"integration_config": integration_service.integration_config,
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -394,7 +394,7 @@ async def get_integration_status(
|
|||||||
"auto_bridge_execution": config["auto_bridge_execution"],
|
"auto_bridge_execution": config["auto_bridge_execution"],
|
||||||
"multi_chain_wallet_support": config["multi_chain_wallet_support"],
|
"multi_chain_wallet_support": config["multi_chain_wallet_support"],
|
||||||
},
|
},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -463,7 +463,7 @@ async def get_integration_config(
|
|||||||
}
|
}
|
||||||
for priority in TransactionPriority
|
for priority in TransactionPriority
|
||||||
},
|
},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -492,7 +492,7 @@ async def update_integration_config(
|
|||||||
return {
|
return {
|
||||||
"updated_config": integration_service.integration_config,
|
"updated_config": integration_service.integration_config,
|
||||||
"updated_keys": list(config_updates.keys()),
|
"updated_keys": list(config_updates.keys()),
|
||||||
"updated_at": datetime.utcnow().isoformat(),
|
"updated_at": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
@@ -554,7 +554,7 @@ async def get_integration_health(
|
|||||||
if health_status["issues"]:
|
if health_status["issues"]:
|
||||||
health_status["overall_status"] = "degraded"
|
health_status["overall_status"] = "degraded"
|
||||||
|
|
||||||
health_status["last_updated"] = datetime.utcnow().isoformat()
|
health_status["last_updated"] = datetime.now(datetime.UTC).isoformat()
|
||||||
|
|
||||||
return health_status
|
return health_status
|
||||||
|
|
||||||
@@ -571,7 +571,7 @@ async def run_integration_diagnostics(
|
|||||||
"""Run integration diagnostics"""
|
"""Run integration diagnostics"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
diagnostics = {"diagnostic_type": diagnostic_type, "started_at": datetime.utcnow().isoformat(), "results": {}}
|
diagnostics = {"diagnostic_type": diagnostic_type, "started_at": datetime.now(datetime.UTC).isoformat(), "results": {}}
|
||||||
|
|
||||||
if diagnostic_type == "full" or diagnostic_type == "services":
|
if diagnostic_type == "full" or diagnostic_type == "services":
|
||||||
# Test services
|
# Test services
|
||||||
@@ -617,9 +617,9 @@ async def run_integration_diagnostics(
|
|||||||
"configuration": integration_service.integration_config,
|
"configuration": integration_service.integration_config,
|
||||||
}
|
}
|
||||||
|
|
||||||
diagnostics["completed_at"] = datetime.utcnow().isoformat()
|
diagnostics["completed_at"] = datetime.now(datetime.UTC).isoformat()
|
||||||
diagnostics["duration_seconds"] = (
|
diagnostics["duration_seconds"] = (
|
||||||
datetime.utcnow() - datetime.fromisoformat(diagnostics["started_at"])
|
datetime.now(datetime.UTC) - datetime.fromisoformat(diagnostics["started_at"])
|
||||||
).total_seconds()
|
).total_seconds()
|
||||||
|
|
||||||
return diagnostics
|
return diagnostics
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Enhanced Governance API Router
|
|||||||
REST API endpoints for multi-jurisdictional DAO governance, regional councils, treasury management, and staking
|
REST API endpoints for multi-jurisdictional DAO governance, regional councils, treasury management, and staking
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
@@ -433,7 +433,7 @@ async def check_compliance_status(
|
|||||||
"jurisdiction": jurisdiction,
|
"jurisdiction": jurisdiction,
|
||||||
"is_compliant": True,
|
"is_compliant": True,
|
||||||
"compliance_level": "full",
|
"compliance_level": "full",
|
||||||
"last_check": datetime.utcnow().isoformat(),
|
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||||
"requirements_met": {
|
"requirements_met": {
|
||||||
"kyc_verified": True,
|
"kyc_verified": True,
|
||||||
"aml_screened": True,
|
"aml_screened": True,
|
||||||
@@ -441,7 +441,7 @@ async def check_compliance_status(
|
|||||||
"minimum_stake_met": True,
|
"minimum_stake_met": True,
|
||||||
},
|
},
|
||||||
"restrictions": [],
|
"restrictions": [],
|
||||||
"next_review_date": (datetime.utcnow() + timedelta(days=365)).isoformat(),
|
"next_review_date": (datetime.now(datetime.UTC) + timedelta(days=365)).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return compliance_status
|
return compliance_status
|
||||||
@@ -490,7 +490,7 @@ async def get_governance_system_health(
|
|||||||
"treasury_balance": analytics["treasury"]["total_allocations"],
|
"treasury_balance": analytics["treasury"]["total_allocations"],
|
||||||
"staking_pools": analytics["staking"]["active_pools"],
|
"staking_pools": analytics["staking"]["active_pools"],
|
||||||
},
|
},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return health_data
|
return health_data
|
||||||
@@ -539,7 +539,7 @@ async def get_governance_platform_status(
|
|||||||
"treasury_utilization": f"{analytics['treasury']['utilization_rate']}%",
|
"treasury_utilization": f"{analytics['treasury']['utilization_rate']}%",
|
||||||
"staking_apy": f"{analytics['staking']['average_apy']}%",
|
"staking_apy": f"{analytics['staking']['average_apy']}%",
|
||||||
},
|
},
|
||||||
"last_updated": datetime.utcnow().isoformat(),
|
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return status_data
|
return status_data
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Provides health monitoring for CUDA-optimized multi-modal processing
|
|||||||
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
@@ -37,7 +37,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
|
|||||||
"status": "healthy" if gpu_info["available"] else "degraded",
|
"status": "healthy" if gpu_info["available"] else "degraded",
|
||||||
"service": "gpu-multimodal",
|
"service": "gpu-multimodal",
|
||||||
"port": 8010,
|
"port": 8010,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
# System metrics
|
# System metrics
|
||||||
"system": {
|
"system": {
|
||||||
@@ -86,7 +86,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "gpu-multimodal",
|
"service": "gpu-multimodal",
|
||||||
"port": 8010,
|
"port": 8010,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Health check failed",
|
"error": "Health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,7 +145,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
|
|||||||
"status": "healthy" if gpu_info["available"] else "degraded",
|
"status": "healthy" if gpu_info["available"] else "degraded",
|
||||||
"service": "gpu-multimodal",
|
"service": "gpu-multimodal",
|
||||||
"port": 8010,
|
"port": 8010,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"gpu_info": gpu_info,
|
"gpu_info": gpu_info,
|
||||||
"cuda_tests": cuda_tests,
|
"cuda_tests": cuda_tests,
|
||||||
"overall_health": (
|
"overall_health": (
|
||||||
@@ -161,7 +161,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "gpu-multimodal",
|
"service": "gpu-multimodal",
|
||||||
"port": 8010,
|
"port": 8010,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Deep health check failed",
|
"error": "Deep health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides health monitoring for royalties, licensing, verification, and analytics
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
@@ -41,7 +41,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "marketplace-enhanced",
|
"service": "marketplace-enhanced",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
# System metrics
|
# System metrics
|
||||||
"system": {
|
"system": {
|
||||||
@@ -98,7 +98,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "marketplace-enhanced",
|
"service": "marketplace-enhanced",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Health check failed",
|
"error": "Health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,7 +173,7 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "marketplace-enhanced",
|
"service": "marketplace-enhanced",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"feature_tests": feature_tests,
|
"feature_tests": feature_tests,
|
||||||
"overall_health": "pass" if all(test.get("status") == "pass" for test in feature_tests.values()) else "degraded",
|
"overall_health": "pass" if all(test.get("status") == "pass" for test in feature_tests.values()) else "degraded",
|
||||||
}
|
}
|
||||||
@@ -184,6 +184,6 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "marketplace-enhanced",
|
"service": "marketplace-enhanced",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Deep health check failed",
|
"error": "Deep health check failed",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ GPU marketplace endpoints backed by persistent SQLModel tables.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import statistics
|
import statistics
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -157,7 +157,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
|
|||||||
|
|
||||||
# Create GPU registry record
|
# Create GPU registry record
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
gpu_id = f"gpu_{uuid.uuid4().hex[:8]}"
|
gpu_id = f"gpu_{uuid.uuid4().hex[:8]}"
|
||||||
|
|
||||||
@@ -180,7 +180,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
|
|||||||
capabilities=[],
|
capabilities=[],
|
||||||
average_rating=0.0,
|
average_rating=0.0,
|
||||||
total_reviews=0,
|
total_reviews=0,
|
||||||
created_at=datetime.utcnow()
|
created_at=datetime.now(datetime.UTC)
|
||||||
)
|
)
|
||||||
|
|
||||||
session.add(gpu_record)
|
session.add(gpu_record)
|
||||||
@@ -259,9 +259,9 @@ async def buy_gpu(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Create booking for the purchase
|
# Create booking for the purchase
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, UTC, timedelta
|
||||||
|
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
end_time = start_time + timedelta(hours=request.duration_hours)
|
end_time = start_time + timedelta(hours=request.duration_hours)
|
||||||
|
|
||||||
# Calculate total cost
|
# Calculate total cost
|
||||||
@@ -411,7 +411,7 @@ async def sell_gpu(
|
|||||||
"listing_price": request.listing_price,
|
"listing_price": request.listing_price,
|
||||||
"status": "listed",
|
"status": "listed",
|
||||||
"description": request.description,
|
"description": request.description,
|
||||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -442,7 +442,7 @@ async def book_gpu(
|
|||||||
status_code=http_status.HTTP_400_BAD_REQUEST, detail="Booking duration cannot exceed 8760 hours (1 year)"
|
status_code=http_status.HTTP_400_BAD_REQUEST, detail="Booking duration cannot exceed 8760 hours (1 year)"
|
||||||
)
|
)
|
||||||
|
|
||||||
start_time = datetime.utcnow()
|
start_time = datetime.now(datetime.UTC)
|
||||||
end_time = start_time + timedelta(hours=request.duration_hours)
|
end_time = start_time + timedelta(hours=request.duration_hours)
|
||||||
|
|
||||||
# Validate booking end time is in the future
|
# Validate booking end time is in the future
|
||||||
@@ -593,7 +593,7 @@ async def submit_ollama_task(
|
|||||||
)
|
)
|
||||||
|
|
||||||
task_id = f"task_{uuid4().hex[:10]}"
|
task_id = f"task_{uuid4().hex[:10]}"
|
||||||
submitted_at = datetime.utcnow().isoformat() + "Z"
|
submitted_at = datetime.now(datetime.UTC).isoformat() + "Z"
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"task_id": task_id,
|
"task_id": task_id,
|
||||||
@@ -619,7 +619,7 @@ async def send_payment(
|
|||||||
)
|
)
|
||||||
|
|
||||||
tx_id = f"tx_{uuid4().hex[:10]}"
|
tx_id = f"tx_{uuid4().hex[:10]}"
|
||||||
processed_at = datetime.utcnow().isoformat() + "Z"
|
processed_at = datetime.now(datetime.UTC).isoformat() + "Z"
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"tx_id": tx_id,
|
"tx_id": tx_id,
|
||||||
@@ -920,7 +920,7 @@ async def get_pricing(
|
|||||||
},
|
},
|
||||||
"individual_gpu_pricing": dynamic_prices,
|
"individual_gpu_pricing": dynamic_prices,
|
||||||
"market_analysis": market_analysis,
|
"market_analysis": market_analysis,
|
||||||
"pricing_timestamp": datetime.utcnow().isoformat() + "Z",
|
"pricing_timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -935,5 +935,5 @@ async def bid_gpu(request: dict[str, Any], session: Session = Depends(get_sessio
|
|||||||
"gpu_id": request.get("gpu_id"),
|
"gpu_id": request.get("gpu_id"),
|
||||||
"bid_amount": request.get("bid_amount"),
|
"bid_amount": request.get("bid_amount"),
|
||||||
"duration_hours": request.get("duration_hours"),
|
"duration_hours": request.get("duration_hours"),
|
||||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||||
@@ -87,7 +87,7 @@ async def submit_result(
|
|||||||
metrics = dict(req.metrics or {})
|
metrics = dict(req.metrics or {})
|
||||||
duration_ms = metrics.get("duration_ms")
|
duration_ms = metrics.get("duration_ms")
|
||||||
if duration_ms is None and job.requested_at:
|
if duration_ms is None and job.requested_at:
|
||||||
duration_ms = int((datetime.utcnow() - job.requested_at).total_seconds() * 1000)
|
duration_ms = int((datetime.now(datetime.UTC) - job.requested_at).total_seconds() * 1000)
|
||||||
metrics["duration_ms"] = duration_ms
|
metrics["duration_ms"] = duration_ms
|
||||||
|
|
||||||
receipt = receipt_service.create_receipt(job, miner_id, req.result, metrics)
|
receipt = receipt_service.create_receipt(job, miner_id, req.result, metrics)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides health monitoring for specialized modality optimization strategies
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
@@ -33,7 +33,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "modality-optimization",
|
"service": "modality-optimization",
|
||||||
"port": 8004,
|
"port": 8004,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
# System metrics
|
# System metrics
|
||||||
"system": {
|
"system": {
|
||||||
@@ -86,7 +86,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "modality-optimization",
|
"service": "modality-optimization",
|
||||||
"port": 8004,
|
"port": 8004,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Health check failed",
|
"error": "Health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +148,7 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "modality-optimization",
|
"service": "modality-optimization",
|
||||||
"port": 8004,
|
"port": 8004,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"optimization_tests": optimization_tests,
|
"optimization_tests": optimization_tests,
|
||||||
"overall_health": (
|
"overall_health": (
|
||||||
"pass" if all(test.get("status") == "pass" for test in optimization_tests.values()) else "degraded"
|
"pass" if all(test.get("status") == "pass" for test in optimization_tests.values()) else "degraded"
|
||||||
@@ -161,6 +161,6 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "modality-optimization",
|
"service": "modality-optimization",
|
||||||
"port": 8004,
|
"port": 8004,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Deep health check failed",
|
"error": "Deep health check failed",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Provides a unified dashboard for all 6 enhanced services
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
@@ -75,7 +75,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
|||||||
overall_metrics = calculate_overall_metrics(health_data)
|
overall_metrics = calculate_overall_metrics(health_data)
|
||||||
|
|
||||||
dashboard_data = {
|
dashboard_data = {
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"overall_status": overall_metrics["overall_status"],
|
"overall_status": overall_metrics["overall_status"],
|
||||||
"services": health_data,
|
"services": health_data,
|
||||||
"metrics": overall_metrics,
|
"metrics": overall_metrics,
|
||||||
@@ -84,7 +84,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
|||||||
"healthy_services": len([s for s in health_data.values() if s.get("status") == "healthy"]),
|
"healthy_services": len([s for s in health_data.values() if s.get("status") == "healthy"]),
|
||||||
"degraded_services": len([s for s in health_data.values() if s.get("status") == "degraded"]),
|
"degraded_services": len([s for s in health_data.values() if s.get("status") == "degraded"]),
|
||||||
"unhealthy_services": len([s for s in health_data.values() if s.get("status") == "unhealthy"]),
|
"unhealthy_services": len([s for s in health_data.values() if s.get("status") == "unhealthy"]),
|
||||||
"last_updated": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"),
|
"last_updated": datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
|||||||
logger.error(f"Failed to generate monitoring dashboard: {e}")
|
logger.error(f"Failed to generate monitoring dashboard: {e}")
|
||||||
return {
|
return {
|
||||||
"error": "Failed to generate dashboard",
|
"error": "Failed to generate dashboard",
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"services": SERVICES,
|
"services": SERVICES,
|
||||||
"overall_status": "error",
|
"overall_status": "error",
|
||||||
"summary": {
|
"summary": {
|
||||||
@@ -106,7 +106,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
|||||||
"healthy_services": 0,
|
"healthy_services": 0,
|
||||||
"degraded_services": 0,
|
"degraded_services": 0,
|
||||||
"unhealthy_services": len(SERVICES),
|
"unhealthy_services": len(SERVICES),
|
||||||
"last_updated": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"),
|
"last_updated": datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,7 +119,7 @@ async def services_summary() -> dict[str, Any]:
|
|||||||
try:
|
try:
|
||||||
health_data = await collect_all_health_data()
|
health_data = await collect_all_health_data()
|
||||||
|
|
||||||
summary = {"timestamp": datetime.utcnow().isoformat(), "services": {}}
|
summary = {"timestamp": datetime.now(datetime.UTC).isoformat(), "services": {}}
|
||||||
|
|
||||||
for service_id, service_info in SERVICES.items():
|
for service_id, service_info in SERVICES.items():
|
||||||
health = health_data.get(service_id, {})
|
health = health_data.get(service_id, {})
|
||||||
@@ -136,7 +136,7 @@ async def services_summary() -> dict[str, Any]:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to generate services summary: {e}")
|
logger.error(f"Failed to generate services summary: {e}")
|
||||||
return {"error": "Failed to generate summary", "timestamp": datetime.utcnow().isoformat()}
|
return {"error": "Failed to generate summary", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/dashboard/metrics", tags=["monitoring"], summary="System Metrics")
|
@router.get("/dashboard/metrics", tags=["monitoring"], summary="System Metrics")
|
||||||
@@ -156,7 +156,7 @@ async def system_metrics() -> dict[str, Any]:
|
|||||||
network = psutil.net_io_counters()
|
network = psutil.net_io_counters()
|
||||||
|
|
||||||
metrics = {
|
metrics = {
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"system": {
|
"system": {
|
||||||
"cpu_percent": cpu_percent,
|
"cpu_percent": cpu_percent,
|
||||||
"cpu_count": psutil.cpu_count(),
|
"cpu_count": psutil.cpu_count(),
|
||||||
@@ -184,7 +184,7 @@ async def system_metrics() -> dict[str, Any]:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to collect system metrics: {e}")
|
logger.error(f"Failed to collect system metrics: {e}")
|
||||||
return {"error": "Failed to collect metrics", "timestamp": datetime.utcnow().isoformat()}
|
return {"error": "Failed to collect metrics", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
async def collect_all_health_data() -> dict[str, Any]:
|
async def collect_all_health_data() -> dict[str, Any]:
|
||||||
@@ -206,7 +206,7 @@ async def collect_all_health_data() -> dict[str, Any]:
|
|||||||
health_data[service_id] = {
|
health_data[service_id] = {
|
||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"error": str(result),
|
"error": str(result),
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
health_data[service_id] = result
|
health_data[service_id] = result
|
||||||
@@ -225,7 +225,7 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
|
|||||||
return {
|
return {
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"response_time": 0.1, # Placeholder - would be measured
|
"response_time": 0.1, # Placeholder - would be measured
|
||||||
"last_check": datetime.utcnow().isoformat(),
|
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||||
"details": response,
|
"details": response,
|
||||||
}
|
}
|
||||||
except NetworkError as e:
|
except NetworkError as e:
|
||||||
@@ -233,11 +233,11 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
|
|||||||
return {
|
return {
|
||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"error": str(e),
|
"error": str(e),
|
||||||
"last_check": datetime.utcnow().isoformat(),
|
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||||
}
|
}
|
||||||
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.utcnow().isoformat()}
|
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.utcnow().isoformat()}
|
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
def calculate_overall_metrics(health_data: dict[str, Any]) -> dict[str, Any]:
|
def calculate_overall_metrics(health_data: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides health monitoring for multi-modal processing capabilities
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
@@ -38,7 +38,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "multimodal-agent",
|
"service": "multimodal-agent",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
# System metrics
|
# System metrics
|
||||||
"system": {
|
"system": {
|
||||||
@@ -81,7 +81,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "multimodal-agent",
|
"service": "multimodal-agent",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Health check failed",
|
"error": "Health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,7 +129,7 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
|
|||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "multimodal-agent",
|
"service": "multimodal-agent",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"modality_tests": modality_tests,
|
"modality_tests": modality_tests,
|
||||||
"overall_health": "pass" if all(test.get("status") == "pass" for test in modality_tests.values()) else "degraded",
|
"overall_health": "pass" if all(test.get("status") == "pass" for test in modality_tests.values()) else "degraded",
|
||||||
}
|
}
|
||||||
@@ -140,6 +140,6 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "multimodal-agent",
|
"service": "multimodal-agent",
|
||||||
"port": 8002,
|
"port": 8002,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Deep health check failed",
|
"error": "Deep health check failed",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,13 +42,13 @@ async def detailed_health():
|
|||||||
try:
|
try:
|
||||||
import psutil
|
import psutil
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "openclaw-enhanced",
|
"service": "openclaw-enhanced",
|
||||||
"port": 8014,
|
"port": 8014,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": "3.13.5",
|
"python_version": "3.13.5",
|
||||||
"system": {
|
"system": {
|
||||||
"cpu_percent": psutil.cpu_percent(),
|
"cpu_percent": psutil.cpu_percent(),
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Provides health monitoring for agent orchestration, edge computing, and ecosyste
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
@@ -43,7 +43,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
|
|||||||
"status": "healthy" if edge_status["available"] else "degraded",
|
"status": "healthy" if edge_status["available"] else "degraded",
|
||||||
"service": "openclaw-enhanced",
|
"service": "openclaw-enhanced",
|
||||||
"port": 8007,
|
"port": 8007,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||||
# System metrics
|
# System metrics
|
||||||
"system": {
|
"system": {
|
||||||
@@ -95,7 +95,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "openclaw-enhanced",
|
"service": "openclaw-enhanced",
|
||||||
"port": 8007,
|
"port": 8007,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Health check failed",
|
"error": "Health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,7 +162,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
|
|||||||
"status": "healthy" if edge_status["available"] else "degraded",
|
"status": "healthy" if edge_status["available"] else "degraded",
|
||||||
"service": "openclaw-enhanced",
|
"service": "openclaw-enhanced",
|
||||||
"port": 8007,
|
"port": 8007,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"feature_tests": feature_tests,
|
"feature_tests": feature_tests,
|
||||||
"edge_computing": edge_status,
|
"edge_computing": edge_status,
|
||||||
"overall_health": (
|
"overall_health": (
|
||||||
@@ -178,7 +178,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
|
|||||||
"status": "unhealthy",
|
"status": "unhealthy",
|
||||||
"service": "openclaw-enhanced",
|
"service": "openclaw-enhanced",
|
||||||
"port": 8007,
|
"port": 8007,
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||||
"error": "Deep health check failed",
|
"error": "Deep health check failed",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Partner Router - Third-party integration management
|
|||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import secrets
|
import secrets
|
||||||
from datetime import datetime
|
from datetime import datetime, UTC
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
@@ -91,7 +91,7 @@ async def register_partner(partner: PartnerRegister, session: Annotated[Session,
|
|||||||
"api_key": api_key,
|
"api_key": api_key,
|
||||||
"api_secret_hash": hashlib.sha256(api_secret.encode()).hexdigest(),
|
"api_secret_hash": hashlib.sha256(api_secret.encode()).hexdigest(),
|
||||||
"rate_limit": rate_limits.get(partner.integration_type, rate_limits["other"]),
|
"rate_limit": rate_limits.get(partner.integration_type, rate_limits["other"]),
|
||||||
"created_at": datetime.utcnow(),
|
"created_at": datetime.now(datetime.UTC),
|
||||||
"status": "active",
|
"status": "active",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,7 +162,7 @@ async def create_webhook(
|
|||||||
"events": webhook.events,
|
"events": webhook.events,
|
||||||
"secret": webhook.secret,
|
"secret": webhook.secret,
|
||||||
"status": "active",
|
"status": "active",
|
||||||
"created_at": datetime.utcnow(),
|
"created_at": datetime.now(datetime.UTC),
|
||||||
}
|
}
|
||||||
|
|
||||||
return WebhookResponse(
|
return WebhookResponse(
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user