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:
aitbc
2026-04-30 08:36:55 +02:00
parent 4d76bf4d97
commit 5f03ded7ff
294 changed files with 1997 additions and 1997 deletions

View File

@@ -4,7 +4,7 @@ Provides standard response formatters, pagination helpers, error response builde
"""
from typing import Any, Optional, List, Dict, Union
from datetime import datetime
from datetime import datetime, UTC
from fastapi import HTTPException, status
from pydantic import BaseModel
@@ -19,7 +19,7 @@ class APIResponse(BaseModel):
def __init__(self, **data):
if 'timestamp' not in data:
data['timestamp'] = datetime.utcnow().isoformat()
data['timestamp'] = datetime.now(datetime.UTC).isoformat()
super().__init__(**data)
@@ -33,7 +33,7 @@ class PaginatedResponse(BaseModel):
def __init__(self, **data):
if 'timestamp' not in data:
data['timestamp'] = datetime.utcnow().isoformat()
data['timestamp'] = datetime.now(datetime.UTC).isoformat()
super().__init__(**data)
@@ -318,5 +318,5 @@ def build_request_metadata(request) -> Dict[str, str]:
"client_ip": get_client_ip(request),
"user_agent": get_user_agent(request),
"request_id": request.headers.get("X-Request-ID", "unknown"),
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}

View File

@@ -5,7 +5,7 @@ Provides toggle between mock and real data sources for development/testing
import os
from typing import Any, Dict, List, Optional
from datetime import datetime
from datetime import datetime, UTC
import httpx
@@ -119,7 +119,7 @@ class MockDataGenerator:
"hash": MockFactory.generate_hash(),
"validator": validator or MockFactory.generate_ethereum_address(),
"tx_count": min_tx or 5,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
})
return blocks

View File

@@ -6,7 +6,7 @@ Provides event bus implementation, pub/sub patterns, and event decorators
import asyncio
from typing import Any, Callable, Dict, List, Optional, TypeVar, Generic
from dataclasses import dataclass
from datetime import datetime
from datetime import datetime, UTC
from enum import Enum
import inspect
import functools
@@ -34,7 +34,7 @@ class Event:
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.utcnow()
self.timestamp = datetime.now(datetime.UTC)
class EventBus:
@@ -199,7 +199,7 @@ class EventAggregator:
def add_event(self, event: Event) -> None:
"""Add event to aggregation"""
key = event.event_type
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
if key not in self.aggregated_events:
self.aggregated_events[key] = {
@@ -223,7 +223,7 @@ class EventAggregator:
def get_aggregated_events(self) -> Dict[str, Dict[str, Any]]:
"""Get aggregated events"""
# Remove old events
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
cutoff = now.timestamp() - self.window_seconds
to_remove = []

View File

@@ -8,7 +8,7 @@ import heapq
import time
from typing import Any, Callable, Dict, List, Optional, TypeVar
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from enum import Enum
import uuid
@@ -244,7 +244,7 @@ class BackgroundTaskManager:
async with self.semaphore:
try:
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):
result = await func(*args, **kwargs)
@@ -253,18 +253,18 @@ class BackgroundTaskManager:
self.task_info[task_id]["status"] = "completed"
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:
self.task_info[task_id]["status"] = "failed"
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:
if task_id in self.tasks:
del self.tasks[task_id]
self.task_info[task_id] = {
"status": "pending",
"created_at": datetime.utcnow(),
"created_at": datetime.now(datetime.UTC),
"started_at": None,
"completed_at": None,
"result": None,
@@ -286,7 +286,7 @@ class BackgroundTaskManager:
pass
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]
return True
return False

View File

@@ -9,7 +9,7 @@ import hashlib
import time
import json
from typing import Optional, Dict, Any
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from cryptography.fernet import Fernet
@@ -118,7 +118,7 @@ class APIKeyManager:
"user_id": user_id,
"scopes": scopes or ["read"],
"name": name,
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"last_used": None
}
@@ -134,7 +134,7 @@ class APIKeyManager:
return None
# Update last used
key_data["last_used"] = datetime.utcnow().isoformat()
key_data["last_used"] = datetime.now(datetime.UTC).isoformat()
if self.storage_path:
self._save_keys()

View File

@@ -7,7 +7,7 @@ import json
import os
from typing import Any, Callable, Dict, Optional, TypeVar, Generic, List
from dataclasses import dataclass, field
from datetime import datetime
from datetime import datetime, UTC
from enum import Enum
from abc import ABC, abstractmethod
import asyncio
@@ -304,7 +304,7 @@ class StateSnapshot:
self.current_state = state_machine.current_state
self.state_data = state_machine.state_data.copy()
self.transitions = state_machine.transitions.copy()
self.timestamp = datetime.utcnow()
self.timestamp = datetime.now(datetime.UTC)
def restore(self, state_machine: StateMachine) -> None:
"""Restore state machine from snapshot"""

View File

@@ -6,7 +6,7 @@ Provides mock factories, test data generators, and test helpers
import secrets
import json
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 decimal import Decimal
import uuid
@@ -72,8 +72,8 @@ class TestDataGenerator:
"username": MockFactory.generate_string(8),
"first_name": MockFactory.generate_string(6),
"last_name": MockFactory.generate_string(6),
"created_at": datetime.utcnow().isoformat(),
"updated_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"updated_at": datetime.now(datetime.UTC).isoformat(),
"is_active": True,
"role": "user"
}
@@ -91,7 +91,7 @@ class TestDataGenerator:
"gas_price": str(secrets.randbelow(100000000000)),
"gas_limit": secrets.randbelow(100000),
"nonce": secrets.randbelow(1000),
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"status": "pending"
}
data.update(overrides)
@@ -104,7 +104,7 @@ class TestDataGenerator:
"number": secrets.randbelow(10000000),
"hash": MockFactory.generate_hash(),
"parent_hash": MockFactory.generate_hash(),
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"transactions": [],
"gas_used": str(secrets.randbelow(10000000)),
"gas_limit": str(15000000),
@@ -122,7 +122,7 @@ class TestDataGenerator:
"user_id": MockFactory.generate_uuid(),
"name": MockFactory.generate_string(10),
"scopes": ["read", "write"],
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"last_used": None,
"is_active": True
}
@@ -137,7 +137,7 @@ class TestDataGenerator:
"address": MockFactory.generate_ethereum_address(),
"chain_id": 1,
"balance": str(secrets.randbelow(1000000000000000000)),
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"is_active": True
}
data.update(overrides)

View File

@@ -10,7 +10,7 @@ try:
import numpy as np
except ImportError: # pragma: no cover - optional dependency for runtime AI features
np = None
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, field
from collections import defaultdict
@@ -93,7 +93,7 @@ class AdvancedAIIntegration:
'hidden_sizes': hidden_sizes,
'output_size': output_size
},
'created_at': datetime.utcnow().isoformat()
'created_at': datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -187,7 +187,7 @@ class AdvancedAIIntegration:
'final_loss': losses[-1] if losses else 0,
'accuracy': accuracy,
'training_data_size': len(training_data),
'trained_at': datetime.utcnow().isoformat()
'trained_at': datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -218,7 +218,7 @@ class AdvancedAIIntegration:
'network_id': network_id,
'features': features,
'prediction': float(prediction[0][0]),
'timestamp': datetime.utcnow().isoformat()
'timestamp': datetime.now(datetime.UTC).isoformat()
}
self.predictions_history.append(prediction_record)
@@ -227,7 +227,7 @@ class AdvancedAIIntegration:
'network_id': network_id,
'prediction': float(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:
@@ -261,7 +261,7 @@ class AdvancedAIIntegration:
'model_type': model_type,
'features': features,
'target': target,
'created_at': datetime.utcnow().isoformat()
'created_at': datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -286,7 +286,7 @@ class AdvancedAIIntegration:
model.accuracy = accuracy
model.training_data_size = len(training_data)
model.last_trained = datetime.utcnow()
model.last_trained = datetime.now(datetime.UTC)
# Store performance
self.model_performance[model_id].append(accuracy)
@@ -405,7 +405,7 @@ class AdvancedAIIntegration:
'model_id': model_id,
'features': features,
'prediction': prediction,
'timestamp': datetime.utcnow().isoformat()
'timestamp': datetime.now(datetime.UTC).isoformat()
}
self.predictions_history.append(prediction_record)
@@ -414,7 +414,7 @@ class AdvancedAIIntegration:
'model_id': model_id,
'prediction': prediction,
'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:
@@ -451,7 +451,7 @@ class AdvancedAIIntegration:
'model_performance': model_stats,
'training_data_sizes': training_stats,
'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:

View File

@@ -4,7 +4,7 @@ Implements adaptive learning, predictive analytics, and intelligent optimization
"""
import asyncio
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, field
from collections import defaultdict, deque
@@ -55,7 +55,7 @@ class RealTimeLearningSystem:
try:
experience = LearningExperience(
experience_id=str(uuid.uuid4()),
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
context=experience_data.get('context', {}),
action=experience_data.get('action', ''),
outcome=experience_data.get('outcome', ''),
@@ -157,7 +157,7 @@ class RealTimeLearningSystem:
features=['action', 'context_load', 'context_agents'],
target='performance_score',
accuracy=0.85,
last_updated=datetime.utcnow()
last_updated=datetime.now(datetime.UTC)
)
self.models['performance'] = performance_model
@@ -169,7 +169,7 @@ class RealTimeLearningSystem:
features=['action', 'context_time', 'context_resources'],
target='success_probability',
accuracy=0.82,
last_updated=datetime.utcnow()
last_updated=datetime.now(datetime.UTC)
)
self.models['success'] = success_model
@@ -257,7 +257,7 @@ class RealTimeLearningSystem:
try:
total_experiences = len(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:
return {
@@ -299,7 +299,7 @@ class RealTimeLearningSystem:
def _get_last_adaptation_time(self) -> Optional[str]:
"""Get the time of the last adaptation"""
# 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]:
"""Recommend the best action based on learning"""

View File

@@ -3,7 +3,7 @@ JWT Authentication Handler for AITBC Agent Coordinator
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
import secrets
@@ -26,15 +26,15 @@ class JWTHandler:
try:
if expires_delta:
expire = datetime.utcnow() + expires_delta
expire = datetime.now(datetime.UTC) + expires_delta
else:
expire = datetime.utcnow() + self.token_expiry
expire = datetime.now(datetime.UTC) + self.token_expiry
# Add standard claims
token_payload = {
**payload,
"exp": expire,
"iat": datetime.utcnow(),
"iat": datetime.now(datetime.UTC),
"type": "access"
}
@@ -57,12 +57,12 @@ class JWTHandler:
import jwt
try:
expire = datetime.utcnow() + self.refresh_expiry
expire = datetime.now(datetime.UTC) + self.refresh_expiry
token_payload = {
**payload,
"exp": expire,
"iat": datetime.utcnow(),
"iat": datetime.now(datetime.UTC),
"type": "refresh"
}
@@ -227,7 +227,7 @@ class APIKeyManager:
key_data = {
"user_id": user_id,
"permissions": permissions or [],
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"last_used": None,
"usage_count": 0
}
@@ -258,7 +258,7 @@ class APIKeyManager:
key_data = self.api_keys[api_key]
# Update usage statistics
key_data["last_used"] = datetime.utcnow().isoformat()
key_data["last_used"] = datetime.now(datetime.UTC).isoformat()
key_data["usage_count"] += 1
return {

View File

@@ -4,7 +4,7 @@ Implements various consensus algorithms for distributed decision making
"""
import asyncio
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Dict, List, Any, Optional, Set, Tuple
from dataclasses import dataclass, field
from collections import defaultdict
@@ -59,7 +59,7 @@ class DistributedConsensus:
node = ConsensusNode(
node_id=node_id,
endpoint=endpoint,
last_seen=datetime.utcnow(),
last_seen=datetime.now(datetime.UTC),
reputation_score=node_data.get('reputation_score', 1.0),
voting_power=node_data.get('voting_power', 1.0),
is_active=True
@@ -70,7 +70,7 @@ class DistributedConsensus:
return {
'status': 'success',
'node_id': node_id,
'registered_at': datetime.utcnow().isoformat(),
'registered_at': datetime.now(datetime.UTC).isoformat(),
'total_nodes': len(self.nodes)
}
@@ -98,8 +98,8 @@ class DistributedConsensus:
proposal_id=proposal_id,
proposer_id=proposer_id,
proposal_data=proposal_data.get('content', {}),
timestamp=datetime.utcnow(),
deadline=datetime.utcnow() + self.voting_timeout,
timestamp=datetime.now(datetime.UTC),
deadline=datetime.now(datetime.UTC) + self.voting_timeout,
required_votes=required_votes
)
@@ -186,7 +186,7 @@ class DistributedConsensus:
# Record 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
await self._check_consensus(proposal)
@@ -216,7 +216,7 @@ class DistributedConsensus:
total_votes = len(proposal.current_votes)
# Check if deadline passed
if datetime.utcnow() > proposal.deadline:
if datetime.now(datetime.UTC) > proposal.deadline:
proposal.status = 'expired'
await self._finalize_proposal(proposal, False, 'Deadline expired')
return
@@ -266,7 +266,7 @@ class DistributedConsensus:
'reason': reason,
'votes': dict(proposal.current_votes),
'required_votes': proposal.required_votes,
'finalized_at': datetime.utcnow().isoformat(),
'finalized_at': datetime.now(datetime.UTC).isoformat(),
'algorithm': self.current_algorithm
}
@@ -283,7 +283,7 @@ class DistributedConsensus:
async def _cleanup_old_proposals(self):
"""Clean up old and expired proposals"""
try:
current_time = datetime.utcnow()
current_time = datetime.now(datetime.UTC)
expired_proposals = [
pid for pid, proposal in self.proposals.items()
if proposal.deadline < current_time or proposal.status in ['approved', 'rejected', 'expired']
@@ -340,7 +340,7 @@ class DistributedConsensus:
return {
'status': 'success',
'algorithm': algorithm,
'changed_at': datetime.utcnow().isoformat()
'changed_at': datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -400,7 +400,7 @@ class DistributedConsensus:
'algorithm_performance': dict(algorithm_stats),
'node_participation': node_participation,
'active_proposals': len(self.proposals),
'last_updated': datetime.utcnow().isoformat()
'last_updated': datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -414,13 +414,13 @@ class DistributedConsensus:
return {'status': 'error', 'message': 'Node not found'}
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 {
'status': 'success',
'node_id': node_id,
'is_active': is_active,
'updated_at': datetime.utcnow().isoformat()
'updated_at': datetime.now(datetime.UTC).isoformat()
}
except Exception as e:

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from aitbc import get_logger
from fastapi.responses import JSONResponse
@@ -14,7 +14,7 @@ def register_exception_handlers(app):
content={
"status": "error",
"message": "Resource not found",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
},
)
@@ -26,6 +26,6 @@ def register_exception_handlers(app):
content={
"status": "error",
"message": "Internal server error",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
},
)

View File

@@ -5,7 +5,7 @@ Implements comprehensive alerting with multiple channels and SLA monitoring
import asyncio
import smtplib
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass, field
from enum import Enum
@@ -134,7 +134,7 @@ class SLAMonitor:
return
if timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
rule = self.sla_rules[sla_id]
@@ -188,7 +188,7 @@ class SLAMonitor:
# Get recent violations
recent_violations = [
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 {
@@ -375,7 +375,7 @@ Annotations: {json.dumps(alert.annotations, indent=2)}
payload = {
"alert": alert.to_dict(),
"message": message,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
response = requests.post(
@@ -499,7 +499,7 @@ class AlertManager:
try:
condition_met = self._evaluate_condition(rule.condition, metrics, rule.threshold)
current_time = datetime.utcnow()
current_time = datetime.now(datetime.UTC)
if condition_met:
# 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]):
"""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
existing_alert = self._find_similar_active_alert(rule)
@@ -556,8 +556,8 @@ class AlertManager:
description=rule.description,
severity=rule.severity,
status=AlertStatus.ACTIVE,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
updated_at=datetime.now(datetime.UTC),
labels=rule.labels.copy(),
annotations=rule.annotations.copy()
)
@@ -607,8 +607,8 @@ class AlertManager:
alert = self.alerts[alert_id]
alert.status = AlertStatus.RESOLVED
alert.resolved_at = datetime.utcnow()
alert.updated_at = datetime.utcnow()
alert.resolved_at = datetime.now(datetime.UTC)
alert.updated_at = datetime.now(datetime.UTC)
return {"status": "success", "alert": alert.to_dict()}

View File

@@ -7,7 +7,7 @@ import json
from enum import Enum
from typing import Dict, List, Optional, Any, Callable
from dataclasses import dataclass, field
from datetime import datetime
from datetime import datetime, UTC
import uuid
from pydantic import BaseModel, Field
@@ -123,7 +123,7 @@ class CommunicationProtocol:
def _is_message_expired(self, message: AgentMessage) -> bool:
"""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
async def _send_to_agent(self, message: AgentMessage):
@@ -283,7 +283,7 @@ class MessageTemplates:
sender_id=sender_id,
message_type=MessageType.HEARTBEAT,
priority=Priority.LOW,
payload={"timestamp": datetime.utcnow().isoformat()}
payload={"timestamp": datetime.now(datetime.UTC).isoformat()}
)
@staticmethod

View File

@@ -7,7 +7,7 @@ import json
from enum import Enum
from typing import Dict, List, Optional, Any, Callable, Union
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
import uuid
import hashlib
from pydantic import BaseModel, Field, validator
@@ -77,7 +77,7 @@ class TaskMessage(BaseModel):
@validator('deadline')
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")
return v
@@ -156,7 +156,7 @@ class MessageRouter:
async def route_message(self, message: AgentMessage) -> Optional[str]:
"""Route message based on routing rules"""
start_time = datetime.utcnow()
start_time = datetime.now(datetime.UTC)
try:
# Check if message is expired
@@ -192,7 +192,7 @@ class MessageRouter:
self.routing_stats["messages_failed"] += 1
return None
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
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:
"""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
async def get_routing_stats(self) -> Dict[str, Any]:
@@ -269,12 +269,12 @@ class LoadBalancer:
def __init__(self):
self.agent_loads: 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):
"""Update agent load information"""
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):
"""Set agent weight for load balancing"""
@@ -421,7 +421,7 @@ class MessageProcessor:
async def process_message(self, message: AgentMessage) -> bool:
"""Process a message"""
start_time = datetime.utcnow()
start_time = datetime.now(datetime.UTC)
try:
# Route message
@@ -440,7 +440,7 @@ class MessageProcessor:
# Update stats
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
return True

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional
from aitbc import get_logger
@@ -52,7 +52,7 @@ async def register_agent(request: AgentRegistrationRequest):
"status": "success",
"message": f"Agent {request.agent_id} registered successfully",
"agent_id": request.agent_id,
"registered_at": datetime.utcnow().isoformat()
"registered_at": datetime.now(datetime.UTC).isoformat()
}
else:
raise HTTPException(status_code=500, detail="Failed to register agent")
@@ -78,7 +78,7 @@ async def discover_agents(query: Dict[str, Any]):
"query": query,
"agents": [agent.to_dict() for agent in agents],
"count": len(agents),
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -101,7 +101,7 @@ async def get_agent(agent_id: str):
return {
"status": "success",
"agent": agent.to_dict(),
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except HTTPException:
@@ -132,7 +132,7 @@ async def update_agent_status(agent_id: str, request: AgentStatusUpdate):
"message": f"Agent {agent_id} status updated",
"agent_id": agent_id,
"new_status": request.status,
"updated_at": datetime.utcnow().isoformat()
"updated_at": datetime.now(datetime.UTC).isoformat()
}
else:
raise HTTPException(status_code=500, detail="Failed to update agent status")

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional
from aitbc import get_logger
@@ -156,7 +156,7 @@ async def record_sla_metric(
"status": "success",
"message": f"SLA metric recorded for {sla_id}",
"value": value,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
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",
"task_distributor": "running" if state.task_distributor else "stopped"
},
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
return status

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional
from aitbc import get_logger
@@ -105,7 +105,7 @@ async def get_advanced_features_status():
return {
"status": "success",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"features": {
"realtime_learning": {
"status": "active",

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional
from aitbc import get_logger
@@ -30,7 +30,7 @@ async def health_check():
return {
"status": "healthy",
"service": "agent-coordinator",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"version": "1.0.0"
}

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional
from aitbc import get_logger
@@ -63,7 +63,7 @@ async def send_message(request: MessageRequest):
"message": "Message sent successfully",
"message_id": message.id,
"receiver_id": request.receiver_id,
"sent_at": datetime.utcnow().isoformat()
"sent_at": datetime.now(datetime.UTC).isoformat()
}
else:
raise HTTPException(status_code=500, detail="Failed to send message")
@@ -85,7 +85,7 @@ async def get_load_balancer_stats():
return {
"status": "success",
"stats": stats,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -105,7 +105,7 @@ async def get_registry_stats():
return {
"status": "success",
"stats": stats,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -127,7 +127,7 @@ async def get_agents_by_service(service: str):
"service": service,
"agents": [agent.to_dict() for agent in agents],
"count": len(agents),
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -149,7 +149,7 @@ async def get_agents_by_capability(capability: str):
"capability": capability,
"agents": [agent.to_dict() for agent in agents],
"count": len(agents),
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -175,7 +175,7 @@ async def set_load_balancing_strategy(strategy: str = Query(..., description="Lo
"status": "success",
"message": f"Load balancing strategy set to {strategy}",
"strategy": strategy,
"updated_at": datetime.utcnow().isoformat()
"updated_at": datetime.now(datetime.UTC).isoformat()
}
except HTTPException:

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional
from aitbc import get_logger
@@ -84,7 +84,7 @@ async def get_metrics_summary():
"status": "success",
"performance": summary,
"system": system_metrics,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:
@@ -116,7 +116,7 @@ async def get_health_metrics():
"count": psutil.cpu_count()
},
"uptime": performance_monitor.get_performance_summary()["uptime_seconds"],
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
return {

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
import uuid
from typing import Any, Dict, List, Optional
@@ -50,7 +50,7 @@ async def submit_task(request: TaskSubmission, background_tasks: BackgroundTasks
"message": "Task submitted successfully",
"task_id": request.task_data.get("task_id", str(uuid.uuid4())),
"priority": request.priority,
"submitted_at": datetime.utcnow().isoformat()
"submitted_at": datetime.now(datetime.UTC).isoformat()
}
except HTTPException:
@@ -72,7 +72,7 @@ async def get_task_status():
return {
"status": "success",
"stats": stats,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:

View File

@@ -8,7 +8,7 @@ import asyncio
import json
from typing import Dict, List, Optional, Set, Callable, Any
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
import uuid
import hashlib
from enum import Enum
@@ -178,7 +178,7 @@ class AgentRegistry:
agent_info = self.agents[agent_id]
agent_info.status = status
agent_info.last_heartbeat = datetime.utcnow()
agent_info.last_heartbeat = datetime.now(datetime.UTC)
if load_metrics:
agent_info.load_metrics.update(load_metrics)
@@ -206,7 +206,7 @@ class AgentRegistry:
return False
agent_info = self.agents[agent_id]
agent_info.last_heartbeat = datetime.utcnow()
agent_info.last_heartbeat = datetime.now(datetime.UTC)
# Update health score
agent_info.health_score = self._calculate_health_score(agent_info)
@@ -307,7 +307,7 @@ class AgentRegistry:
"type_counts": type_counts,
"service_count": len(self.service_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):
@@ -372,7 +372,7 @@ class AgentRegistry:
base_score -= 0.1
# 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:
base_score -= 0.5
elif heartbeat_age > self.max_heartbeat_age / 2:
@@ -428,7 +428,7 @@ class AgentRegistry:
event = {
"event_type": event_type,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"agent_info": agent_info.to_dict()
}
@@ -441,7 +441,7 @@ class AgentRegistry:
await asyncio.sleep(self.heartbeat_interval)
# Check for agents with old heartbeats
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
for agent_id, agent_info in list(self.agents.items()):
heartbeat_age = (now - agent_info.last_heartbeat).total_seconds()
@@ -462,7 +462,7 @@ class AgentRegistry:
await asyncio.sleep(self.cleanup_interval)
# Remove agents that have been inactive too long
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
max_inactive_age = timedelta(hours=1) # 1 hour
for agent_id, agent_info in list(self.agents.items()):
@@ -502,8 +502,8 @@ class AgentDiscoveryService:
services=discovery_data.services,
endpoints=discovery_data.endpoints,
metadata=discovery_data.metadata,
last_heartbeat=datetime.utcnow(),
registration_time=datetime.utcnow()
last_heartbeat=datetime.now(datetime.UTC),
registration_time=datetime.now(datetime.UTC)
)
# Register or update agent
@@ -597,8 +597,8 @@ def create_agent_info(agent_id: str, agent_type: str, capabilities: List[str], s
services=services,
endpoints=endpoints,
metadata={},
last_heartbeat=datetime.utcnow(),
registration_time=datetime.utcnow()
last_heartbeat=datetime.now(datetime.UTC),
registration_time=datetime.now(datetime.UTC)
)
# Example usage

View File

@@ -6,7 +6,7 @@ import asyncio
import json
from typing import Dict, List, Optional, Tuple, Any, Callable
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from enum import Enum
import statistics
import uuid
@@ -132,7 +132,7 @@ class LoadBalancer:
def update_agent_metrics(self, agent_id: str, metrics: LoadMetrics):
"""Update agent load 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
self._update_performance_score(agent_id, metrics)
@@ -196,7 +196,7 @@ class LoadBalancer:
assignment = TaskAssignment(
task_id=task_id,
agent_id=selected_agent,
assigned_at=datetime.utcnow()
assigned_at=datetime.now(datetime.UTC)
)
# Record assignment
@@ -226,7 +226,7 @@ class LoadBalancer:
return
assignment = self.task_assignments[task_id]
assignment.completed_at = datetime.utcnow()
assignment.completed_at = datetime.now(datetime.UTC)
assignment.status = "completed"
assignment.success = success
assignment.response_time = response_time
@@ -580,7 +580,7 @@ class TaskDistributor:
"task_data": task_data,
"priority": priority,
"requirements": requirements,
"submitted_at": datetime.utcnow()
"submitted_at": datetime.now(datetime.UTC)
}
await self.priority_queues[priority].put(task_info)
@@ -612,7 +612,7 @@ class TaskDistributor:
async def _distribute_task(self, task_info: Dict[str, Any]):
"""Distribute a single task"""
start_time = datetime.utcnow()
start_time = datetime.now(datetime.UTC)
try:
# Assign task
@@ -648,7 +648,7 @@ class TaskDistributor:
finally:
# 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"]
self.distribution_stats["avg_distribution_time"] = (
(self.distribution_stats["avg_distribution_time"] * (total_distributed - 1) + distribution_time) / total_distributed

View File

@@ -5,7 +5,7 @@ Tests for Agent Communication Protocols
import sys
import pytest
import asyncio
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from unittest.mock import Mock, AsyncMock
from src.app.protocols.communication import (
@@ -63,12 +63,12 @@ class TestAgentMessage:
sender_id="agent-001",
receiver_id="agent-002",
message_type=MessageType.DIRECT,
timestamp=datetime.utcnow() - timedelta(seconds=400),
timestamp=datetime.now(datetime.UTC) - timedelta(seconds=400),
ttl=300
)
# 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
class TestHierarchicalProtocol:

View File

@@ -8,7 +8,7 @@ import asyncio
import aiohttp
import json
from typing import Dict, Any, List, Optional
from datetime import datetime
from datetime import datetime, UTC
class AITBCServiceIntegration:
"""Integration layer for AITBC services"""
@@ -110,7 +110,7 @@ class AgentServiceBridge:
self.active_agents[agent_id] = {
"config": agent_config,
"registration": registration_result,
"started_at": datetime.utcnow()
"started_at": datetime.now(datetime.UTC)
}
return True
else:
@@ -182,7 +182,7 @@ class AgentServiceBridge:
"volatility": "medium",
"recommendation": "hold"
},
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
return {"status": "success", "result": analysis_result}
@@ -221,7 +221,7 @@ class AgentServiceBridge:
"check_type": task_data.get("check_type", "basic"),
"status": "passed",
"checks_performed": ["kyc", "aml", "sanctions"],
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
return {"status": "success", "result": compliance_result}

View File

@@ -9,7 +9,7 @@ import json
import logging
import time
from typing import Dict, Any, List
from datetime import datetime
from datetime import datetime, UTC
import sys
import os
@@ -112,7 +112,7 @@ class ComplianceAgent:
"alert_type": "compliance_failure",
"severity": "high",
"details": result,
"timestamp": datetime.utcnow().isoformat()
"timestamp": datetime.now(datetime.UTC).isoformat()
}
# In a real implementation, this would send to alert system

View File

@@ -9,7 +9,7 @@ from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import json
import uuid
from datetime import datetime
from datetime import datetime, UTC
import sqlite3
from contextlib import contextmanager
from contextlib import asynccontextmanager
@@ -125,7 +125,7 @@ async def list_tasks(status: Optional[str] = None):
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {"status": "ok", "timestamp": datetime.utcnow()}
return {"status": "ok", "timestamp": datetime.now(datetime.UTC)}
if __name__ == "__main__":
import uvicorn

View File

@@ -5,7 +5,7 @@ Handles message creation, routing, and delivery between agents
import json
import uuid
from datetime import datetime
from datetime import datetime, UTC
from typing import Dict, Any, Optional, List
from enum import Enum
@@ -43,7 +43,7 @@ class MessageProtocol:
"receiver_id": receiver_id,
"message_type": message_type.value,
"content": content,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"status": "pending"
}
@@ -54,7 +54,7 @@ class MessageProtocol:
"""Send a message to the receiver"""
try:
message["status"] = "sent"
message["sent_timestamp"] = datetime.utcnow().isoformat()
message["sent_timestamp"] = datetime.now(datetime.UTC).isoformat()
return True
except Exception:
message["status"] = "failed"
@@ -65,7 +65,7 @@ class MessageProtocol:
for message in self.messages:
if message["message_id"] == message_id:
message["status"] = "received"
message["received_timestamp"] = datetime.utcnow().isoformat()
message["received_timestamp"] = datetime.now(datetime.UTC).isoformat()
return message
return None

View File

@@ -4,7 +4,7 @@ Handles task creation, assignment, and tracking
"""
import uuid
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Dict, Any, Optional, List
from enum import Enum
@@ -42,8 +42,8 @@ class Task:
self.priority = priority
self.created_by = created_by or assigned_to
self.status = TaskStatus.PENDING
self.created_at = datetime.utcnow()
self.updated_at = datetime.utcnow()
self.created_at = datetime.now(datetime.UTC)
self.updated_at = datetime.now(datetime.UTC)
self.completed_at = None
self.result = None
self.error = None
@@ -94,10 +94,10 @@ class TaskManager:
return False
task.status = status
task.updated_at = datetime.utcnow()
task.updated_at = datetime.now(datetime.UTC)
if status == TaskStatus.COMPLETED:
task.completed_at = datetime.utcnow()
task.completed_at = datetime.now(datetime.UTC)
task.result = result
elif status == TaskStatus.FAILED:
task.error = error
@@ -120,7 +120,7 @@ class TaskManager:
def get_overdue_tasks(self, hours: int = 24) -> List[Task]:
"""Get tasks that are overdue"""
cutoff_time = datetime.utcnow() - timedelta(hours=hours)
cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours)
return [
task for task in self.tasks.values()
if task.status in [TaskStatus.PENDING, TaskStatus.IN_PROGRESS] and

View File

@@ -10,7 +10,7 @@ from typing import List, Optional, Dict, Any
import json
import time
import uuid
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
import sqlite3
from contextlib import contextmanager
from contextlib import asynccontextmanager
@@ -144,7 +144,7 @@ async def list_agents(
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {"status": "ok", "timestamp": datetime.utcnow()}
return {"status": "ok", "timestamp": datetime.now(datetime.UTC)}
if __name__ == "__main__":
import uvicorn

View File

@@ -7,7 +7,7 @@ Basic AI-powered trading and analytics
import asyncio
import json
import numpy as np
from datetime import datetime
from datetime import datetime, UTC
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Dict, Any, List
@@ -58,7 +58,7 @@ class SimpleAITradingEngine:
'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]:
@@ -90,7 +90,7 @@ class SimpleAITradingEngine:
'quantity': quantity,
'price': analysis['current_price'],
'reasoning': f"Signal strength: {signal_strength:.3f}",
'timestamp': datetime.utcnow()
'timestamp': datetime.now(datetime.UTC)
}
# Global AI engine
@@ -104,7 +104,7 @@ async def analyze_market(request: AnalysisRequest):
return {
"status": "success",
"analysis": analysis,
"timestamp": datetime.utcnow()
"timestamp": datetime.now(datetime.UTC)
}
except Exception as e:
return {"status": "error", "message": "Analysis failed"}
@@ -118,7 +118,7 @@ async def execute_ai_trade(request: TradingRequest):
return {
"status": "success",
"decision": decision,
"timestamp": datetime.utcnow()
"timestamp": datetime.now(datetime.UTC)
}
except Exception as e:
return {"status": "error", "message": "Analysis failed"}
@@ -136,7 +136,7 @@ async def predict_market(symbol: str):
"risk": analysis['ai_predictions']['risk_assessment'],
"sentiment": analysis['ai_predictions']['sentiment_analysis']
},
"timestamp": datetime.utcnow()
"timestamp": datetime.now(datetime.UTC)
}
except Exception as e:
return {"status": "error", "message": "Analysis failed"}
@@ -152,7 +152,7 @@ async def get_ai_dashboard():
'total_volume': np.random.uniform(100000, 1000000),
'active_symbols': len(symbols),
'ai_models_active': 3,
'last_update': datetime.utcnow()
'last_update': datetime.now(datetime.UTC)
},
'symbol_analysis': {}
}
@@ -169,7 +169,7 @@ async def get_ai_dashboard():
return {
"status": "success",
"dashboard": dashboard_data,
"timestamp": datetime.utcnow()
"timestamp": datetime.now(datetime.UTC)
}
except Exception as e:
return {"status": "error", "message": "Analysis failed"}
@@ -192,13 +192,13 @@ async def get_ai_status():
"risk_assessment",
"sentiment_analysis"
],
"timestamp": datetime.utcnow()
"timestamp": datetime.now(datetime.UTC)
}
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {"status": "ok", "timestamp": datetime.utcnow()}
return {"status": "ok", "timestamp": datetime.now(datetime.UTC)}
if __name__ == "__main__":
import uvicorn

View File

@@ -5,7 +5,7 @@ import sys
import sys
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
from datetime import datetime
from datetime import datetime, UTC
# 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},
'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')
@@ -155,7 +155,7 @@ async def test_signal_strength_boundary_buy():
'risk_assessment': {'risk_score': 0.0, 'volatility': 0.01},
'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')

View File

@@ -4,7 +4,7 @@ import pytest
import sys
import sys
from pathlib import Path
from datetime import datetime
from datetime import datetime, UTC
from unittest.mock import Mock, patch, MagicMock
from fastapi.testclient import TestClient
@@ -98,7 +98,7 @@ def test_get_ai_dashboard_endpoint():
'risk_assessment': {'risk_score': 0.5, 'volatility': 0.03},
'sentiment_analysis': {'sentiment_score': 0.5, 'overall_sentiment': 'bullish'}
},
'timestamp': datetime.utcnow()
'timestamp': datetime.now(datetime.UTC)
}
mock_decision.return_value = {
@@ -108,7 +108,7 @@ def test_get_ai_dashboard_endpoint():
'quantity': 500,
'price': 0.005,
'reasoning': 'Test reasoning',
'timestamp': datetime.utcnow()
'timestamp': datetime.now(datetime.UTC)
}
response = client.get("/api/ai/dashboard")

View File

@@ -8,7 +8,7 @@ sys.path.insert(0, 'src')
from aitbc_chain.database import session_scope, init_db
from aitbc_chain.models import Block
from datetime import datetime
from datetime import datetime, UTC
import hashlib
def compute_block_hash(height: int, parent_hash: str, timestamp: datetime) -> str:
@@ -31,7 +31,7 @@ def create_genesis():
return
# Create genesis block
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
genesis_hash = compute_block_hash(0, "0x00", timestamp)
genesis = Block(
height=0,

View File

@@ -1,11 +1,11 @@
from aitbc_chain.database import session_scope, init_db
from aitbc_chain.models import Account
from datetime import datetime
from datetime import datetime, UTC
def fix():
init_db()
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.commit()
print("Added aitbc1genesis to mainnet")

View File

@@ -18,7 +18,7 @@ import base64
import os
import sys
from pathlib import Path
from datetime import datetime
from datetime import datetime, UTC
from typing import Dict, List, Any, Optional
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["balance"],
alloc["nonce"],
datetime.utcnow().isoformat()
datetime.now(datetime.UTC).isoformat()
)
)

View File

@@ -2,7 +2,7 @@ import asyncio
import hashlib
import json
import re
from datetime import datetime
from datetime import datetime, UTC
from pathlib import Path
from typing import Callable, ContextManager, Optional
@@ -168,7 +168,7 @@ class PoAProposer:
head = self._fetch_chain_head()
if head is None:
return
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
elapsed = (now - head.timestamp).total_seconds()
sleep_for = max(self._config.interval_seconds - elapsed, 0.1)
if sleep_for <= 0:
@@ -201,7 +201,7 @@ class PoAProposer:
elif block_generation_mode == "hybrid":
# Hybrid mode: check heartbeat interval
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:
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")
@@ -224,9 +224,9 @@ class PoAProposer:
if head is not None:
next_height = head.height + 1
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
max_txs = self._config.max_txs_per_block

View File

@@ -8,7 +8,7 @@ of agent compromise.
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
import json
from eth_account import Account
from eth_utils import to_checksum_address
@@ -37,7 +37,7 @@ class AgentSecurityProfile:
def __post_init__(self):
if self.created_at is None:
self.created_at = datetime.utcnow()
self.created_at = datetime.now(datetime.UTC)
class AgentWalletSecurity:
@@ -423,7 +423,7 @@ class AgentWalletSecurity:
def _log_security_event(self, **kwargs):
"""Log a security event"""
event = {
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
**kwargs
}
self.security_events.append(event)
@@ -469,7 +469,7 @@ class AgentWalletSecurity:
return {
"status": "disabled",
"agent_address": agent_address,
"disabled_at": datetime.utcnow().isoformat(),
"disabled_at": datetime.now(datetime.UTC).isoformat(),
"guardian": guardian_address
}
@@ -527,7 +527,7 @@ def generate_security_report() -> Dict:
recent_events = agent_wallet_security.get_security_events(limit=20)
return {
"generated_at": datetime.utcnow().isoformat(),
"generated_at": datetime.now(datetime.UTC).isoformat(),
"summary": {
"total_protected_agents": total_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_patterns": suspicious_patterns,
"analysis_period_hours": hours,
"analyzed_at": datetime.utcnow().isoformat()
"analyzed_at": datetime.now(datetime.UTC).isoformat()
}

View File

@@ -12,7 +12,7 @@ wallets from unlimited spending in case of compromise. It provides:
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
import json
import os
import sqlite3
@@ -248,7 +248,7 @@ class GuardianContract:
def _get_spent_in_period(self, period: str, timestamp: datetime = None) -> int:
"""Calculate total spent in given period"""
if timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
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]:
"""Check if amount exceeds spending limits"""
if timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
# Check per-transaction limit
if amount > self.config.limits.per_transaction:
@@ -350,7 +350,7 @@ class GuardianContract:
"to": to_address,
"amount": amount,
"data": data,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"nonce": self.nonce,
"status": "pending"
}
@@ -360,7 +360,7 @@ class GuardianContract:
# Check if time lock is required
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["status"] = "time_locked"
@@ -406,7 +406,7 @@ class GuardianContract:
# Check if operation is time locked
if operation["status"] == "time_locked":
unlock_time = datetime.fromisoformat(operation["unlock_time"])
if datetime.utcnow() < unlock_time:
if datetime.now(datetime.UTC) < unlock_time:
return {
"status": "error",
"reason": f"Operation locked until {unlock_time.isoformat()}"
@@ -432,7 +432,7 @@ class GuardianContract:
"amount": operation["amount"],
"data": operation.get("data", ""),
"timestamp": operation["timestamp"],
"executed_at": datetime.utcnow().isoformat(),
"executed_at": datetime.now(datetime.UTC).isoformat(),
"status": "completed",
"nonce": operation["nonce"]
}
@@ -479,7 +479,7 @@ class GuardianContract:
return {
"status": "paused",
"paused_at": datetime.utcnow().isoformat(),
"paused_at": datetime.now(datetime.UTC).isoformat(),
"guardian": guardian_address,
"message": "Emergency pause activated - all operations halted"
}
@@ -513,7 +513,7 @@ class GuardianContract:
return {
"status": "unpaused",
"unpaused_at": datetime.utcnow().isoformat(),
"unpaused_at": datetime.now(datetime.UTC).isoformat(),
"message": "Emergency pause lifted - operations resumed"
}
@@ -541,13 +541,13 @@ class GuardianContract:
"status": "updated",
"old_limits": old_limits,
"new_limits": new_limits,
"updated_at": datetime.utcnow().isoformat(),
"updated_at": datetime.now(datetime.UTC).isoformat(),
"guardian": guardian_address
}
def get_spending_status(self) -> Dict:
"""Get current spending status and limits"""
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
return {
"agent_address": self.agent_address,

View File

@@ -5,7 +5,7 @@ Fixes the critical vulnerability where spending limits were lost on restart
from typing import Dict, List, Optional, Tuple
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.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
@@ -112,7 +112,7 @@ class PersistentSpendingTracker:
Total amount spent in period
"""
if timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
period_key = self._get_period_key(timestamp, period)
agent_address = to_checksum_address(agent_address)
@@ -140,7 +140,7 @@ class PersistentSpendingTracker:
True if recorded successfully
"""
if timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
agent_address = to_checksum_address(agent_address)
@@ -184,7 +184,7 @@ class PersistentSpendingTracker:
Spending check result
"""
if timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
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.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.updated_at = datetime.utcnow()
limits.updated_at = datetime.now(datetime.UTC)
limits.updated_by = guardian_address
else:
limits = SpendingLimit(
@@ -323,7 +323,7 @@ class PersistentSpendingTracker:
per_week=new_limits.get("per_week", 100000.0),
time_lock_threshold=new_limits.get("time_lock_threshold", 5000.0),
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
)
session.add(limits)
@@ -361,7 +361,7 @@ class PersistentSpendingTracker:
if existing:
existing.is_active = True
existing.added_at = datetime.utcnow()
existing.added_at = datetime.now(datetime.UTC)
existing.added_by = added_by
else:
auth = GuardianAuthorization(
@@ -369,7 +369,7 @@ class PersistentSpendingTracker:
agent_address=agent_address,
guardian_address=guardian_address,
is_active=True,
added_at=datetime.utcnow(),
added_at=datetime.now(datetime.UTC),
added_by=added_by
)
session.add(auth)
@@ -415,7 +415,7 @@ class PersistentSpendingTracker:
Spending summary
"""
agent_address = to_checksum_address(agent_address)
now = datetime.utcnow()
now = datetime.now(datetime.UTC)
# Get current spending
current_spent = {

View File

@@ -1,7 +1,7 @@
"""Cross-chain synchronization for testing multi-chain scenarios."""
import asyncio
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List
@@ -18,7 +18,7 @@ class CrossChainSync:
self.sync_status[chain] = {
"synced": True,
"height": 0,
"last_sync": datetime.utcnow().isoformat(),
"last_sync": datetime.now(datetime.UTC).isoformat(),
}
@@ -36,5 +36,5 @@ class MultiChainConsensus:
"consensus_reached": True,
"height": 0,
"validators": 1,
"last_consensus": datetime.utcnow().isoformat(),
"last_consensus": datetime.now(datetime.UTC).isoformat(),
}

View File

@@ -2,12 +2,12 @@ import logging
import sys
from logging.handlers import RotatingFileHandler
import json
from datetime import datetime
from datetime import datetime, UTC
class JsonFormatter(logging.Formatter):
def format(self, record):
log_record = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
"level": record.levelname,
"logger": record.name,
"message": record.getMessage()

View File

@@ -4,7 +4,7 @@ import asyncio
import json
import time
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 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,
recipient=recipient_addr,
payload=tx_data.get("payload", {}),
created_at=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
nonce=tx_nonce,
value=amount,
fee=fee,
status="pending",
timestamp=datetime.utcnow().isoformat()
timestamp=datetime.now(datetime.UTC).isoformat()
)
session.add(transaction)
@@ -700,9 +700,9 @@ async def import_block(block_data: dict) -> Dict[str, Any]:
try:
timestamp = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
except ValueError:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
elif timestamp is None:
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
with session_scope(chain_id) as session:
# 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)")
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(
chain_id=chain_id,
height=block_data["height"],

View File

@@ -11,7 +11,7 @@ from typing import Dict, List, Optional, Tuple
from sqlmodel import Session, select
from sqlalchemy import select, text
from datetime import datetime
from datetime import datetime, UTC
from ..models import Account, Transaction, Receipt
from ..logger import get_logger
@@ -242,7 +242,7 @@ class StateTransition:
# Update receipt status
receipt.status = "claimed"
receipt.claimed_at = datetime.utcnow()
receipt.claimed_at = datetime.now(datetime.UTC)
receipt.claimed_by = sender_addr
logger.info(

View File

@@ -7,7 +7,7 @@ import hashlib
import hmac
import time
from dataclasses import dataclass
from datetime import datetime
from datetime import datetime, UTC
from typing import Any, Dict, List, Optional, Tuple
import httpx
@@ -397,9 +397,9 @@ class ChainSync:
"""Append a block to the chain tip."""
timestamp_str = block_data.get("timestamp", "")
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):
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
tx_count = block_data.get("tx_count", 0)
if transactions:

View File

@@ -5,7 +5,7 @@ from __future__ import annotations
import sys
import asyncio
import pytest
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from unittest.mock import AsyncMock, Mock, patch
from typing import Generator
@@ -192,7 +192,7 @@ class TestPoAProposer:
hash="0xparent",
parent_hash="0x00",
proposer="previous-proposer",
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
tx_count=0,
)
test_db.add(parent)
@@ -231,16 +231,16 @@ class TestPoAProposer:
hash="0xhead",
parent_hash="0x00",
proposer="test-proposer",
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
tx_count=0,
)
test_db.add(head)
test_db.commit()
# Should wait for the configured interval
start_time = datetime.utcnow()
start_time = datetime.now(datetime.UTC)
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)
assert elapsed >= 0.1
@@ -255,7 +255,7 @@ class TestPoAProposer:
hash="0xhead",
parent_hash="0x00",
proposer="test-proposer",
timestamp=datetime.utcnow() - timedelta(seconds=10),
timestamp=datetime.now(datetime.UTC) - timedelta(seconds=10),
tx_count=0,
)
test_db.add(head)
@@ -263,9 +263,9 @@ class TestPoAProposer:
# Set stop event and wait
proposer._stop_event.set()
start_time = datetime.utcnow()
start_time = datetime.now(datetime.UTC)
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
assert elapsed < 0.1
@@ -290,7 +290,7 @@ class TestPoAProposer:
"""Test block hash computation."""
height = 1
parent_hash = "0xparent"
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
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."""
height = 1
parent_hash = "0xparent"
timestamp = datetime.utcnow()
timestamp = datetime.now(datetime.UTC)
mock_tx = Mock()
mock_tx.tx_hash = "0xtx"
@@ -324,7 +324,7 @@ class TestPoAProposer:
hash="0xexisting",
parent_hash="0x00",
proposer="test-proposer",
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
tx_count=0,
)
test_db.add(block)

View File

@@ -6,7 +6,7 @@ import sys
import pytest
import tempfile
import shutil
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from pathlib import Path
from unittest.mock import patch, Mock
from typing import Generator
@@ -113,7 +113,7 @@ class TestGuardianContract:
def test_spending_limit_check_hourly(self, guardian_contract: GuardianContract) -> None:
"""Test hourly spending limit."""
# Add some spending history
base_time = datetime.utcnow()
base_time = datetime.now(datetime.UTC)
guardian_contract.spending_history = [
{
"operation_id": "op1",
@@ -139,7 +139,7 @@ class TestGuardianContract:
def test_spending_limit_check_daily(self, guardian_contract: GuardianContract) -> None:
"""Test daily spending limit."""
# Add spending history across the day
base_time = datetime.utcnow()
base_time = datetime.now(datetime.UTC)
guardian_contract.spending_history = [
{
"operation_id": "op1",
@@ -165,7 +165,7 @@ class TestGuardianContract:
def test_spending_limit_check_weekly(self, guardian_contract: GuardianContract) -> None:
"""Test weekly spending limit."""
# Add spending history across the week
base_time = datetime.utcnow()
base_time = datetime.now(datetime.UTC)
guardian_contract.spending_history = [
{
"operation_id": "op1",

View File

@@ -4,7 +4,7 @@ import hashlib
import time
import sys
import pytest
from datetime import datetime
from datetime import datetime, UTC
from contextlib import contextmanager
from sqlmodel import Session, SQLModel, create_engine, select
@@ -68,7 +68,7 @@ class TestProposerSignatureValidator:
def test_valid_block(self):
v = ProposerSignatureValidator()
ts = datetime.utcnow()
ts = datetime.now(datetime.UTC)
bh = _make_block_hash("test", 1, "0x00", ts)
ok, reason = v.validate_block_signature({
"height": 1, "hash": bh, "parent_hash": "0x00",
@@ -81,7 +81,7 @@ class TestProposerSignatureValidator:
v = ProposerSignatureValidator()
ok, reason = v.validate_block_signature({
"height": 1, "hash": "0x" + "a" * 64, "parent_hash": "0x00",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
})
assert ok is False
assert "Missing proposer" in reason
@@ -90,7 +90,7 @@ class TestProposerSignatureValidator:
v = ProposerSignatureValidator()
ok, reason = v.validate_block_signature({
"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 "Invalid block hash" in reason
@@ -99,14 +99,14 @@ class TestProposerSignatureValidator:
v = ProposerSignatureValidator()
ok, reason = v.validate_block_signature({
"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 "Invalid hash length" in reason
def test_untrusted_proposer_rejected(self):
v = ProposerSignatureValidator(trusted_proposers=["node-a", "node-b"])
ts = datetime.utcnow()
ts = datetime.now(datetime.UTC)
bh = _make_block_hash("test", 1, "0x00", ts)
ok, reason = v.validate_block_signature({
"height": 1, "hash": bh, "parent_hash": "0x00",
@@ -117,7 +117,7 @@ class TestProposerSignatureValidator:
def test_trusted_proposer_accepted(self):
v = ProposerSignatureValidator(trusted_proposers=["node-a"])
ts = datetime.utcnow()
ts = datetime.now(datetime.UTC)
bh = _make_block_hash("test", 1, "0x00", ts)
ok, reason = v.validate_block_signature({
"height": 1, "hash": bh, "parent_hash": "0x00",
@@ -147,7 +147,7 @@ class TestChainSyncAppend:
def test_append_to_empty_chain(self, session_factory):
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)
result = sync.import_block({
"height": 0, "hash": bh, "parent_hash": "0x00",
@@ -232,7 +232,7 @@ class TestChainSyncSignatureValidation:
def test_untrusted_proposer_rejected_on_import(self, session_factory):
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
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)
result = sync.import_block({
"height": 0, "hash": bh, "parent_hash": "0x00",
@@ -244,7 +244,7 @@ class TestChainSyncSignatureValidation:
def test_trusted_proposer_accepted_on_import(self, session_factory):
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
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)
result = sync.import_block({
"height": 0, "hash": bh, "parent_hash": "0x00",
@@ -255,7 +255,7 @@ class TestChainSyncSignatureValidation:
def test_validation_disabled(self, session_factory):
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
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)
result = sync.import_block({
"height": 0, "hash": bh, "parent_hash": "0x00",
@@ -295,7 +295,7 @@ class TestSyncMetrics:
def test_accepted_block_increments_metrics(self, session_factory):
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)
sync.import_block({
"height": 0, "hash": bh, "parent_hash": "0x00",
@@ -308,7 +308,7 @@ class TestSyncMetrics:
def test_rejected_block_increments_metrics(self, session_factory):
validator = ProposerSignatureValidator(trusted_proposers=["node-a"])
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)
sync.import_block({
"height": 0, "hash": bh, "parent_hash": "0x00",

View File

@@ -5,7 +5,7 @@ Handles KYC/AML, regulatory compliance, and monitoring
import asyncio
import json
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from pathlib import Path
from typing import Dict, Any, List, Optional
from fastapi import FastAPI, HTTPException
@@ -68,7 +68,7 @@ async def root():
return {
"service": "AITBC Compliance Service",
"status": "running",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"version": "1.0.0"
}
@@ -97,7 +97,7 @@ async def submit_kyc(kyc_request: KYCRequest):
"document_number": kyc_request.document_number,
"address": kyc_request.address,
"status": "pending",
"submitted_at": datetime.utcnow().isoformat(),
"submitted_at": datetime.now(datetime.UTC).isoformat(),
"reviewed_at": None,
"approved_at": None,
"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)
kyc_record["status"] = "approved"
kyc_record["reviewed_at"] = datetime.utcnow().isoformat()
kyc_record["approved_at"] = datetime.utcnow().isoformat()
kyc_record["reviewed_at"] = datetime.now(datetime.UTC).isoformat()
kyc_record["approved_at"] = datetime.now(datetime.UTC).isoformat()
kyc_record["risk_score"] = "low"
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")
async def create_compliance_report(report: ComplianceReport):
"""Create a compliance report"""
report_id = f"report_{int(datetime.utcnow().timestamp())}"
report_id = f"report_{int(datetime.now(datetime.UTC).timestamp())}"
compliance_record = {
"report_id": report_id,
@@ -155,7 +155,7 @@ async def create_compliance_report(report: ComplianceReport):
"severity": report.severity,
"details": report.details,
"status": "open",
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"assigned_to": None,
"resolved_at": None,
"resolution": None
@@ -195,7 +195,7 @@ async def monitor_transaction(transaction: TransactionMonitoring):
"currency": transaction.currency,
"counterparty": transaction.counterparty,
"timestamp": transaction.timestamp.isoformat(),
"monitored_at": datetime.utcnow().isoformat(),
"monitored_at": datetime.now(datetime.UTC).isoformat(),
"risk_score": calculate_transaction_risk(transaction),
"flags": [],
"status": "monitored"
@@ -232,7 +232,7 @@ async def list_monitored_transactions():
@app.post("/api/v1/rules/create")
async def create_compliance_rule(rule_data: Dict[str, Any]):
"""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_id": rule_id,
@@ -243,7 +243,7 @@ async def create_compliance_rule(rule_data: Dict[str, Any]):
"actions": rule_data.get("actions", []),
"severity": rule_data.get("severity", "medium"),
"active": True,
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"trigger_count": 0
}
@@ -294,7 +294,7 @@ async def compliance_dashboard():
},
"risk_distribution": get_risk_distribution(),
"recent_activity": get_recent_activity(),
"generated_at": datetime.utcnow().isoformat()
"generated_at": datetime.now(datetime.UTC).isoformat()
}
# Helper functions
@@ -337,7 +337,7 @@ def check_suspicious_patterns(transaction: TransactionMonitoring) -> List[str]:
recent_transactions = [t for t in user_transactions
if datetime.fromisoformat(t["monitored_at"]) >
datetime.utcnow() - timedelta(hours=1)]
datetime.now(datetime.UTC) - timedelta(hours=1)]
if len(recent_transactions) > 5:
flags.append("rapid_transactions")
@@ -385,7 +385,7 @@ def get_recent_activity() -> List[Dict]:
recent_kyc = [r for r in kyc_records.values()
if r.get("approved_at") and
datetime.fromisoformat(r["approved_at"]) >
datetime.utcnow() - timedelta(hours=24)]
datetime.now(datetime.UTC) - timedelta(hours=24)]
for kyc in recent_kyc[:5]:
activities.append({
@@ -397,7 +397,7 @@ def get_recent_activity() -> List[Dict]:
# Recent compliance reports
recent_reports = [r for r in compliance_reports.values()
if datetime.fromisoformat(r["created_at"]) >
datetime.utcnow() - timedelta(hours=24)]
datetime.now(datetime.UTC) - timedelta(hours=24)]
for report in recent_reports[:5]:
activities.append({
@@ -418,7 +418,7 @@ async def periodic_compliance_checks():
await asyncio.sleep(300) # Check every 5 minutes
# Check for expired KYC records
current_time = datetime.utcnow()
current_time = datetime.now(datetime.UTC)
for user_id, kyc_record in kyc_records.items():
if kyc_record["status"] == "approved":
approved_time = datetime.fromisoformat(kyc_record["approved_at"])

View File

@@ -6,7 +6,7 @@ import sys
from pathlib import Path
from unittest.mock import Mock, patch
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
@@ -62,7 +62,7 @@ def test_transaction_monitoring_zero_amount():
amount=0.0,
currency="BTC",
counterparty="counterparty1",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
assert tx.amount == 0.0
@@ -76,7 +76,7 @@ def test_transaction_monitoring_negative_amount():
amount=-1000.0,
currency="BTC",
counterparty="counterparty1",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
assert tx.amount == -1000.0

View File

@@ -6,7 +6,7 @@ import sys
from pathlib import Path
from unittest.mock import Mock, patch
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
@@ -171,7 +171,7 @@ def test_monitor_transaction():
amount=1000.0,
currency="BTC",
counterparty="counterparty1",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
response = client.post("/api/v1/monitoring/transaction", json=tx.model_dump(mode='json'))
assert response.status_code == 200
@@ -190,7 +190,7 @@ def test_monitor_suspicious_transaction():
amount=100000.0,
currency="BTC",
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'))
assert response.status_code == 200

View File

@@ -5,7 +5,7 @@ import sys
import sys
from pathlib import Path
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
@@ -62,7 +62,7 @@ def test_transaction_monitoring_model():
amount=1000.0,
currency="BTC",
counterparty="counterparty1",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
assert tx.transaction_id == "tx123"
assert tx.user_id == "user123"
@@ -125,7 +125,7 @@ def test_check_suspicious_patterns_high_value():
amount=100000.0,
currency="BTC",
counterparty="counterparty1",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
flags = check_suspicious_patterns(tx)
assert "high_value_transaction" in flags
@@ -140,7 +140,7 @@ def test_check_suspicious_patterns_high_risk_counterparty():
amount=1000.0,
currency="BTC",
counterparty="high_risk_entity_1",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
flags = check_suspicious_patterns(tx)
assert "high_risk_counterparty" in flags
@@ -155,7 +155,7 @@ def test_check_suspicious_patterns_none():
amount=1000.0,
currency="BTC",
counterparty="safe_counterparty",
timestamp=datetime.utcnow()
timestamp=datetime.now(datetime.UTC)
)
flags = check_suspicious_patterns(tx)
assert len(flags) == 0

View File

@@ -6,7 +6,7 @@ Demonstrates basic usage of the Agent Identity SDK
import asyncio
import json
from datetime import datetime
from datetime import datetime, UTC
from typing import Dict, Any
# Import SDK components
@@ -94,7 +94,7 @@ async def basic_identity_example():
"agent_id": identity.agent_id,
"chain_id": mapping.chain_id,
"chain_address": mapping.chain_address,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"verification_method": "demo"
}
@@ -234,7 +234,7 @@ async def advanced_transaction_example():
"description": "Updated description with new capabilities",
"metadata": {
"version": "1.1.0",
"last_updated": datetime.utcnow().isoformat()
"last_updated": datetime.now(datetime.UTC).isoformat()
},
"tags": ["demo", "ai", "updated"]
}

View File

@@ -6,7 +6,7 @@ Complete deployment procedures for the agent orchestration system
import asyncio
import json
from aitbc.logging import get_logger
from datetime import datetime
from datetime import datetime, UTC
from typing import Dict, List, Optional, Any
from pathlib import Path
@@ -30,7 +30,7 @@ class AgentOrchestrationDeployment:
"""Deploy complete agent orchestration system to production"""
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",
"steps_completed": [],
"steps_failed": [],

View File

@@ -6,7 +6,7 @@ Ongoing maintenance, monitoring, and enhancement of the complete system
import asyncio
import json
from aitbc.logging import get_logger
from datetime import datetime
from datetime import datetime, UTC
from typing import Dict, List, Optional, Any
from enum import Enum
@@ -73,7 +73,7 @@ class SystemMaintenanceManager:
"""Perform comprehensive maintenance cycle"""
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",
"categories_completed": [],
"enhancements_implemented": [],

View File

@@ -5,7 +5,7 @@ Provides unified agent identification and cross-chain compatibility
import hashlib
import json
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Any
from uuid import uuid4
@@ -90,7 +90,7 @@ class AgentIdentityCore:
if hasattr(identity, field):
setattr(identity, field, value)
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
self.session.commit()
self.session.refresh(identity)
@@ -133,7 +133,7 @@ class AgentIdentityCore:
# Update identity's supported chains
if chain_id not in identity.supported_chains:
identity.supported_chains.append(str(chain_id))
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
self.session.commit()
logger.info(f"Registered cross-chain identity: {identity_id} -> {chain_id}:{chain_address}")
@@ -190,7 +190,7 @@ class AgentIdentityCore:
# Update mapping verification status
mapping.is_verified = True
mapping.verified_at = datetime.utcnow()
mapping.verified_at = datetime.now(datetime.UTC)
mapping.verification_proof = proof_data
self.session.commit()
@@ -198,7 +198,7 @@ class AgentIdentityCore:
identity = await self.get_identity(identity_id)
if identity and chain_id == identity.primary_chain:
identity.is_verified = True
identity.verified_at = datetime.utcnow()
identity.verified_at = datetime.now(datetime.UTC)
identity.verification_level = verification_type
self.session.commit()
@@ -242,7 +242,7 @@ class AgentIdentityCore:
else:
setattr(mapping, field, value)
mapping.updated_at = datetime.utcnow()
mapping.updated_at = datetime.now(datetime.UTC)
self.session.commit()
self.session.refresh(mapping)
@@ -260,11 +260,11 @@ class AgentIdentityCore:
# Update identity status
identity.status = IdentityStatus.REVOKED
identity.is_verified = False
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
# Add revocation reason to identity_data
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()
@@ -280,11 +280,11 @@ class AgentIdentityCore:
# Update identity status
identity.status = IdentityStatus.SUSPENDED
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
# Add suspension reason to identity_data
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()
@@ -303,7 +303,7 @@ class AgentIdentityCore:
# Update identity status
identity.status = IdentityStatus.ACTIVE
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
# Clear suspension 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
identity.reputation_score = base_score * (0.7 + 0.3 * volume_factor)
identity.last_activity = datetime.utcnow()
identity.updated_at = datetime.utcnow()
identity.last_activity = datetime.now(datetime.UTC)
identity.updated_at = datetime.now(datetime.UTC)
self.session.commit()
self.session.refresh(identity)
@@ -452,7 +452,7 @@ class AgentIdentityCore:
"owner_address": identity.owner_address,
"chain_id": chain_id,
"chain_address": mapping.chain_address,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"nonce": str(uuid4()),
}
@@ -463,5 +463,5 @@ class AgentIdentityCore:
return {
"proof_data": proof_data,
"proof_hash": proof_hash,
"expires_at": (datetime.utcnow() + timedelta(hours=24)).isoformat(),
"expires_at": (datetime.now(datetime.UTC) + timedelta(hours=24)).isoformat(),
}

View File

@@ -3,7 +3,7 @@ Agent Identity Manager Implementation
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 uuid import uuid4
@@ -171,7 +171,7 @@ class AgentIdentityManager:
# Update identity reputation
await self.core.update_reputation(agent_id, True, 0) # This will recalculate based on new data
identity.reputation_score = aggregated_score
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
self.session.commit()
else:
aggregated_score = identity.reputation_score
@@ -181,7 +181,7 @@ class AgentIdentityManager:
"aggregated_reputation": aggregated_score,
"chain_reputations": reputation_scores,
"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:
@@ -449,12 +449,12 @@ class AgentIdentityManager:
"supported_chains": supported_chains,
"cleaned_verifications": cleaned_count,
"issues": issues,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
except Exception as 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]:
"""Export agent identity data for backup or migration"""
@@ -469,7 +469,7 @@ class AgentIdentityManager:
# Prepare export data
export_data = {
"export_version": "1.0",
"export_timestamp": datetime.utcnow().isoformat(),
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
"agent_id": agent_id,
"identity": summary["identity"],
"cross_chain_mappings": summary["cross_chain"]["mappings"],
@@ -541,7 +541,7 @@ class AgentIdentityManager:
"identity_id": identity.id,
"import_successful": True,
"restored_mappings": len(chain_mappings),
"import_timestamp": datetime.utcnow().isoformat(),
"import_timestamp": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:

View File

@@ -5,7 +5,7 @@ Registry for cross-chain agent identity mapping and synchronization
import hashlib
import json
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Any
from uuid import uuid4
@@ -97,7 +97,7 @@ class CrossChainRegistry:
registration_results.append({"chain_id": chain_id, "chain_address": chain_address, "error": str(e)})
# Update identity
identity.updated_at = datetime.utcnow()
identity.updated_at = datetime.now(datetime.UTC)
self.session.commit()
return {
@@ -143,7 +143,7 @@ class CrossChainRegistry:
old_address = mapping.chain_address
mapping.chain_address = new_address.lower()
mapping.updated_at = datetime.utcnow()
mapping.updated_at = datetime.now(datetime.UTC)
# Reset verification status since address changed
mapping.is_verified = False
@@ -195,7 +195,7 @@ class CrossChainRegistry:
proof_hash=proof_hash,
proof_data=proof_data,
verification_result="approved",
expires_at=datetime.utcnow() + timedelta(days=30),
expires_at=datetime.now(datetime.UTC) + timedelta(days=30),
)
self.session.add(verification)
@@ -204,7 +204,7 @@ class CrossChainRegistry:
# Update mapping verification status
mapping.is_verified = True
mapping.verified_at = datetime.utcnow()
mapping.verified_at = datetime.now(datetime.UTC)
mapping.verification_proof = proof_data
self.session.commit()
@@ -212,7 +212,7 @@ class CrossChainRegistry:
if self._is_higher_verification_level(verification_type, identity.verification_level):
identity.verification_level = verification_type
identity.is_verified = True
identity.verified_at = datetime.utcnow()
identity.verified_at = datetime.now(datetime.UTC)
self.session.commit()
logger.info(f"Verified cross-chain identity: {identity_id} on chain {chain_id}")
@@ -229,14 +229,14 @@ class CrossChainRegistry:
mapping.is_verified = False
mapping.verified_at = None
mapping.verification_proof = None
mapping.updated_at = datetime.utcnow()
mapping.updated_at = datetime.now(datetime.UTC)
# Add revocation to metadata
if not mapping.chain_metadata:
mapping.chain_metadata = {}
mapping.chain_metadata["verification_revoked"] = True
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()
@@ -453,7 +453,7 @@ class CrossChainRegistry:
async def cleanup_expired_verifications(self) -> int:
"""Clean up expired verification records"""
current_time = datetime.utcnow()
current_time = datetime.now(datetime.UTC)
# Find expired verifications
stmt = select(IdentityVerification).where(IdentityVerification.expires_at < current_time)

View File

@@ -4,7 +4,7 @@ Provides blockchain-agnostic wallet interface for agents
"""
from abc import ABC, abstractmethod
from datetime import datetime
from datetime import datetime, UTC
from decimal import Decimal
from typing import Any
@@ -69,7 +69,7 @@ class EthereumWalletAdapter(WalletAdapter):
"wallet_address": f"0x{'0' * 40}", # Mock address
"contract_address": f"0x{'1' * 40}", # Mock contract
"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:
@@ -91,7 +91,7 @@ class EthereumWalletAdapter(WalletAdapter):
"gas_price": "20000000000",
"status": "success",
"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]]:
@@ -105,7 +105,7 @@ class EthereumWalletAdapter(WalletAdapter):
"amount": "0.1",
"gas_used": "21000",
"block_number": 12344,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
]
@@ -269,7 +269,7 @@ class MultiChainWalletAdapter:
# Update wallet in database
wallet.total_spent += float(amount)
wallet.last_transaction = datetime.utcnow()
wallet.last_transaction = datetime.now(datetime.UTC)
wallet.transaction_count += 1
self.session.commit()
@@ -312,7 +312,7 @@ class MultiChainWalletAdapter:
if hasattr(wallet, field):
setattr(wallet, field, value)
wallet.updated_at = datetime.utcnow()
wallet.updated_at = datetime.now(datetime.UTC)
self.session.commit()
self.session.refresh(wallet)
@@ -338,7 +338,7 @@ class MultiChainWalletAdapter:
# Deactivate wallet
wallet.is_active = False
wallet.updated_at = datetime.utcnow()
wallet.updated_at = datetime.now(datetime.UTC)
self.session.commit()

View File

@@ -7,7 +7,7 @@ import hashlib
import json
import secrets
from abc import ABC, abstractmethod
from datetime import datetime
from datetime import datetime, UTC
from decimal import Decimal
from enum import StrEnum
from typing import Any
@@ -124,7 +124,7 @@ class EnhancedWalletAdapter(ABC):
"""Securely sign a message"""
try:
# 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)
message_to_sign = f"{message}:{timestamp}:{nonce}"
@@ -194,7 +194,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
"chain_type": self.chain_type.value,
"owner_address": owner_address,
"security_level": self.security_level.value,
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"status": WalletStatus.ACTIVE.value,
"security_config": security_config,
"nonce": 0,
@@ -227,7 +227,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
"chain_id": self.chain_id,
"eth_balance": eth_balance,
"token_balances": {},
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
# Get token balances if specified
@@ -304,7 +304,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
"gas_limit": gas_limit,
"gas_price": gas_price,
"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}")
@@ -331,7 +331,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
"gas_used": None,
"effective_gas_price": None,
"logs": [],
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
}
# Get transaction details
@@ -348,7 +348,7 @@ class EthereumWalletAdapter(EnhancedWalletAdapter):
"from": tx_data.get("from"),
"to": tx_data.get("to"),
"value": int(tx_data.get("value", "0x0"), 16),
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
}
return result

View File

@@ -3,7 +3,7 @@ Advanced Agent Performance Domain Models
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 typing import Any
from uuid import uuid4
@@ -206,7 +206,7 @@ class ResourceAllocation(SQLModel, table=True):
# Timestamps
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
allocation_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))

View File

@@ -6,7 +6,7 @@ Domain models for agent portfolio management, trading strategies, and risk asses
from __future__ import annotations
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from enum import StrEnum
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))
is_executed: bool = Field(default=False, index=True)
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)
@@ -278,4 +278,4 @@ class MarketCondition(SQLModel, table=True):
support_level: float = Field(default=0.0) # Support level
resistance_level: float = Field(default=0.0) # Resistance level
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))

View File

@@ -6,7 +6,7 @@ Domain models for automated market making, liquidity pools, and swap transaction
from __future__ import annotations
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from enum import StrEnum
from sqlalchemy import JSON, Column
@@ -122,7 +122,7 @@ class SwapTransaction(SQLModel, table=True):
gas_price: float | None = Field(default=None)
executed_at: datetime | None = Field(default=None, 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
# 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
time_adjustment: float = Field(default=0.0) # Time-based adjustment
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
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)
is_active: bool = Field(default=True, index=True)
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)
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)
resolved_at: datetime | None = Field(default=None)
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):
@@ -336,4 +336,4 @@ class ArbitrageOpportunity(SQLModel, table=True):
execution_tx_hash: str | None = Field(default=None)
actual_profit: float | None = Field(default=None)
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))

View File

@@ -6,7 +6,7 @@ Domain models for cross-chain asset transfers, bridge requests, and validator ma
from __future__ import annotations
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from enum import StrEnum
from sqlalchemy import JSON, Column
@@ -80,7 +80,7 @@ class BridgeRequest(SQLModel, table=True):
confirmed_at: datetime | None = Field(default=None)
completed_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
# 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
is_valid: bool = Field(default=False)
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)
@@ -291,7 +291,7 @@ class BridgeAlert(SQLModel, table=True):
resolved_at: datetime | None = Field(default=None)
resolution_notes: str | None = Field(default=None)
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):

View File

@@ -4,7 +4,7 @@ Defines various pricing strategies and their configurations for dynamic pricing
"""
from dataclasses import dataclass, field
from datetime import datetime
from datetime import datetime, UTC
from enum import StrEnum
from typing import Any
@@ -515,7 +515,7 @@ class StrategyOptimizer:
if strategy_id not in self.performance_history:
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
optimized_config = self._apply_optimization_rules(strategy_config, performance_data)

View File

@@ -4,7 +4,7 @@ Exception classes and error response schemas for AITBC coordinator
Provides structured error responses for consistent API error handling.
"""
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
from pydantic import BaseModel, Field
@@ -22,7 +22,7 @@ class ErrorResponse(BaseModel):
"""Standardized error response for all API errors."""
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")
class Config:

View File

@@ -5,7 +5,7 @@ Tenant context middleware for multi-tenant isolation
import hashlib
from collections.abc import Callable
from contextvars import ContextVar
from datetime import datetime
from datetime import datetime, UTC
from fastapi import HTTPException, Request, status
from sqlalchemy import and_, event, select
@@ -170,11 +170,11 @@ class TenantContextMiddleware(BaseHTTPMiddleware):
return None
# 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
# Update last used timestamp
api_key_record.last_used_at = datetime.utcnow()
api_key_record.last_used_at = datetime.now(datetime.UTC)
db.commit()
# Get tenant

View File

@@ -3,7 +3,7 @@ Repository layer for confidential transactions
"""
from base64 import b64decode
from datetime import datetime
from datetime import datetime, UTC
from sqlalchemy import and_, delete, select, update
from sqlalchemy.ext.asyncio import AsyncSession
@@ -131,7 +131,7 @@ class ParticipantKeyRepository:
stmt = (
update(ParticipantKeyDB)
.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)
@@ -309,7 +309,7 @@ class AuditAuthorizationRepository:
and_(
AuditAuthorizationDB.id == authorization_id,
AuditAuthorizationDB.active,
AuditAuthorizationDB.expires_at > datetime.utcnow(),
AuditAuthorizationDB.expires_at > datetime.now(datetime.UTC),
)
)
@@ -321,7 +321,7 @@ class AuditAuthorizationRepository:
stmt = (
update(AuditAuthorizationDB)
.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)
@@ -331,7 +331,7 @@ class AuditAuthorizationRepository:
async def cleanup_expired(self, session: AsyncSession) -> int:
"""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)
await session.commit()

View File

@@ -3,7 +3,7 @@ Cross-Chain Reputation Aggregator
Aggregates reputation data from multiple blockchains and normalizes scores
"""
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
from aitbc import get_logger
@@ -147,7 +147,7 @@ class CrossChainReputationAggregator:
{
"agent_id": agent_id,
"anomaly_type": "low_consistency",
"detected_at": datetime.utcnow(),
"detected_at": datetime.now(datetime.UTC),
"description": f"Low consistency score: {aggregation.consistency_score:.2f}",
"severity": "high" if aggregation.consistency_score < 0.5 else "medium",
"consistency_score": aggregation.consistency_score,
@@ -162,7 +162,7 @@ class CrossChainReputationAggregator:
{
"agent_id": agent_id,
"anomaly_type": "high_variance",
"detected_at": datetime.utcnow(),
"detected_at": datetime.now(datetime.UTC),
"description": f"High score variance: {aggregation.score_variance:.2f}",
"severity": "high" if aggregation.score_variance > 0.5 else "medium",
"score_variance": aggregation.score_variance,
@@ -180,7 +180,7 @@ class CrossChainReputationAggregator:
{
"agent_id": agent_id,
"anomaly_type": "missing_chain_data",
"detected_at": datetime.utcnow(),
"detected_at": datetime.now(datetime.UTC),
"description": f"Missing data for chains: {list(missing_chains)}",
"severity": "medium",
"missing_chains": list(missing_chains),
@@ -221,7 +221,7 @@ class CrossChainReputationAggregator:
# Update reputation
reputation.trust_score = new_score * 1000 # Convert to 0-1000 scale
reputation.reputation_level = self._determine_reputation_level(new_score)
reputation.updated_at = datetime.utcnow()
reputation.updated_at = datetime.now(datetime.UTC)
# Create event record
event = ReputationEvent(
@@ -231,7 +231,7 @@ class CrossChainReputationAggregator:
trust_score_before=reputation.trust_score,
trust_score_after=reputation.trust_score,
event_data=update,
occurred_at=datetime.utcnow(),
occurred_at=datetime.now(datetime.UTC),
)
self.session.add(event)
@@ -242,8 +242,8 @@ class CrossChainReputationAggregator:
agent_id=agent_id,
trust_score=new_score * 1000,
reputation_level=self._determine_reputation_level(new_score),
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
updated_at=datetime.now(datetime.UTC),
)
self.session.add(reputation)
@@ -316,7 +316,7 @@ class CrossChainReputationAggregator:
"reputation_distribution": distribution,
"total_transactions": total_transactions,
"success_rate": success_rate,
"last_updated": datetime.utcnow(),
"last_updated": datetime.now(datetime.UTC),
}
except Exception as e:
@@ -430,7 +430,7 @@ class CrossChainReputationAggregator:
aggregation.score_variance = variance
aggregation.score_range = score_range
aggregation.consistency_score = consistency_score
aggregation.last_updated = datetime.utcnow()
aggregation.last_updated = datetime.now(datetime.UTC)
else:
aggregation = CrossChainReputationAggregation(
agent_id=agent_id,
@@ -441,8 +441,8 @@ class CrossChainReputationAggregator:
score_range=score_range,
consistency_score=consistency_score,
verification_status="pending",
created_at=datetime.utcnow(),
last_updated=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
last_updated=datetime.now(datetime.UTC),
)
self.session.add(aggregation)

View File

@@ -3,7 +3,7 @@ Cross-Chain Reputation Engine
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 aitbc import get_logger
@@ -57,8 +57,8 @@ class CrossChainReputationEngine:
agent_id=agent_id,
trust_score=score * 1000, # Convert to 0-1000 scale
reputation_level=self._determine_reputation_level(score),
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
updated_at=datetime.now(datetime.UTC),
)
self.session.add(new_reputation)
@@ -152,8 +152,8 @@ class CrossChainReputationEngine:
agent_id=agent_id,
trust_score=max(0, min(1000, (base_score + impact_score) * 1000)),
reputation_level=self._determine_reputation_level(base_score + impact_score),
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
updated_at=datetime.now(datetime.UTC),
)
self.session.add(reputation)
@@ -164,7 +164,7 @@ class CrossChainReputationEngine:
reputation.trust_score = new_score * 1000
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
event = ReputationEvent(
@@ -174,7 +174,7 @@ class CrossChainReputationEngine:
trust_score_before=reputation.trust_score - (impact_score * 1000),
trust_score_after=reputation.trust_score,
event_data=event_data,
occurred_at=datetime.utcnow(),
occurred_at=datetime.now(datetime.UTC),
)
self.session.add(event)
@@ -195,7 +195,7 @@ class CrossChainReputationEngine:
try:
# Get reputation events for the period
cutoff_date = datetime.utcnow() - timedelta(days=days)
cutoff_date = datetime.now(datetime.UTC) - timedelta(days=days)
stmt = (
select(ReputationEvent)
@@ -295,7 +295,7 @@ class CrossChainReputationEngine:
reputation.trust_score = new_score * 1000
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
if "transaction_count" in transaction_data:
@@ -364,7 +364,7 @@ class CrossChainReputationEngine:
aggregation.score_variance = variance
aggregation.score_range = score_range
aggregation.consistency_score = consistency_score
aggregation.last_updated = datetime.utcnow()
aggregation.last_updated = datetime.now(datetime.UTC)
else:
# Create new aggregation
aggregation = CrossChainReputationAggregation(
@@ -376,8 +376,8 @@ class CrossChainReputationEngine:
score_range=score_range,
consistency_score=consistency_score,
verification_status="pending",
created_at=datetime.utcnow(),
last_updated=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
last_updated=datetime.now(datetime.UTC),
)
self.session.add(aggregation)
@@ -440,7 +440,7 @@ class CrossChainReputationEngine:
"total_transactions": getattr(reputation, "transaction_count", 0),
"success_rate": getattr(reputation, "success_rate", 0.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": {
"aggregated_score": aggregation.aggregated_score if aggregation else 0.0,
"chain_count": aggregation.chain_count if aggregation else 0,

View File

@@ -6,7 +6,7 @@ Provides health monitoring for reinforcement learning frameworks
"""
import sys
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
import psutil
@@ -40,7 +40,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
"status": "healthy",
"service": "adaptive-learning",
"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}",
# System metrics
"system": {
@@ -97,7 +97,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
"status": "unhealthy",
"service": "adaptive-learning",
"port": 8011,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Health check failed",
}
@@ -177,7 +177,7 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
"status": "healthy",
"service": "adaptive-learning",
"port": 8011,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"algorithm_tests": algorithm_tests,
"safety_tests": safety_tests,
"overall_health": (
@@ -196,6 +196,6 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
"status": "unhealthy",
"service": "adaptive-learning",
"port": 8011,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Deep health check failed",
}

View File

@@ -1,6 +1,6 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, UTC
from typing import Annotated
from fastapi import APIRouter, Depends, Header, HTTPException, Request
@@ -55,7 +55,7 @@ async def create_test_miner(
if existing_miner:
# Update existing miner to 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
session.add(existing_miner)
session.commit()
@@ -79,7 +79,7 @@ async def create_test_miner(
session_token=session_token,
status="ONLINE",
inflight=0,
last_heartbeat=datetime.utcnow(),
last_heartbeat=datetime.now(datetime.UTC),
)
session.add(miner)
@@ -223,7 +223,7 @@ async def get_system_status(
# Get system info
import sys
from datetime import datetime
from datetime import datetime, UTC
import psutil
@@ -232,7 +232,7 @@ async def get_system_status(
"memory_percent": psutil.virtual_memory().percent,
"disk_percent": psutil.disk_usage("/").percent,
"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 {
@@ -275,7 +275,7 @@ async def create_agent_network(network_data: dict):
raise HTTPException(status_code=400, detail="Agent list is required")
# 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 = {
"id": network_id,
@@ -284,7 +284,7 @@ async def create_agent_network(network_data: dict):
"agents": network_data["agents"],
"coordination_strategy": network_data.get("coordination", "centralized"),
"status": "active",
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"owner_id": "temp_user",
}
@@ -315,11 +315,11 @@ async def get_execution_receipt(execution_id: str):
{
"coordinator_id": "coordinator_1",
"signature": "0xmock_attestation_1",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
],
"minted_amount": 1000,
"recorded_at": datetime.utcnow().isoformat(),
"recorded_at": datetime.now(datetime.UTC).isoformat(),
"verified": True,
"block_hash": "0xmock_block_hash",
"transaction_hash": "0xmock_tx_hash",

View File

@@ -3,7 +3,7 @@ Agent Identity API Router
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 fastapi import APIRouter, Depends, HTTPException, Query
@@ -85,7 +85,7 @@ async def deactivate_agent_identity(
success = await manager.deactivate_agent_identity(agent_id, reason)
if not success:
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:
raise
except Exception as e:
@@ -164,7 +164,7 @@ async def update_cross_chain_mapping(
"chain_id": chain_id,
"new_address": new_address,
"updated": True,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
except HTTPException:
raise
@@ -255,7 +255,7 @@ async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentit
"agent_id": agent_id,
"chain_id": chain_id,
"balance": str(balance),
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:
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"""
try:
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:
raise HTTPException(status_code=500, detail="Operation failed")

View File

@@ -7,7 +7,7 @@ Advanced Agent Performance API Endpoints
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 fastapi import APIRouter, Depends, HTTPException, Query
@@ -319,7 +319,7 @@ async def adapt_model_to_task(
"success": True,
"model_id": model_id,
"adaptation_results": results,
"adapted_at": datetime.utcnow().isoformat(),
"adapted_at": datetime.now(datetime.UTC).isoformat(),
}
except ValueError as e:
@@ -554,7 +554,7 @@ async def create_capability(
skill_level=capability_request.skill_level,
specialization_areas=capability_request.specialization_areas,
proficiency_score=min(1.0, capability_request.skill_level / 10.0),
created_at=datetime.utcnow(),
created_at=datetime.now(datetime.UTC),
)
session.add(capability)
@@ -718,7 +718,7 @@ async def health_check() -> Dict[str, Any]:
return {
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"version": "1.0.0",
"services": {
"meta_learning_engine": "operational",

View File

@@ -7,7 +7,7 @@ AI Agent API Router for Verifiable AI Agent Orchestration
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
@@ -141,7 +141,7 @@ async def update_workflow(
for field, value in update_data.items():
setattr(workflow, field, value)
workflow.updated_at = datetime.utcnow()
workflow.updated_at = datetime.now(datetime.UTC)
session.commit()
session.refresh(workflow)
@@ -351,7 +351,7 @@ async def cancel_execution(
# Cancel execution
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}")
return {"message": "Execution cancelled successfully"}
@@ -424,7 +424,7 @@ async def get_execution_logs(
@router.get("/test")
async def test_endpoint():
"""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)
@@ -444,7 +444,7 @@ async def create_agent_network(
raise HTTPException(status_code=400, detail="Agent list is required")
# 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 = {
"id": network_id,
@@ -453,7 +453,7 @@ async def create_agent_network(
"agents": network_data["agents"],
"coordination_strategy": network_data.get("coordination", "centralized"),
"status": "active",
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"owner_id": current_user,
}
@@ -487,11 +487,11 @@ async def get_execution_receipt(
{
"coordinator_id": "coordinator_1",
"signature": "0xmock_attestation_1",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
],
"minted_amount": 1000,
"recorded_at": datetime.utcnow().isoformat(),
"recorded_at": datetime.now(datetime.UTC).isoformat(),
"verified": True,
"block_hash": "0xmock_block_hash",
"transaction_hash": "0xmock_tx_hash",

View File

@@ -125,7 +125,7 @@ async def update_security_policy(
if hasattr(policy, field):
setattr(policy, field, value)
policy.updated_at = datetime.utcnow()
policy.updated_at = datetime.now(datetime.UTC)
session.commit()
session.refresh(policy)

View File

@@ -7,7 +7,7 @@ Marketplace Analytics API Endpoints
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 fastapi import APIRouter, Depends, HTTPException, Query
@@ -552,7 +552,7 @@ async def get_key_performance_indicators(
try:
# Get latest metrics for KPIs
end_time = datetime.utcnow()
end_time = datetime.now(datetime.UTC)
if period_type == AnalyticsPeriod.DAILY:
start_time = end_time - timedelta(days=1)

View File

@@ -5,7 +5,7 @@ Bounty Management API
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 fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
@@ -38,7 +38,7 @@ class BountyCreateRequest(BaseModel):
performance_criteria: Dict[str, Any] = Field(default_factory=dict)
min_accuracy: float = Field(default=90.0, ge=0, le=100)
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)
requires_zk_proof: bool = Field(default=True)
auto_verify_threshold: float = Field(default=95.0, ge=0, le=100)
@@ -48,9 +48,9 @@ class BountyCreateRequest(BaseModel):
@validator('deadline')
def validate_deadline(cls, v):
if v <= datetime.utcnow():
if v <= datetime.now(datetime.UTC):
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')
return v
@@ -281,7 +281,7 @@ async def submit_bounty_solution(
if bounty.status != BountyStatus.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")
# Create submission
@@ -519,7 +519,7 @@ async def expire_bounty(
if bounty.status != BountyStatus.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")
# Expire bounty

View File

@@ -7,7 +7,7 @@ Certification and Partnership API Endpoints
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 fastapi import APIRouter, Depends, HTTPException, Query
@@ -626,7 +626,7 @@ async def check_automatic_badges(
"agent_id": agent_id,
"badges_awarded": awarded_badges,
"total_awarded": len(awarded_badges),
"checked_at": datetime.utcnow().isoformat()
"checked_at": datetime.now(datetime.UTC).isoformat()
}
except Exception as e:

View File

@@ -1,6 +1,6 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, UTC
from typing import Annotated
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")
# 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 = {
"id": network_id,
@@ -274,7 +274,7 @@ async def create_agent_network(network_data: dict):
"agents": network_data["agents"],
"coordination_strategy": network_data.get("coordination", "centralized"),
"status": "active",
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"owner_id": "temp_user",
}
@@ -302,11 +302,11 @@ async def get_execution_receipt(execution_id: str):
{
"coordinator_id": "coordinator_1",
"signature": "0xmock_attestation_1",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
],
"minted_amount": 1000,
"recorded_at": datetime.utcnow().isoformat(),
"recorded_at": datetime.now(datetime.UTC).isoformat(),
"verified": True,
"block_hash": "0xmock_block_hash",
"transaction_hash": "0xmock_tx_hash",

View File

@@ -2,7 +2,7 @@
API endpoints for confidential transactions
"""
from datetime import datetime
from datetime import datetime, UTC
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPBearer
@@ -78,13 +78,13 @@ async def create_confidential_transaction(request: ConfidentialTransactionCreate
"""Create a new confidential transaction with optional encryption"""
try:
# Generate transaction ID
transaction_id = f"ctx-{datetime.utcnow().timestamp()}"
transaction_id = f"ctx-{datetime.now(datetime.UTC).timestamp()}"
# Create base transaction
transaction = ConfidentialTransaction(
transaction_id=transaction_id,
job_id=request.job_id,
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
status="created",
amount=request.amount,
pricing=request.pricing,
@@ -173,7 +173,7 @@ async def access_confidential_data(
transaction = ConfidentialTransaction(
transaction_id=transaction_id,
job_id="test-job",
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
status="completed",
confidential=True,
participants=["client-456", "miner-789"],
@@ -200,7 +200,7 @@ async def access_confidential_data(
return ConfidentialAccessResponse(
success=True,
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
@@ -225,7 +225,7 @@ async def access_confidential_data(
)
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:
@@ -249,7 +249,7 @@ async def audit_access_confidential_data(
transaction = ConfidentialTransaction(
transaction_id=transaction_id,
job_id="test-job",
timestamp=datetime.utcnow(),
timestamp=datetime.now(datetime.UTC),
status="completed",
confidential=True,
)
@@ -278,7 +278,7 @@ async def audit_access_confidential_data(
)
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:
@@ -308,7 +308,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
success=True,
participant_id=request.participant_id,
key_version=1, # Would get from storage
registered_at=datetime.utcnow(),
registered_at=datetime.now(datetime.UTC),
error=None,
)
except:
@@ -328,7 +328,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
except KeyManagementError as e:
logger.error(f"Key registration failed: {e}")
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:
logger.error(f"Failed to register key: {e}")

View File

@@ -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
"""
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
from uuid import uuid4
@@ -217,7 +217,7 @@ async def verify_signature(
"message": message,
"address": address,
"chain_id": chain_id,
"verified_at": datetime.utcnow().isoformat(),
"verified_at": datetime.now(datetime.UTC).isoformat(),
}
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"],
"average_processing_time": tx_stats["average_processing_time_minutes"],
"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:
@@ -675,7 +675,7 @@ async def get_cross_chain_config(session: Session = Depends(get_session)) -> dic
"transaction_priorities": transaction_priorities,
"routing_strategies": routing_strategies,
"security_levels": [level.value for level in SecurityLevel],
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:

View File

@@ -3,7 +3,7 @@ Developer Platform API Router
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 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,
"granted_at": certification.granted_at.isoformat(),
"is_valid": True,
"verification_timestamp": datetime.utcnow().isoformat(),
"verification_timestamp": datetime.now(datetime.UTC).isoformat(),
}
except HTTPException:
@@ -746,7 +746,7 @@ async def get_platform_overview(
"regions_covered": 12, # 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:
@@ -785,7 +785,7 @@ async def get_platform_health(session: Session = Depends(get_session)) -> dict[s
"pending_submissions": 8, # Mock data
"system_uptime": "99.9%",
},
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:

View File

@@ -5,7 +5,7 @@ Dynamic Pricing API Router
Provides RESTful endpoints for dynamic pricing management
"""
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -147,7 +147,7 @@ async def get_price_forecast(
accuracy_score=(
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:
@@ -197,7 +197,7 @@ async def set_pricing_strategy(
provider_id=provider_id,
strategy=request.strategy,
constraints=request.constraints,
set_at=datetime.utcnow().isoformat(),
set_at=datetime.now(datetime.UTC).isoformat(),
status="active",
)
@@ -239,7 +239,7 @@ async def get_pricing_strategy(
provider_id=provider_id,
strategy=strategy.value,
constraints=constraints_dict,
set_at=datetime.utcnow().isoformat(),
set_at=datetime.now(datetime.UTC).isoformat(),
status="active",
)
@@ -531,7 +531,7 @@ async def get_price_history(
)
# 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]
# Calculate statistics
@@ -637,7 +637,7 @@ async def bulk_pricing_update(
success_count=success_count,
error_count=error_count,
results=results,
processed_at=datetime.utcnow().isoformat(),
processed_at=datetime.now(datetime.UTC).isoformat(),
)
except Exception as e:
@@ -691,7 +691,7 @@ async def pricing_health_check(
return {
"status": overall_status,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"services": {
"pricing_engine": {
"status": engine_status,
@@ -710,4 +710,4 @@ async def pricing_health_check(
except Exception as 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"}

View File

@@ -5,7 +5,7 @@ Ecosystem Metrics Dashboard API
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 fastapi import APIRouter, Depends, HTTPException
@@ -345,7 +345,7 @@ async def get_ecosystem_alerts(
"alerts": alerts,
"severity": severity,
"count": len(alerts),
"last_updated": datetime.utcnow()
"last_updated": datetime.now(datetime.UTC)
}
except Exception as e:
@@ -422,7 +422,7 @@ async def get_real_time_metrics(
real_time_data = await ecosystem_service.get_real_time_metrics()
return {
"timestamp": datetime.utcnow(),
"timestamp": datetime.now(datetime.UTC),
"metrics": real_time_data,
"update_frequency": "60s" # Update frequency in seconds
}
@@ -442,7 +442,7 @@ async def get_kpi_dashboard(
return {
"kpis": kpi_data,
"last_updated": datetime.utcnow(),
"last_updated": datetime.now(datetime.UTC),
"refresh_interval": 300 # 5 minutes
}

View File

@@ -4,7 +4,7 @@ Bitcoin Exchange Router for AITBC
import time
import uuid
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
@@ -214,7 +214,7 @@ async def monitor_payment(payment_id: str):
@router.get("/agents/test")
async def test_agent_endpoint():
"""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)
@@ -230,7 +230,7 @@ async def create_agent_network(network_data: dict):
raise HTTPException(status_code=400, detail="Agent list is required")
# 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 = {
"id": network_id,
@@ -239,7 +239,7 @@ async def create_agent_network(network_data: dict):
"agents": network_data["agents"],
"coordination_strategy": network_data.get("coordination", "centralized"),
"status": "active",
"created_at": datetime.utcnow().isoformat(),
"created_at": datetime.now(datetime.UTC).isoformat(),
"owner_id": "temp_user",
}
@@ -269,11 +269,11 @@ async def get_execution_receipt(execution_id: str):
{
"coordinator_id": "coordinator_1",
"signature": "0xmock_attestation_1",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
],
"minted_amount": 1000,
"recorded_at": datetime.utcnow().isoformat(),
"recorded_at": datetime.now(datetime.UTC).isoformat(),
"verified": True,
"block_hash": "0xmock_block_hash",
"transaction_hash": "0xmock_tx_hash",

View File

@@ -3,7 +3,7 @@ Global Marketplace API Router
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 fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
@@ -585,7 +585,7 @@ async def get_global_marketplace_health(
recent_transactions = (
session.execute(
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()
or 0
@@ -608,7 +608,7 @@ async def get_global_marketplace_health(
"recent_24h": recent_transactions,
"activity_rate": transaction_activity,
},
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:

View File

@@ -3,7 +3,7 @@ Global Marketplace Integration API Router
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 fastapi import APIRouter, Depends, HTTPException, Query
@@ -350,7 +350,7 @@ async def get_marketplace_integration_analytics(
"active_regions": len(active_regions),
"supported_chains": len(supported_chains),
"integration_config": integration_service.integration_config,
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:
@@ -394,7 +394,7 @@ async def get_integration_status(
"auto_bridge_execution": config["auto_bridge_execution"],
"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:
@@ -463,7 +463,7 @@ async def get_integration_config(
}
for priority in TransactionPriority
},
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
except Exception as e:
@@ -492,7 +492,7 @@ async def update_integration_config(
return {
"updated_config": integration_service.integration_config,
"updated_keys": list(config_updates.keys()),
"updated_at": datetime.utcnow().isoformat(),
"updated_at": datetime.now(datetime.UTC).isoformat(),
}
except ValueError as e:
@@ -554,7 +554,7 @@ async def get_integration_health(
if health_status["issues"]:
health_status["overall_status"] = "degraded"
health_status["last_updated"] = datetime.utcnow().isoformat()
health_status["last_updated"] = datetime.now(datetime.UTC).isoformat()
return health_status
@@ -571,7 +571,7 @@ async def run_integration_diagnostics(
"""Run integration diagnostics"""
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":
# Test services
@@ -617,9 +617,9 @@ async def run_integration_diagnostics(
"configuration": integration_service.integration_config,
}
diagnostics["completed_at"] = datetime.utcnow().isoformat()
diagnostics["completed_at"] = datetime.now(datetime.UTC).isoformat()
diagnostics["duration_seconds"] = (
datetime.utcnow() - datetime.fromisoformat(diagnostics["started_at"])
datetime.now(datetime.UTC) - datetime.fromisoformat(diagnostics["started_at"])
).total_seconds()
return diagnostics

View File

@@ -3,7 +3,7 @@ Enhanced Governance API Router
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 fastapi import APIRouter, Depends, HTTPException, Query
@@ -433,7 +433,7 @@ async def check_compliance_status(
"jurisdiction": jurisdiction,
"is_compliant": True,
"compliance_level": "full",
"last_check": datetime.utcnow().isoformat(),
"last_check": datetime.now(datetime.UTC).isoformat(),
"requirements_met": {
"kyc_verified": True,
"aml_screened": True,
@@ -441,7 +441,7 @@ async def check_compliance_status(
"minimum_stake_met": True,
},
"restrictions": [],
"next_review_date": (datetime.utcnow() + timedelta(days=365)).isoformat(),
"next_review_date": (datetime.now(datetime.UTC) + timedelta(days=365)).isoformat(),
}
return compliance_status
@@ -490,7 +490,7 @@ async def get_governance_system_health(
"treasury_balance": analytics["treasury"]["total_allocations"],
"staking_pools": analytics["staking"]["active_pools"],
},
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
return health_data
@@ -539,7 +539,7 @@ async def get_governance_platform_status(
"treasury_utilization": f"{analytics['treasury']['utilization_rate']}%",
"staking_apy": f"{analytics['staking']['average_apy']}%",
},
"last_updated": datetime.utcnow().isoformat(),
"last_updated": datetime.now(datetime.UTC).isoformat(),
}
return status_data

View File

@@ -7,7 +7,7 @@ Provides health monitoring for CUDA-optimized multi-modal processing
import subprocess
import sys
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
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",
"service": "gpu-multimodal",
"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}",
# System metrics
"system": {
@@ -86,7 +86,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
"status": "unhealthy",
"service": "gpu-multimodal",
"port": 8010,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"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",
"service": "gpu-multimodal",
"port": 8010,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"gpu_info": gpu_info,
"cuda_tests": cuda_tests,
"overall_health": (
@@ -161,7 +161,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
"status": "unhealthy",
"service": "gpu-multimodal",
"port": 8010,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Deep health check failed",
}

View File

@@ -6,7 +6,7 @@ Provides health monitoring for royalties, licensing, verification, and analytics
"""
import sys
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
import psutil
@@ -41,7 +41,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
"status": "healthy",
"service": "marketplace-enhanced",
"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}",
# System metrics
"system": {
@@ -98,7 +98,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
"status": "unhealthy",
"service": "marketplace-enhanced",
"port": 8002,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Health check failed",
}
@@ -173,7 +173,7 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
"status": "healthy",
"service": "marketplace-enhanced",
"port": 8002,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"feature_tests": feature_tests,
"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",
"service": "marketplace-enhanced",
"port": 8002,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Deep health check failed",
}

View File

@@ -5,7 +5,7 @@ GPU marketplace endpoints backed by persistent SQLModel tables.
"""
import statistics
from datetime import datetime, timedelta
from datetime import datetime, UTC, timedelta
from typing import Any
from uuid import uuid4
@@ -157,7 +157,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
# Create GPU registry record
import uuid
from datetime import datetime
from datetime import datetime, UTC
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=[],
average_rating=0.0,
total_reviews=0,
created_at=datetime.utcnow()
created_at=datetime.now(datetime.UTC)
)
session.add(gpu_record)
@@ -259,9 +259,9 @@ async def buy_gpu(
)
# 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)
# Calculate total cost
@@ -411,7 +411,7 @@ async def sell_gpu(
"listing_price": request.listing_price,
"status": "listed",
"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)"
)
start_time = datetime.utcnow()
start_time = datetime.now(datetime.UTC)
end_time = start_time + timedelta(hours=request.duration_hours)
# Validate booking end time is in the future
@@ -593,7 +593,7 @@ async def submit_ollama_task(
)
task_id = f"task_{uuid4().hex[:10]}"
submitted_at = datetime.utcnow().isoformat() + "Z"
submitted_at = datetime.now(datetime.UTC).isoformat() + "Z"
return {
"task_id": task_id,
@@ -619,7 +619,7 @@ async def send_payment(
)
tx_id = f"tx_{uuid4().hex[:10]}"
processed_at = datetime.utcnow().isoformat() + "Z"
processed_at = datetime.now(datetime.UTC).isoformat() + "Z"
return {
"tx_id": tx_id,
@@ -920,7 +920,7 @@ async def get_pricing(
},
"individual_gpu_pricing": dynamic_prices,
"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"),
"bid_amount": request.get("bid_amount"),
"duration_hours": request.get("duration_hours"),
"timestamp": datetime.utcnow().isoformat() + "Z",
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
}

View File

@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC
from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
@@ -87,7 +87,7 @@ async def submit_result(
metrics = dict(req.metrics or {})
duration_ms = metrics.get("duration_ms")
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
receipt = receipt_service.create_receipt(job, miner_id, req.result, metrics)

View File

@@ -6,7 +6,7 @@ Provides health monitoring for specialized modality optimization strategies
"""
import sys
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
import psutil
@@ -33,7 +33,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
"status": "healthy",
"service": "modality-optimization",
"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}",
# System metrics
"system": {
@@ -86,7 +86,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
"status": "unhealthy",
"service": "modality-optimization",
"port": 8004,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Health check failed",
}
@@ -148,7 +148,7 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
"status": "healthy",
"service": "modality-optimization",
"port": 8004,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"optimization_tests": optimization_tests,
"overall_health": (
"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",
"service": "modality-optimization",
"port": 8004,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Deep health check failed",
}

View File

@@ -4,7 +4,7 @@ Provides a unified dashboard for all 6 enhanced services
"""
import asyncio
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
from fastapi import APIRouter
@@ -75,7 +75,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
overall_metrics = calculate_overall_metrics(health_data)
dashboard_data = {
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"overall_status": overall_metrics["overall_status"],
"services": health_data,
"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"]),
"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"]),
"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}")
return {
"error": "Failed to generate dashboard",
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"services": SERVICES,
"overall_status": "error",
"summary": {
@@ -106,7 +106,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
"healthy_services": 0,
"degraded_services": 0,
"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:
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():
health = health_data.get(service_id, {})
@@ -136,7 +136,7 @@ async def services_summary() -> dict[str, Any]:
except Exception as 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")
@@ -156,7 +156,7 @@ async def system_metrics() -> dict[str, Any]:
network = psutil.net_io_counters()
metrics = {
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"system": {
"cpu_percent": cpu_percent,
"cpu_count": psutil.cpu_count(),
@@ -184,7 +184,7 @@ async def system_metrics() -> dict[str, Any]:
except Exception as 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]:
@@ -206,7 +206,7 @@ async def collect_all_health_data() -> dict[str, Any]:
health_data[service_id] = {
"status": "unhealthy",
"error": str(result),
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
}
else:
health_data[service_id] = result
@@ -225,7 +225,7 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
return {
"status": "healthy",
"response_time": 0.1, # Placeholder - would be measured
"last_check": datetime.utcnow().isoformat(),
"last_check": datetime.now(datetime.UTC).isoformat(),
"details": response,
}
except NetworkError as e:
@@ -233,11 +233,11 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
return {
"status": "unhealthy",
"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:
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]:

View File

@@ -6,7 +6,7 @@ Provides health monitoring for multi-modal processing capabilities
"""
import sys
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
import psutil
@@ -38,7 +38,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
"status": "healthy",
"service": "multimodal-agent",
"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}",
# System metrics
"system": {
@@ -81,7 +81,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
"status": "unhealthy",
"service": "multimodal-agent",
"port": 8002,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Health check failed",
}
@@ -129,7 +129,7 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
"status": "healthy",
"service": "multimodal-agent",
"port": 8002,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"modality_tests": modality_tests,
"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",
"service": "multimodal-agent",
"port": 8002,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Deep health check failed",
}

View File

@@ -42,13 +42,13 @@ async def detailed_health():
try:
import psutil
import logging
from datetime import datetime
from datetime import datetime, UTC
return {
"status": "healthy",
"service": "openclaw-enhanced",
"port": 8014,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"python_version": "3.13.5",
"system": {
"cpu_percent": psutil.cpu_percent(),

View File

@@ -6,7 +6,7 @@ Provides health monitoring for agent orchestration, edge computing, and ecosyste
"""
import sys
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
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",
"service": "openclaw-enhanced",
"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}",
# System metrics
"system": {
@@ -95,7 +95,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
"status": "unhealthy",
"service": "openclaw-enhanced",
"port": 8007,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"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",
"service": "openclaw-enhanced",
"port": 8007,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"feature_tests": feature_tests,
"edge_computing": edge_status,
"overall_health": (
@@ -178,7 +178,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
"status": "unhealthy",
"service": "openclaw-enhanced",
"port": 8007,
"timestamp": datetime.utcnow().isoformat(),
"timestamp": datetime.now(datetime.UTC).isoformat(),
"error": "Deep health check failed",
}

View File

@@ -8,7 +8,7 @@ Partner Router - Third-party integration management
import hashlib
import secrets
from datetime import datetime
from datetime import datetime, UTC
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
@@ -91,7 +91,7 @@ async def register_partner(partner: PartnerRegister, session: Annotated[Session,
"api_key": api_key,
"api_secret_hash": hashlib.sha256(api_secret.encode()).hexdigest(),
"rate_limit": rate_limits.get(partner.integration_type, rate_limits["other"]),
"created_at": datetime.utcnow(),
"created_at": datetime.now(datetime.UTC),
"status": "active",
}
@@ -162,7 +162,7 @@ async def create_webhook(
"events": webhook.events,
"secret": webhook.secret,
"status": "active",
"created_at": datetime.utcnow(),
"created_at": datetime.now(datetime.UTC),
}
return WebhookResponse(

Some files were not shown because too many files have changed in this diff Show More